Code cleanup: use bool
[blender-staging.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_threads.h"
45
46 #include "DNA_meshdata_types.h"
47 #include "DNA_object_types.h"
48 #include "DNA_scene_types.h"
49 #include "DNA_mesh_types.h"
50
51 #include "BKE_ccg.h"
52 #include "BKE_cdderivedmesh.h"
53 #include "BKE_context.h"
54 #include "BKE_depsgraph.h"
55 #include "BKE_modifier.h"
56 #include "BKE_multires.h"
57 #include "BKE_paint.h"
58 #include "BKE_key.h"
59 #include "BKE_mesh.h"
60 #include "BKE_subsurf.h"
61
62 #include "WM_api.h"
63 #include "WM_types.h"
64
65 #include "GPU_buffers.h"
66
67 #include "ED_sculpt.h"
68 #include "bmesh.h"
69 #include "paint_intern.h"
70 #include "sculpt_intern.h"
71
72 /************************** Undo *************************/
73
74 static void update_cb(PBVHNode *node, void *rebuild)
75 {
76         BKE_pbvh_node_mark_update(node);
77         if (*((int *)rebuild))
78                 BKE_pbvh_node_mark_rebuild_draw(node);
79         BKE_pbvh_node_fully_hidden_set(node, 0);
80 }
81
82 static void sculpt_undo_restore_deformed(const SculptSession *ss,
83                                          SculptUndoNode *unode,
84                                          int uindex, int oindex,
85                                          float coord[3])
86 {
87         if (unode->orig_co) {
88                 swap_v3_v3(coord, unode->orig_co[uindex]);
89                 copy_v3_v3(unode->co[uindex], ss->deform_cos[oindex]);
90         }
91         else {
92                 swap_v3_v3(coord, unode->co[uindex]);
93         }
94 }
95
96 static int sculpt_undo_restore_coords(bContext *C, DerivedMesh *dm, SculptUndoNode *unode)
97 {
98         Scene *scene = CTX_data_scene(C);
99         Sculpt *sd = CTX_data_tool_settings(C)->sculpt;
100         Object *ob = CTX_data_active_object(C);
101         SculptSession *ss = ob->sculpt;
102         MVert *mvert;
103         int *index, i, j;
104         
105         if (unode->maxvert) {
106                 /* regular mesh restore */
107
108                 if (ss->kb && strcmp(ss->kb->name, unode->shapeName)) {
109                         /* shape key has been changed before calling undo operator */
110
111                         Key *key = BKE_key_from_object(ob);
112                         KeyBlock *kb = key ? BKE_keyblock_find_name(key, unode->shapeName) : NULL;
113
114                         if (kb) {
115                                 ob->shapenr = BLI_findindex(&key->block, kb) + 1;
116
117                                 sculpt_update_mesh_elements(scene, sd, ob, 0, false);
118                                 WM_event_add_notifier(C, NC_OBJECT | ND_DATA, ob);
119                         }
120                         else {
121                                 /* key has been removed -- skip this undo node */
122                                 return 0;
123                         }
124                 }
125
126                 index = unode->index;
127                 mvert = ss->mvert;
128
129                 if (ss->kb) {
130                         float (*vertCos)[3];
131                         vertCos = BKE_key_convert_to_vertcos(ob, ss->kb);
132
133                         for (i = 0; i < unode->totvert; i++) {
134                                 if (ss->modifiers_active) {
135                                         sculpt_undo_restore_deformed(ss, unode, i, index[i], vertCos[index[i]]);
136                                 }
137                                 else {
138                                         if (unode->orig_co) swap_v3_v3(vertCos[index[i]], unode->orig_co[i]);
139                                         else swap_v3_v3(vertCos[index[i]], unode->co[i]);
140                                 }
141                         }
142
143                         /* propagate new coords to keyblock */
144                         sculpt_vertcos_to_key(ob, ss->kb, vertCos);
145
146                         /* pbvh uses it's own mvert array, so coords should be */
147                         /* propagated to pbvh here */
148                         BKE_pbvh_apply_vertCos(ss->pbvh, vertCos);
149
150                         MEM_freeN(vertCos);
151                 }
152                 else {
153                         for (i = 0; i < unode->totvert; i++) {
154                                 if (ss->modifiers_active) {
155                                         sculpt_undo_restore_deformed(ss, unode, i, index[i], mvert[index[i]].co);
156                                 }
157                                 else {
158                                         if (unode->orig_co) swap_v3_v3(mvert[index[i]].co, unode->orig_co[i]);
159                                         else swap_v3_v3(mvert[index[i]].co, unode->co[i]);
160                                 }
161                                 mvert[index[i]].flag |= ME_VERT_PBVH_UPDATE;
162                         }
163                 }
164         }
165         else if (unode->maxgrid && dm->getGridData) {
166                 /* multires restore */
167                 CCGElem **grids, *grid;
168                 CCGKey key;
169                 float (*co)[3];
170                 int gridsize;
171
172                 grids = dm->getGridData(dm);
173                 gridsize = dm->getGridSize(dm);
174                 dm->getGridKey(dm, &key);
175
176                 co = unode->co;
177                 for (j = 0; j < unode->totgrid; j++) {
178                         grid = grids[unode->grids[j]];
179
180                         for (i = 0; i < gridsize * gridsize; i++, co++)
181                                 swap_v3_v3(CCG_elem_offset_co(&key, grid, i), co[0]);
182                 }
183         }
184
185         return 1;
186 }
187
188 static int sculpt_undo_restore_hidden(bContext *C, DerivedMesh *dm,
189                                       SculptUndoNode *unode)
190 {
191         Object *ob = CTX_data_active_object(C);
192         SculptSession *ss = ob->sculpt;
193         int i;
194
195         if (unode->maxvert) {
196                 MVert *mvert = ss->mvert;
197                 
198                 for (i = 0; i < unode->totvert; i++) {
199                         MVert *v = &mvert[unode->index[i]];
200                         int uval = BLI_BITMAP_GET(unode->vert_hidden, i);
201
202                         BLI_BITMAP_MODIFY(unode->vert_hidden, i,
203                                           v->flag & ME_HIDE);
204                         if (uval)
205                                 v->flag |= ME_HIDE;
206                         else
207                                 v->flag &= ~ME_HIDE;
208                         
209                         v->flag |= ME_VERT_PBVH_UPDATE;
210                 }
211         }
212         else if (unode->maxgrid && dm->getGridData) {
213                 BLI_bitmap **grid_hidden = dm->getGridHidden(dm);
214                 
215                 for (i = 0; i < unode->totgrid; i++) {
216                         SWAP(BLI_bitmap *,
217                              unode->grid_hidden[i],
218                              grid_hidden[unode->grids[i]]);
219                         
220                 }
221         }
222
223         return 1;
224 }
225
226 static int sculpt_undo_restore_mask(bContext *C, DerivedMesh *dm, SculptUndoNode *unode)
227 {
228         Object *ob = CTX_data_active_object(C);
229         SculptSession *ss = ob->sculpt;
230         MVert *mvert;
231         float *vmask;
232         int *index, i, j;
233         
234         if (unode->maxvert) {
235                 /* regular mesh restore */
236
237                 index = unode->index;
238                 mvert = ss->mvert;
239                 vmask = ss->vmask;
240
241                 for (i = 0; i < unode->totvert; i++) {
242                         SWAP(float, vmask[index[i]], unode->mask[i]);
243                         mvert[index[i]].flag |= ME_VERT_PBVH_UPDATE;
244                 }
245         }
246         else if (unode->maxgrid && dm->getGridData) {
247                 /* multires restore */
248                 CCGElem **grids, *grid;
249                 CCGKey key;
250                 float *mask;
251                 int gridsize;
252
253                 grids = dm->getGridData(dm);
254                 gridsize = dm->getGridSize(dm);
255                 dm->getGridKey(dm, &key);
256
257                 mask = unode->mask;
258                 for (j = 0; j < unode->totgrid; j++) {
259                         grid = grids[unode->grids[j]];
260
261                         for (i = 0; i < gridsize * gridsize; i++, mask++)
262                                 SWAP(float, *CCG_elem_offset_mask(&key, grid, i), *mask);
263                 }
264         }
265
266         return 1;
267 }
268
269 static void sculpt_undo_bmesh_restore_generic(bContext *C,
270                                               SculptUndoNode *unode,
271                                               Object *ob,
272                                               SculptSession *ss)
273 {
274         if (unode->applied) {
275                 BM_log_undo(ss->bm, ss->bm_log);
276                 unode->applied = false;
277         }
278         else {
279                 BM_log_redo(ss->bm, ss->bm_log);
280                 unode->applied = true;
281         }
282
283         if (ELEM(unode->type, SCULPT_UNDO_MASK, SCULPT_UNDO_MASK)) {
284                 int i, totnode;
285                 PBVHNode **nodes;
286
287 #ifdef _OPENMP
288                 Sculpt *sd = CTX_data_tool_settings(C)->sculpt;
289 #else
290                 (void)C;
291 #endif
292
293                 BKE_pbvh_search_gather(ss->pbvh, NULL, NULL, &nodes, &totnode);
294
295 #pragma omp parallel for schedule(guided) if (sd->flags & SCULPT_USE_OPENMP)
296                 for (i = 0; i < totnode; i++) {
297                         BKE_pbvh_node_mark_redraw(nodes[i]);
298                 }
299
300                 if (nodes)
301                         MEM_freeN(nodes);
302         }
303         else {
304                 /* A bit lame, but for now just recreate the PBVH. The alternative
305                  * is to store changes to the PBVH in the undo stack. */
306                 sculpt_pbvh_clear(ob);
307         }
308 }
309
310 /* Create empty sculpt BMesh and enable logging */
311 static void sculpt_undo_bmesh_enable(Object *ob,
312                                      SculptUndoNode *unode)
313 {
314         SculptSession *ss = ob->sculpt;
315         Mesh *me = ob->data;
316
317         sculpt_pbvh_clear(ob);
318
319         /* Create empty BMesh and enable logging */
320         ss->bm = BM_mesh_create(&bm_mesh_allocsize_default);
321         BM_data_layer_add(ss->bm, &ss->bm->vdata, CD_PAINT_MASK);
322         me->flag |= ME_SCULPT_DYNAMIC_TOPOLOGY;
323
324         /* Restore the BMLog using saved entries */
325         ss->bm_log = BM_log_from_existing_entries_create(ss->bm,
326                                                          unode->bm_entry);
327 }
328
329 static void sculpt_undo_bmesh_restore_begin(bContext *C,
330                                             SculptUndoNode *unode,
331                                             Object *ob,
332                                             SculptSession *ss)
333 {
334         if (unode->applied) {
335                 sculpt_dynamic_topology_disable(C, unode);
336                 unode->applied = false;
337         }
338         else {
339                 sculpt_undo_bmesh_enable(ob, unode);
340
341                 /* Restore the mesh from the first log entry */
342                 BM_log_redo(ss->bm, ss->bm_log);
343
344                 unode->applied = true;
345         }
346 }
347
348 static void sculpt_undo_bmesh_restore_end(bContext *C,
349                                           SculptUndoNode *unode,
350                                           Object *ob,
351                                           SculptSession *ss)
352 {
353         if (unode->applied) {
354                 sculpt_undo_bmesh_enable(ob, unode);
355
356                 /* Restore the mesh from the last log entry */
357                 BM_log_undo(ss->bm, ss->bm_log);
358
359                 unode->applied = false;
360         }
361         else {
362                 /* Disable dynamic topology sculpting */
363                 sculpt_dynamic_topology_disable(C, NULL);
364                 unode->applied = true;
365         }
366 }
367
368 /* Handle all dynamic-topology updates
369  *
370  * Returns true if this was a dynamic-topology undo step, otherwise
371  * returns false to indicate the non-dyntopo code should run. */
372 static int sculpt_undo_bmesh_restore(bContext *C,
373                                      SculptUndoNode *unode,
374                                      Object *ob,
375                                      SculptSession *ss)
376 {
377         switch (unode->type) {
378                 case SCULPT_UNDO_DYNTOPO_BEGIN:
379                         sculpt_undo_bmesh_restore_begin(C, unode, ob, ss);
380                         return true;
381
382                 case SCULPT_UNDO_DYNTOPO_END:
383                         sculpt_undo_bmesh_restore_end(C, unode, ob, ss);
384                         return true;
385
386                 default:
387                         if (ss->bm_log) {
388                                 sculpt_undo_bmesh_restore_generic(C, unode, ob, ss);
389                                 return true;
390                         }
391                         break;
392         }
393
394         return false;
395 }
396
397 static void sculpt_undo_restore(bContext *C, ListBase *lb)
398 {
399         Scene *scene = CTX_data_scene(C);
400         Sculpt *sd = CTX_data_tool_settings(C)->sculpt;
401         Object *ob = CTX_data_active_object(C);
402         DerivedMesh *dm;
403         SculptSession *ss = ob->sculpt;
404         SculptUndoNode *unode;
405         bool update = false, rebuild = false;
406         bool need_mask = false;
407
408         for (unode = lb->first; unode; unode = unode->next) {
409                 if (strcmp(unode->idname, ob->id.name) == 0) {
410                         if (unode->type == SCULPT_UNDO_MASK) {
411                                 /* is possible that we can't do the mask undo (below)
412                                  * because of the vertex count */
413                                 need_mask = true;
414                                 break;
415                         }
416                 }
417         }
418
419         sculpt_update_mesh_elements(scene, sd, ob, 0, need_mask);
420
421         /* call _after_ sculpt_update_mesh_elements() which may update 'ob->derivedFinal' */
422         dm = mesh_get_derived_final(scene, ob, 0);
423
424         if (lb->first && sculpt_undo_bmesh_restore(C, lb->first, ob, ss))
425                 return;
426
427         for (unode = lb->first; unode; unode = unode->next) {
428                 if (!(strcmp(unode->idname, ob->id.name) == 0))
429                         continue;
430
431                 /* check if undo data matches current data well enough to
432                  * continue */
433                 if (unode->maxvert) {
434                         if (ss->totvert != unode->maxvert)
435                                 continue;
436                 }
437                 else if (unode->maxgrid && dm->getGridData) {
438                         if ((dm->getNumGrids(dm) != unode->maxgrid) ||
439                             (dm->getGridSize(dm) != unode->gridsize))
440                         {
441                                 continue;
442                         }
443                 }
444
445                 switch (unode->type) {
446                         case SCULPT_UNDO_COORDS:
447                                 if (sculpt_undo_restore_coords(C, dm, unode))
448                                         update = true;
449                                 break;
450                         case SCULPT_UNDO_HIDDEN:
451                                 if (sculpt_undo_restore_hidden(C, dm, unode))
452                                         rebuild = true;
453                                 break;
454                         case SCULPT_UNDO_MASK:
455                                 if (sculpt_undo_restore_mask(C, dm, unode))
456                                         update = true;
457                                 break;
458
459                         case SCULPT_UNDO_DYNTOPO_BEGIN:
460                         case SCULPT_UNDO_DYNTOPO_END:
461                         case SCULPT_UNDO_DYNTOPO_SYMMETRIZE:
462                                 BLI_assert(!"Dynamic topology should've already been handled");
463                                 break;
464                 }
465         }
466
467         if (update || rebuild) {
468                 int tag_update = 0;
469                 /* we update all nodes still, should be more clever, but also
470                  * needs to work correct when exiting/entering sculpt mode and
471                  * the nodes get recreated, though in that case it could do all */
472                 BKE_pbvh_search_callback(ss->pbvh, NULL, NULL, update_cb, &rebuild);
473                 BKE_pbvh_update(ss->pbvh, PBVH_UpdateBB | PBVH_UpdateOriginalBB | PBVH_UpdateRedraw, NULL);
474
475                 if (sculpt_multires_active(scene, ob)) {
476                         if (rebuild)
477                                 multires_mark_as_modified(ob, MULTIRES_HIDDEN_MODIFIED);
478                         else
479                                 multires_mark_as_modified(ob, MULTIRES_COORDS_MODIFIED);
480                 }
481
482                 tag_update = ((Mesh *)ob->data)->id.us > 1;
483
484                 if (ss->modifiers_active) {
485                         Mesh *mesh = ob->data;
486                         BKE_mesh_calc_normals_tessface(mesh->mvert, mesh->totvert,
487                                                        mesh->mface, mesh->totface, NULL);
488
489                         free_sculptsession_deformMats(ss);
490                         tag_update |= 1;
491                 }
492
493                 if (tag_update) {
494                         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
495                 }
496                 else {
497                         sculpt_update_object_bounding_box(ob);
498                 }
499
500                 /* for non-PBVH drawing, need to recreate VBOs */
501                 GPU_drawobject_free(ob->derivedFinal);
502         }
503 }
504
505 static void sculpt_undo_free(ListBase *lb)
506 {
507         SculptUndoNode *unode;
508         int i;
509
510         for (unode = lb->first; unode; unode = unode->next) {
511                 if (unode->co)
512                         MEM_freeN(unode->co);
513                 if (unode->no)
514                         MEM_freeN(unode->no);
515                 if (unode->index)
516                         MEM_freeN(unode->index);
517                 if (unode->grids)
518                         MEM_freeN(unode->grids);
519                 if (unode->orig_co)
520                         MEM_freeN(unode->orig_co);
521                 if (unode->vert_hidden)
522                         MEM_freeN(unode->vert_hidden);
523                 if (unode->grid_hidden) {
524                         for (i = 0; i < unode->totgrid; i++) {
525                                 if (unode->grid_hidden[i])
526                                         MEM_freeN(unode->grid_hidden[i]);
527                         }
528                         MEM_freeN(unode->grid_hidden);
529                 }
530                 if (unode->mask)
531                         MEM_freeN(unode->mask);
532                 if (unode->bm_entry) {
533                         BM_log_entry_drop(unode->bm_entry);
534                 }
535                 if (unode->bm_enter_totvert)
536                         CustomData_free(&unode->bm_enter_vdata, unode->bm_enter_totvert);
537                 if (unode->bm_enter_totedge)
538                         CustomData_free(&unode->bm_enter_edata, unode->bm_enter_totedge);
539                 if (unode->bm_enter_totloop)
540                         CustomData_free(&unode->bm_enter_ldata, unode->bm_enter_totloop);
541                 if (unode->bm_enter_totpoly)
542                         CustomData_free(&unode->bm_enter_pdata, unode->bm_enter_totpoly);
543         }
544 }
545
546 SculptUndoNode *sculpt_undo_get_node(PBVHNode *node)
547 {
548         ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_MESH);
549
550         if (!lb) {
551                 return NULL;
552         }
553
554         return BLI_findptr(lb, node, offsetof(SculptUndoNode, node));
555 }
556
557 static void sculpt_undo_alloc_and_store_hidden(PBVH *pbvh,
558                                                SculptUndoNode *unode)
559 {
560         PBVHNode *node = unode->node;
561         BLI_bitmap **grid_hidden;
562         int i, *grid_indices, totgrid;
563
564         grid_hidden = BKE_pbvh_grid_hidden(pbvh);
565
566         BKE_pbvh_node_get_grids(pbvh, node, &grid_indices, &totgrid,
567                                 NULL, NULL, NULL, NULL);
568                         
569         unode->grid_hidden = MEM_mapallocN(sizeof(*unode->grid_hidden) * totgrid,
570                                            "unode->grid_hidden");
571                 
572         for (i = 0; i < totgrid; i++) {
573                 if (grid_hidden[grid_indices[i]])
574                         unode->grid_hidden[i] = MEM_dupallocN(grid_hidden[grid_indices[i]]);
575                 else
576                         unode->grid_hidden[i] = NULL;
577         }
578 }
579
580 static SculptUndoNode *sculpt_undo_alloc_node(Object *ob, PBVHNode *node,
581                                               SculptUndoType type)
582 {
583         ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_MESH);
584         SculptUndoNode *unode;
585         SculptSession *ss = ob->sculpt;
586         int totvert, allvert, totgrid, maxgrid, gridsize, *grids;
587         
588         unode = MEM_callocN(sizeof(SculptUndoNode), "SculptUndoNode");
589         BLI_strncpy(unode->idname, ob->id.name, sizeof(unode->idname));
590         unode->type = type;
591         unode->node = node;
592
593         if (node) {
594                 BKE_pbvh_node_num_verts(ss->pbvh, node, &totvert, &allvert);
595                 BKE_pbvh_node_get_grids(ss->pbvh, node, &grids, &totgrid,
596                                         &maxgrid, &gridsize, NULL, NULL);
597
598                 unode->totvert = totvert;
599         }
600         else
601                 maxgrid = 0;
602         
603         /* we will use this while sculpting, is mapalloc slow to access then? */
604
605         /* general TODO, fix count_alloc */
606         switch (type) {
607                 case SCULPT_UNDO_COORDS:
608                         unode->co = MEM_mapallocN(sizeof(float) * 3 * allvert, "SculptUndoNode.co");
609                         unode->no = MEM_mapallocN(sizeof(short) * 3 * allvert, "SculptUndoNode.no");
610                         undo_paint_push_count_alloc(UNDO_PAINT_MESH,
611                                                     (sizeof(float) * 3 +
612                                                      sizeof(short) * 3 +
613                                                      sizeof(int)) * allvert);
614                         break;
615                 case SCULPT_UNDO_HIDDEN:
616                         if (maxgrid)
617                                 sculpt_undo_alloc_and_store_hidden(ss->pbvh, unode);
618                         else
619                                 unode->vert_hidden = BLI_BITMAP_NEW(allvert, "SculptUndoNode.vert_hidden");
620                 
621                         break;
622                 case SCULPT_UNDO_MASK:
623                         unode->mask = MEM_mapallocN(sizeof(float) * allvert, "SculptUndoNode.mask");
624                         undo_paint_push_count_alloc(UNDO_PAINT_MESH, (sizeof(float) * sizeof(int)) * allvert);
625                         break;
626                 case SCULPT_UNDO_DYNTOPO_BEGIN:
627                 case SCULPT_UNDO_DYNTOPO_END:
628                 case SCULPT_UNDO_DYNTOPO_SYMMETRIZE:
629                         BLI_assert(!"Dynamic topology should've already been handled");
630                         break;
631         }
632         
633         BLI_addtail(lb, unode);
634
635         if (maxgrid) {
636                 /* multires */
637                 unode->maxgrid = maxgrid;
638                 unode->totgrid = totgrid;
639                 unode->gridsize = gridsize;
640                 unode->grids = MEM_mapallocN(sizeof(int) * totgrid, "SculptUndoNode.grids");
641         }
642         else {
643                 /* regular mesh */
644                 unode->maxvert = ss->totvert;
645                 unode->index = MEM_mapallocN(sizeof(int) * allvert, "SculptUndoNode.index");
646         }
647
648         if (ss->modifiers_active)
649                 unode->orig_co = MEM_callocN(allvert * sizeof(*unode->orig_co), "undoSculpt orig_cos");
650
651         return unode;
652 }
653
654 static void sculpt_undo_store_coords(Object *ob, SculptUndoNode *unode)
655 {
656         SculptSession *ss = ob->sculpt;
657         PBVHVertexIter vd;
658
659         BKE_pbvh_vertex_iter_begin(ss->pbvh, unode->node, vd, PBVH_ITER_ALL)
660         {
661                 copy_v3_v3(unode->co[vd.i], vd.co);
662                 if (vd.no) copy_v3_v3_short(unode->no[vd.i], vd.no);
663                 else normal_float_to_short_v3(unode->no[vd.i], vd.fno);
664
665                 if (ss->modifiers_active)
666                         copy_v3_v3(unode->orig_co[vd.i], ss->orig_cos[unode->index[vd.i]]);
667         }
668         BKE_pbvh_vertex_iter_end;
669 }
670
671 static void sculpt_undo_store_hidden(Object *ob, SculptUndoNode *unode)
672 {
673         PBVH *pbvh = ob->sculpt->pbvh;
674         PBVHNode *node = unode->node;
675
676         if (unode->grids) {
677                 /* already stored during allocation */
678         }
679         else {
680                 MVert *mvert;
681                 int *vert_indices, allvert;
682                 int i;
683                 
684                 BKE_pbvh_node_num_verts(pbvh, node, NULL, &allvert);
685                 BKE_pbvh_node_get_verts(pbvh, node, &vert_indices, &mvert);
686                 for (i = 0; i < allvert; i++) {
687                         BLI_BITMAP_MODIFY(unode->vert_hidden, i,
688                                           mvert[vert_indices[i]].flag & ME_HIDE);
689                 }
690         }
691 }
692
693 static void sculpt_undo_store_mask(Object *ob, SculptUndoNode *unode)
694 {
695         SculptSession *ss = ob->sculpt;
696         PBVHVertexIter vd;
697
698         BKE_pbvh_vertex_iter_begin(ss->pbvh, unode->node, vd, PBVH_ITER_ALL)
699         {
700                 unode->mask[vd.i] = *vd.mask;
701         }
702         BKE_pbvh_vertex_iter_end;
703 }
704
705 static SculptUndoNode *sculpt_undo_bmesh_push(Object *ob,
706                                               PBVHNode *node,
707                                               SculptUndoType type)
708 {
709         ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_MESH);
710         SculptUndoNode *unode = lb->first;
711         SculptSession *ss = ob->sculpt;
712         PBVHVertexIter vd;
713
714         if (!lb->first) {
715                 unode = MEM_callocN(sizeof(*unode), __func__);
716
717                 BLI_strncpy(unode->idname, ob->id.name, sizeof(unode->idname));
718                 unode->type = type;
719                 unode->applied = true;
720
721                 if (type == SCULPT_UNDO_DYNTOPO_END) {
722                         unode->bm_entry = BM_log_entry_add(ss->bm_log);
723                         BM_log_before_all_removed(ss->bm, ss->bm_log);
724                 }
725                 else if (type == SCULPT_UNDO_DYNTOPO_BEGIN) {
726                         Mesh *me = ob->data;
727
728                         /* Store a copy of the mesh's current vertices, loops, and
729                          * polys. A full copy like this is needed because entering
730                          * dynamic-topology immediately does topological edits
731                          * (converting polys to triangles) that the BMLog can't
732                          * fully restore from */
733                         CustomData_copy(&me->vdata, &unode->bm_enter_vdata, CD_MASK_MESH,
734                                         CD_DUPLICATE, me->totvert);
735                         CustomData_copy(&me->edata, &unode->bm_enter_edata, CD_MASK_MESH,
736                                         CD_DUPLICATE, me->totedge);
737                         CustomData_copy(&me->ldata, &unode->bm_enter_ldata, CD_MASK_MESH,
738                                         CD_DUPLICATE, me->totloop);
739                         CustomData_copy(&me->pdata, &unode->bm_enter_pdata, CD_MASK_MESH,
740                                         CD_DUPLICATE, me->totpoly);
741                         unode->bm_enter_totvert = me->totvert;
742                         unode->bm_enter_totedge = me->totedge;
743                         unode->bm_enter_totloop = me->totloop;
744                         unode->bm_enter_totpoly = me->totpoly;
745
746                         unode->bm_entry = BM_log_entry_add(ss->bm_log);
747                         BM_log_all_added(ss->bm, ss->bm_log);
748                 }
749                 else {
750                         unode->bm_entry = BM_log_entry_add(ss->bm_log);
751                 }
752
753                 BLI_addtail(lb, unode);
754         }
755
756         if (node) {
757                 switch (type) {
758                         case SCULPT_UNDO_COORDS:
759                         case SCULPT_UNDO_MASK:
760                                 /* Before any vertex values get modified, ensure their
761                                  * original positions are logged */
762                                 BKE_pbvh_vertex_iter_begin(ss->pbvh, node, vd, PBVH_ITER_ALL) {
763                                         BM_log_vert_before_modified(ss->bm_log, vd.bm_vert, vd.cd_vert_mask_offset);
764                                 }
765                                 BKE_pbvh_vertex_iter_end;
766                                 break;
767
768                         case SCULPT_UNDO_HIDDEN:
769                         {
770                                 GSetIterator gs_iter;
771                                 GSet *faces = BKE_pbvh_bmesh_node_faces(node);
772                                 BKE_pbvh_vertex_iter_begin(ss->pbvh, node, vd, PBVH_ITER_ALL) {
773                                         BM_log_vert_before_modified(ss->bm_log, vd.bm_vert, vd.cd_vert_mask_offset);
774                                 }
775                                 BKE_pbvh_vertex_iter_end;
776
777                                 GSET_ITER (gs_iter, faces) {
778                                         BMFace *f = BLI_gsetIterator_getKey(&gs_iter);
779                                         BM_log_face_modified(ss->bm_log, f);
780                                 }
781                                 break;
782                         }
783
784                         case SCULPT_UNDO_DYNTOPO_BEGIN:
785                         case SCULPT_UNDO_DYNTOPO_END:
786                         case SCULPT_UNDO_DYNTOPO_SYMMETRIZE:
787                                 break;
788                 }
789         }
790
791         return unode;
792 }
793
794 SculptUndoNode *sculpt_undo_push_node(Object *ob, PBVHNode *node,
795                                       SculptUndoType type)
796 {
797         SculptSession *ss = ob->sculpt;
798         SculptUndoNode *unode;
799
800         /* list is manipulated by multiple threads, so we lock */
801         BLI_lock_thread(LOCK_CUSTOM1);
802
803         if (ss->bm ||
804             ELEM(type,
805                  SCULPT_UNDO_DYNTOPO_BEGIN,
806                  SCULPT_UNDO_DYNTOPO_END))
807         {
808                 /* Dynamic topology stores only one undo node per stroke,
809                  * regardless of the number of PBVH nodes modified */
810                 unode = sculpt_undo_bmesh_push(ob, node, type);
811                 BLI_unlock_thread(LOCK_CUSTOM1);
812                 return unode;
813         }
814         else if ((unode = sculpt_undo_get_node(node))) {
815                 BLI_unlock_thread(LOCK_CUSTOM1);
816                 return unode;
817         }
818
819         unode = sculpt_undo_alloc_node(ob, node, type);
820         
821         BLI_unlock_thread(LOCK_CUSTOM1);
822
823         /* copy threaded, hopefully this is the performance critical part */
824
825         if (unode->grids) {
826                 int totgrid, *grids;
827                 BKE_pbvh_node_get_grids(ss->pbvh, node, &grids, &totgrid,
828                                         NULL, NULL, NULL, NULL);
829                 memcpy(unode->grids, grids, sizeof(int) * totgrid);
830         }
831         else {
832                 int *vert_indices, allvert;
833                 BKE_pbvh_node_num_verts(ss->pbvh, node, NULL, &allvert);
834                 BKE_pbvh_node_get_verts(ss->pbvh, node, &vert_indices, NULL);
835                 memcpy(unode->index, vert_indices, sizeof(int) * unode->totvert);
836         }
837
838         switch (type) {
839                 case SCULPT_UNDO_COORDS:
840                         sculpt_undo_store_coords(ob, unode);
841                         break;
842                 case SCULPT_UNDO_HIDDEN:
843                         sculpt_undo_store_hidden(ob, unode);
844                         break;
845                 case SCULPT_UNDO_MASK:
846                         sculpt_undo_store_mask(ob, unode);
847                         break;
848                 case SCULPT_UNDO_DYNTOPO_BEGIN:
849                 case SCULPT_UNDO_DYNTOPO_END:
850                 case SCULPT_UNDO_DYNTOPO_SYMMETRIZE:
851                         BLI_assert(!"Dynamic topology should've already been handled");
852                         break;
853         }
854
855         /* store active shape key */
856         if (ss->kb) BLI_strncpy(unode->shapeName, ss->kb->name, sizeof(ss->kb->name));
857         else unode->shapeName[0] = '\0';
858
859         return unode;
860 }
861
862 void sculpt_undo_push_begin(const char *name)
863 {
864         ED_undo_paint_push_begin(UNDO_PAINT_MESH, name,
865                               sculpt_undo_restore, sculpt_undo_free);
866 }
867
868 void sculpt_undo_push_end(void)
869 {
870         ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_MESH);
871         SculptUndoNode *unode;
872
873         /* we don't need normals in the undo stack */
874         for (unode = lb->first; unode; unode = unode->next) {
875                 if (unode->no) {
876                         MEM_freeN(unode->no);
877                         unode->no = NULL;
878                 }
879
880                 if (unode->node)
881                         BKE_pbvh_node_layer_disp_free(unode->node);
882         }
883
884         ED_undo_paint_push_end(UNDO_PAINT_MESH);
885 }