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