Fix T38427: Sculpt mode dimension changes don't Undo
[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 (unode->type == 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         else {
301                 /* A bit lame, but for now just recreate the PBVH. The alternative
302                  * is to store changes to the PBVH in the undo stack. */
303                 sculpt_pbvh_clear(ob);
304         }
305 }
306
307 /* Create empty sculpt BMesh and enable logging */
308 static void sculpt_undo_bmesh_enable(Object *ob,
309                                      SculptUndoNode *unode)
310 {
311         SculptSession *ss = ob->sculpt;
312         Mesh *me = ob->data;
313
314         sculpt_pbvh_clear(ob);
315
316         /* Create empty BMesh and enable logging */
317         ss->bm = BM_mesh_create(&bm_mesh_allocsize_default);
318         BM_data_layer_add(ss->bm, &ss->bm->vdata, CD_PAINT_MASK);
319         me->flag |= ME_SCULPT_DYNAMIC_TOPOLOGY;
320
321         /* Restore the BMLog using saved entries */
322         ss->bm_log = BM_log_from_existing_entries_create(ss->bm,
323                                                          unode->bm_entry);
324 }
325
326 static void sculpt_undo_bmesh_restore_begin(bContext *C,
327                                             SculptUndoNode *unode,
328                                             Object *ob,
329                                             SculptSession *ss)
330 {
331         if (unode->applied) {
332                 sculpt_dynamic_topology_disable(C, unode);
333                 unode->applied = FALSE;
334         }
335         else {
336                 sculpt_undo_bmesh_enable(ob, unode);
337
338                 /* Restore the mesh from the first log entry */
339                 BM_log_redo(ss->bm, ss->bm_log);
340
341                 unode->applied = TRUE;
342         }
343 }
344
345 static void sculpt_undo_bmesh_restore_end(bContext *C,
346                                           SculptUndoNode *unode,
347                                           Object *ob,
348                                           SculptSession *ss)
349 {
350         if (unode->applied) {
351                 sculpt_undo_bmesh_enable(ob, unode);
352
353                 /* Restore the mesh from the last log entry */
354                 BM_log_undo(ss->bm, ss->bm_log);
355
356                 unode->applied = FALSE;
357         }
358         else {
359                 /* Disable dynamic topology sculpting */
360                 sculpt_dynamic_topology_disable(C, NULL);
361                 unode->applied = TRUE;
362         }
363 }
364
365 /* Handle all dynamic-topology updates
366  *
367  * Returns TRUE if this was a dynamic-topology undo step, otherwise
368  * returns FALSE to indicate the non-dyntopo code should run. */
369 static int sculpt_undo_bmesh_restore(bContext *C,
370                                      SculptUndoNode *unode,
371                                      Object *ob,
372                                      SculptSession *ss)
373 {
374         switch (unode->type) {
375                 case SCULPT_UNDO_DYNTOPO_BEGIN:
376                         sculpt_undo_bmesh_restore_begin(C, unode, ob, ss);
377                         return TRUE;
378
379                 case SCULPT_UNDO_DYNTOPO_END:
380                         sculpt_undo_bmesh_restore_end(C, unode, ob, ss);
381                         return TRUE;
382
383                 default:
384                         if (ss->bm_log) {
385                                 sculpt_undo_bmesh_restore_generic(C, unode, ob, ss);
386                                 return TRUE;
387                         }
388                         break;
389         }
390
391         return FALSE;
392 }
393
394 static void sculpt_undo_restore(bContext *C, ListBase *lb)
395 {
396         Scene *scene = CTX_data_scene(C);
397         Sculpt *sd = CTX_data_tool_settings(C)->sculpt;
398         Object *ob = CTX_data_active_object(C);
399         DerivedMesh *dm;
400         SculptSession *ss = ob->sculpt;
401         SculptUndoNode *unode;
402         int update = FALSE, rebuild = FALSE;
403         int need_mask = FALSE;
404
405         for (unode = lb->first; unode; unode = unode->next) {
406                 if (strcmp(unode->idname, ob->id.name) == 0) {
407                         if (unode->type == SCULPT_UNDO_MASK) {
408                                 /* is possible that we can't do the mask undo (below)
409                                  * because of the vertex count */
410                                 need_mask = TRUE;
411                                 break;
412                         }
413                 }
414         }
415
416         sculpt_update_mesh_elements(scene, sd, ob, 0, need_mask);
417
418         /* call _after_ sculpt_update_mesh_elements() which may update 'ob->derivedFinal' */
419         dm = mesh_get_derived_final(scene, ob, 0);
420
421         if (lb->first && sculpt_undo_bmesh_restore(C, lb->first, ob, ss))
422                 return;
423
424         for (unode = lb->first; unode; unode = unode->next) {
425                 if (!(strcmp(unode->idname, ob->id.name) == 0))
426                         continue;
427
428                 /* check if undo data matches current data well enough to
429                  * continue */
430                 if (unode->maxvert) {
431                         if (ss->totvert != unode->maxvert)
432                                 continue;
433                 }
434                 else if (unode->maxgrid && dm->getGridData) {
435                         if ((dm->getNumGrids(dm) != unode->maxgrid) ||
436                             (dm->getGridSize(dm) != unode->gridsize))
437                         {
438                                 continue;
439                         }
440                 }
441
442                 switch (unode->type) {
443                         case SCULPT_UNDO_COORDS:
444                                 if (sculpt_undo_restore_coords(C, dm, unode))
445                                         update = TRUE;
446                                 break;
447                         case SCULPT_UNDO_HIDDEN:
448                                 if (sculpt_undo_restore_hidden(C, dm, unode))
449                                         rebuild = TRUE;
450                                 break;
451                         case SCULPT_UNDO_MASK:
452                                 if (sculpt_undo_restore_mask(C, dm, unode))
453                                         update = TRUE;
454                                 break;
455
456                         case SCULPT_UNDO_DYNTOPO_BEGIN:
457                         case SCULPT_UNDO_DYNTOPO_END:
458                         case SCULPT_UNDO_DYNTOPO_SYMMETRIZE:
459                                 BLI_assert(!"Dynamic topology should've already been handled");
460                                 break;
461                 }
462         }
463
464         if (update || rebuild) {
465                 int tag_update = 0;
466                 /* we update all nodes still, should be more clever, but also
467                  * needs to work correct when exiting/entering sculpt mode and
468                  * the nodes get recreated, though in that case it could do all */
469                 BKE_pbvh_search_callback(ss->pbvh, NULL, NULL, update_cb, &rebuild);
470                 BKE_pbvh_update(ss->pbvh, PBVH_UpdateBB | PBVH_UpdateOriginalBB | PBVH_UpdateRedraw, NULL);
471
472                 if (sculpt_multires_active(scene, ob)) {
473                         if (rebuild)
474                                 multires_mark_as_modified(ob, MULTIRES_HIDDEN_MODIFIED);
475                         else
476                                 multires_mark_as_modified(ob, MULTIRES_COORDS_MODIFIED);
477                 }
478
479                 tag_update = ((Mesh *)ob->data)->id.us > 1;
480
481                 if (ss->modifiers_active) {
482                         Mesh *mesh = ob->data;
483                         BKE_mesh_calc_normals_tessface(mesh->mvert, mesh->totvert,
484                                                        mesh->mface, mesh->totface, NULL);
485
486                         free_sculptsession_deformMats(ss);
487                         tag_update |= 1;
488                 }
489
490                 if (tag_update) {
491                         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
492                 }
493                 else {
494                         sculpt_update_object_bounding_box(ob);
495                 }
496
497                 /* for non-PBVH drawing, need to recreate VBOs */
498                 GPU_drawobject_free(ob->derivedFinal);
499         }
500 }
501
502 static void sculpt_undo_free(ListBase *lb)
503 {
504         SculptUndoNode *unode;
505         int i;
506
507         for (unode = lb->first; unode; unode = unode->next) {
508                 if (unode->co)
509                         MEM_freeN(unode->co);
510                 if (unode->no)
511                         MEM_freeN(unode->no);
512                 if (unode->index)
513                         MEM_freeN(unode->index);
514                 if (unode->grids)
515                         MEM_freeN(unode->grids);
516                 if (unode->orig_co)
517                         MEM_freeN(unode->orig_co);
518                 if (unode->vert_hidden)
519                         MEM_freeN(unode->vert_hidden);
520                 if (unode->grid_hidden) {
521                         for (i = 0; i < unode->totgrid; i++) {
522                                 if (unode->grid_hidden[i])
523                                         MEM_freeN(unode->grid_hidden[i]);
524                         }
525                         MEM_freeN(unode->grid_hidden);
526                 }
527                 if (unode->mask)
528                         MEM_freeN(unode->mask);
529                 if (unode->bm_entry) {
530                         BM_log_entry_drop(unode->bm_entry);
531                 }
532                 if (unode->bm_enter_totvert)
533                         CustomData_free(&unode->bm_enter_vdata, unode->bm_enter_totvert);
534                 if (unode->bm_enter_totedge)
535                         CustomData_free(&unode->bm_enter_edata, unode->bm_enter_totedge);
536                 if (unode->bm_enter_totloop)
537                         CustomData_free(&unode->bm_enter_ldata, unode->bm_enter_totloop);
538                 if (unode->bm_enter_totpoly)
539                         CustomData_free(&unode->bm_enter_pdata, unode->bm_enter_totpoly);
540         }
541 }
542
543 SculptUndoNode *sculpt_undo_get_node(PBVHNode *node)
544 {
545         ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_MESH);
546
547         if (!lb) {
548                 return NULL;
549         }
550
551         return BLI_findptr(lb, node, offsetof(SculptUndoNode, node));
552 }
553
554 static void sculpt_undo_alloc_and_store_hidden(PBVH *pbvh,
555                                                SculptUndoNode *unode)
556 {
557         PBVHNode *node = unode->node;
558         BLI_bitmap **grid_hidden;
559         int i, *grid_indices, totgrid;
560
561         grid_hidden = BKE_pbvh_grid_hidden(pbvh);
562
563         BKE_pbvh_node_get_grids(pbvh, node, &grid_indices, &totgrid,
564                                 NULL, NULL, NULL, NULL);
565                         
566         unode->grid_hidden = MEM_mapallocN(sizeof(*unode->grid_hidden) * totgrid,
567                                            "unode->grid_hidden");
568                 
569         for (i = 0; i < totgrid; i++) {
570                 if (grid_hidden[grid_indices[i]])
571                         unode->grid_hidden[i] = MEM_dupallocN(grid_hidden[grid_indices[i]]);
572                 else
573                         unode->grid_hidden[i] = NULL;
574         }
575 }
576
577 static SculptUndoNode *sculpt_undo_alloc_node(Object *ob, PBVHNode *node,
578                                               SculptUndoType type)
579 {
580         ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_MESH);
581         SculptUndoNode *unode;
582         SculptSession *ss = ob->sculpt;
583         int totvert, allvert, totgrid, maxgrid, gridsize, *grids;
584         
585         unode = MEM_callocN(sizeof(SculptUndoNode), "SculptUndoNode");
586         BLI_strncpy(unode->idname, ob->id.name, sizeof(unode->idname));
587         unode->type = type;
588         unode->node = node;
589
590         if (node) {
591                 BKE_pbvh_node_num_verts(ss->pbvh, node, &totvert, &allvert);
592                 BKE_pbvh_node_get_grids(ss->pbvh, node, &grids, &totgrid,
593                                         &maxgrid, &gridsize, NULL, NULL);
594
595                 unode->totvert = totvert;
596         }
597         else
598                 maxgrid = 0;
599         
600         /* we will use this while sculpting, is mapalloc slow to access then? */
601
602         /* general TODO, fix count_alloc */
603         switch (type) {
604                 case SCULPT_UNDO_COORDS:
605                         unode->co = MEM_mapallocN(sizeof(float) * 3 * allvert, "SculptUndoNode.co");
606                         unode->no = MEM_mapallocN(sizeof(short) * 3 * allvert, "SculptUndoNode.no");
607                         undo_paint_push_count_alloc(UNDO_PAINT_MESH,
608                                                     (sizeof(float) * 3 +
609                                                      sizeof(short) * 3 +
610                                                      sizeof(int)) * allvert);
611                         break;
612                 case SCULPT_UNDO_HIDDEN:
613                         if (maxgrid)
614                                 sculpt_undo_alloc_and_store_hidden(ss->pbvh, unode);
615                         else
616                                 unode->vert_hidden = BLI_BITMAP_NEW(allvert, "SculptUndoNode.vert_hidden");
617                 
618                         break;
619                 case SCULPT_UNDO_MASK:
620                         unode->mask = MEM_mapallocN(sizeof(float) * allvert, "SculptUndoNode.mask");
621                         undo_paint_push_count_alloc(UNDO_PAINT_MESH, (sizeof(float) * sizeof(int)) * allvert);
622                         break;
623                 case SCULPT_UNDO_DYNTOPO_BEGIN:
624                 case SCULPT_UNDO_DYNTOPO_END:
625                 case SCULPT_UNDO_DYNTOPO_SYMMETRIZE:
626                         BLI_assert(!"Dynamic topology should've already been handled");
627                         break;
628         }
629         
630         BLI_addtail(lb, unode);
631
632         if (maxgrid) {
633                 /* multires */
634                 unode->maxgrid = maxgrid;
635                 unode->totgrid = totgrid;
636                 unode->gridsize = gridsize;
637                 unode->grids = MEM_mapallocN(sizeof(int) * totgrid, "SculptUndoNode.grids");
638         }
639         else {
640                 /* regular mesh */
641                 unode->maxvert = ss->totvert;
642                 unode->index = MEM_mapallocN(sizeof(int) * allvert, "SculptUndoNode.index");
643         }
644
645         if (ss->modifiers_active)
646                 unode->orig_co = MEM_callocN(allvert * sizeof(*unode->orig_co), "undoSculpt orig_cos");
647
648         return unode;
649 }
650
651 static void sculpt_undo_store_coords(Object *ob, SculptUndoNode *unode)
652 {
653         SculptSession *ss = ob->sculpt;
654         PBVHVertexIter vd;
655
656         BKE_pbvh_vertex_iter_begin(ss->pbvh, unode->node, vd, PBVH_ITER_ALL)
657         {
658                 copy_v3_v3(unode->co[vd.i], vd.co);
659                 if (vd.no) copy_v3_v3_short(unode->no[vd.i], vd.no);
660                 else normal_float_to_short_v3(unode->no[vd.i], vd.fno);
661
662                 if (ss->modifiers_active)
663                         copy_v3_v3(unode->orig_co[vd.i], ss->orig_cos[unode->index[vd.i]]);
664         }
665         BKE_pbvh_vertex_iter_end;
666 }
667
668 static void sculpt_undo_store_hidden(Object *ob, SculptUndoNode *unode)
669 {
670         PBVH *pbvh = ob->sculpt->pbvh;
671         PBVHNode *node = unode->node;
672
673         if (unode->grids) {
674                 /* already stored during allocation */
675         }
676         else {
677                 MVert *mvert;
678                 int *vert_indices, allvert;
679                 int i;
680                 
681                 BKE_pbvh_node_num_verts(pbvh, node, NULL, &allvert);
682                 BKE_pbvh_node_get_verts(pbvh, node, &vert_indices, &mvert);
683                 for (i = 0; i < allvert; i++) {
684                         BLI_BITMAP_MODIFY(unode->vert_hidden, i,
685                                           mvert[vert_indices[i]].flag & ME_HIDE);
686                 }
687         }
688 }
689
690 static void sculpt_undo_store_mask(Object *ob, SculptUndoNode *unode)
691 {
692         SculptSession *ss = ob->sculpt;
693         PBVHVertexIter vd;
694
695         BKE_pbvh_vertex_iter_begin(ss->pbvh, unode->node, vd, PBVH_ITER_ALL)
696         {
697                 unode->mask[vd.i] = *vd.mask;
698         }
699         BKE_pbvh_vertex_iter_end;
700 }
701
702 static SculptUndoNode *sculpt_undo_bmesh_push(Object *ob,
703                                               PBVHNode *node,
704                                               SculptUndoType type)
705 {
706         ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_MESH);
707         SculptUndoNode *unode = lb->first;
708         SculptSession *ss = ob->sculpt;
709         PBVHVertexIter vd;
710
711         if (!lb->first) {
712                 unode = MEM_callocN(sizeof(*unode), AT);
713
714                 BLI_strncpy(unode->idname, ob->id.name, sizeof(unode->idname));
715                 unode->type = type;
716                 unode->applied = TRUE;
717
718                 if (type == SCULPT_UNDO_DYNTOPO_END) {
719                         unode->bm_entry = BM_log_entry_add(ss->bm_log);
720                         BM_log_before_all_removed(ss->bm, ss->bm_log);
721                 }
722                 else if (type == SCULPT_UNDO_DYNTOPO_BEGIN) {
723                         Mesh *me = ob->data;
724
725                         /* Store a copy of the mesh's current vertices, loops, and
726                          * polys. A full copy like this is needed because entering
727                          * dynamic-topology immediately does topological edits
728                          * (converting polys to triangles) that the BMLog can't
729                          * fully restore from */
730                         CustomData_copy(&me->vdata, &unode->bm_enter_vdata, CD_MASK_MESH,
731                                         CD_DUPLICATE, me->totvert);
732                         CustomData_copy(&me->edata, &unode->bm_enter_edata, CD_MASK_MESH,
733                                         CD_DUPLICATE, me->totedge);
734                         CustomData_copy(&me->ldata, &unode->bm_enter_ldata, CD_MASK_MESH,
735                                         CD_DUPLICATE, me->totloop);
736                         CustomData_copy(&me->pdata, &unode->bm_enter_pdata, CD_MASK_MESH,
737                                         CD_DUPLICATE, me->totpoly);
738                         unode->bm_enter_totvert = me->totvert;
739                         unode->bm_enter_totedge = me->totedge;
740                         unode->bm_enter_totloop = me->totloop;
741                         unode->bm_enter_totpoly = me->totpoly;
742
743                         unode->bm_entry = BM_log_entry_add(ss->bm_log);
744                         BM_log_all_added(ss->bm, ss->bm_log);
745                 }
746                 else {
747                         unode->bm_entry = BM_log_entry_add(ss->bm_log);
748                 }
749
750                 BLI_addtail(lb, unode);
751         }
752
753         if (node) {
754                 switch (type) {
755                         case SCULPT_UNDO_COORDS:
756                         case SCULPT_UNDO_HIDDEN:
757                         case SCULPT_UNDO_MASK:
758                                 /* Before any vertex values get modified, ensure their
759                                  * original positions are logged */
760                                 BKE_pbvh_vertex_iter_begin(ss->pbvh, node, vd, PBVH_ITER_ALL) {
761                                         BM_log_vert_before_modified(ss->bm, ss->bm_log, vd.bm_vert);
762                                 }
763                                 BKE_pbvh_vertex_iter_end;
764                                 break;
765
766                         case SCULPT_UNDO_DYNTOPO_BEGIN:
767                         case SCULPT_UNDO_DYNTOPO_END:
768                         case SCULPT_UNDO_DYNTOPO_SYMMETRIZE:
769                                 break;
770                 }
771         }
772
773         return unode;
774 }
775
776 SculptUndoNode *sculpt_undo_push_node(Object *ob, PBVHNode *node,
777                                       SculptUndoType type)
778 {
779         SculptSession *ss = ob->sculpt;
780         SculptUndoNode *unode;
781
782         /* list is manipulated by multiple threads, so we lock */
783         BLI_lock_thread(LOCK_CUSTOM1);
784
785         if (ss->bm ||
786             ELEM(type,
787                  SCULPT_UNDO_DYNTOPO_BEGIN,
788                  SCULPT_UNDO_DYNTOPO_END))
789         {
790                 /* Dynamic topology stores only one undo node per stroke,
791                  * regardless of the number of PBVH nodes modified */
792                 unode = sculpt_undo_bmesh_push(ob, node, type);
793                 BLI_unlock_thread(LOCK_CUSTOM1);
794                 return unode;
795         }
796         else if ((unode = sculpt_undo_get_node(node))) {
797                 BLI_unlock_thread(LOCK_CUSTOM1);
798                 return unode;
799         }
800
801         unode = sculpt_undo_alloc_node(ob, node, type);
802         
803         BLI_unlock_thread(LOCK_CUSTOM1);
804
805         /* copy threaded, hopefully this is the performance critical part */
806
807         if (unode->grids) {
808                 int totgrid, *grids;
809                 BKE_pbvh_node_get_grids(ss->pbvh, node, &grids, &totgrid,
810                                         NULL, NULL, NULL, NULL);
811                 memcpy(unode->grids, grids, sizeof(int) * totgrid);
812         }
813         else {
814                 int *vert_indices, allvert;
815                 BKE_pbvh_node_num_verts(ss->pbvh, node, NULL, &allvert);
816                 BKE_pbvh_node_get_verts(ss->pbvh, node, &vert_indices, NULL);
817                 memcpy(unode->index, vert_indices, sizeof(int) * unode->totvert);
818         }
819
820         switch (type) {
821                 case SCULPT_UNDO_COORDS:
822                         sculpt_undo_store_coords(ob, unode);
823                         break;
824                 case SCULPT_UNDO_HIDDEN:
825                         sculpt_undo_store_hidden(ob, unode);
826                         break;
827                 case SCULPT_UNDO_MASK:
828                         sculpt_undo_store_mask(ob, unode);
829                         break;
830                 case SCULPT_UNDO_DYNTOPO_BEGIN:
831                 case SCULPT_UNDO_DYNTOPO_END:
832                 case SCULPT_UNDO_DYNTOPO_SYMMETRIZE:
833                         BLI_assert(!"Dynamic topology should've already been handled");
834                         break;
835         }
836
837         /* store active shape key */
838         if (ss->kb) BLI_strncpy(unode->shapeName, ss->kb->name, sizeof(ss->kb->name));
839         else unode->shapeName[0] = '\0';
840
841         return unode;
842 }
843
844 void sculpt_undo_push_begin(const char *name)
845 {
846         ED_undo_paint_push_begin(UNDO_PAINT_MESH, name,
847                               sculpt_undo_restore, sculpt_undo_free);
848 }
849
850 void sculpt_undo_push_end(void)
851 {
852         ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_MESH);
853         SculptUndoNode *unode;
854
855         /* we don't need normals in the undo stack */
856         for (unode = lb->first; unode; unode = unode->next) {
857                 if (unode->no) {
858                         MEM_freeN(unode->no);
859                         unode->no = NULL;
860                 }
861
862                 if (unode->node)
863                         BKE_pbvh_node_layer_disp_free(unode->node);
864         }
865
866         ED_undo_paint_push_end(UNDO_PAINT_MESH);
867 }