Merging r46111 through r46136 from trunk into soc-2011-tomato
[blender-staging.git] / source / blender / editors / physics / particle_edit.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) 2007 by Janne Karhu.
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
28 /** \file blender/editors/physics/particle_edit.c
29  *  \ingroup edphys
30  */
31
32
33 #include <stdlib.h>
34 #include <math.h>
35 #include <string.h>
36 #include <assert.h>
37
38 #include "MEM_guardedalloc.h"
39
40 #include "DNA_scene_types.h"
41 #include "DNA_mesh_types.h"
42 #include "DNA_meshdata_types.h"
43 #include "DNA_view3d_types.h"
44 #include "DNA_screen_types.h"
45 #include "DNA_space_types.h"
46
47 #include "BLI_math.h"
48 #include "BLI_lasso.h"
49 #include "BLI_listbase.h"
50 #include "BLI_string.h"
51 #include "BLI_dynstr.h"
52 #include "BLI_kdtree.h"
53 #include "BLI_rand.h"
54 #include "BLI_utildefines.h"
55
56 #include "BKE_DerivedMesh.h"
57 #include "BKE_depsgraph.h"
58
59 #include "BKE_context.h"
60 #include "BKE_global.h"
61 #include "BKE_object.h"
62 #include "BKE_mesh.h"
63 #include "BKE_modifier.h"
64 #include "BKE_particle.h"
65 #include "BKE_report.h"
66 #include "BKE_scene.h"
67
68 #include "BKE_pointcache.h"
69
70 #include "BIF_gl.h"
71 #include "BIF_glutil.h"
72
73 #include "ED_physics.h"
74 #include "ED_mesh.h"
75 #include "ED_particle.h"
76 #include "ED_view3d.h"
77
78 #include "UI_resources.h"
79
80 #include "WM_api.h"
81 #include "WM_types.h"
82
83 #include "RNA_access.h"
84 #include "RNA_define.h"
85
86 #include "physics_intern.h"
87
88 static void PE_create_particle_edit(Scene *scene, Object *ob, PointCache *cache, ParticleSystem *psys);
89 static void PTCacheUndo_clear(PTCacheEdit *edit);
90 static void recalc_emitter_field(Object *ob, ParticleSystem *psys);
91
92 #define KEY_K                                   PTCacheEditKey *key; int k
93 #define POINT_P                                 PTCacheEditPoint *point; int p
94 #define LOOP_POINTS                             for (p=0, point=edit->points; p<edit->totpoint; p++, point++)
95 #define LOOP_VISIBLE_POINTS             for (p=0, point=edit->points; p<edit->totpoint; p++, point++) if (!(point->flag & PEP_HIDE))
96 #define LOOP_SELECTED_POINTS    for (p=0, point=edit->points; p<edit->totpoint; p++, point++) if (point_is_selected(point))
97 #define LOOP_UNSELECTED_POINTS  for (p=0, point=edit->points; p<edit->totpoint; p++, point++) if (!point_is_selected(point))
98 #define LOOP_EDITED_POINTS              for (p=0, point=edit->points; p<edit->totpoint; p++, point++) if (point->flag & PEP_EDIT_RECALC)
99 #define LOOP_TAGGED_POINTS              for (p=0, point=edit->points; p<edit->totpoint; p++, point++) if (point->flag & PEP_TAG)
100 #define LOOP_KEYS                               for (k=0, key=point->keys; k<point->totkey; k++, key++)
101 #define LOOP_VISIBLE_KEYS               for (k=0, key=point->keys; k<point->totkey; k++, key++) if (!(key->flag & PEK_HIDE))
102 #define LOOP_SELECTED_KEYS              for (k=0, key=point->keys; k<point->totkey; k++, key++) if ((key->flag & PEK_SELECT) && !(key->flag & PEK_HIDE))
103 #define LOOP_TAGGED_KEYS                for (k=0, key=point->keys; k<point->totkey; k++, key++) if (key->flag & PEK_TAG)
104
105 #define KEY_WCO                                 (key->flag & PEK_USE_WCO ? key->world_co : key->co)
106
107 /**************************** utilities *******************************/
108
109 int PE_poll(bContext *C)
110 {
111         Scene *scene= CTX_data_scene(C);
112         Object *ob= CTX_data_active_object(C);
113
114         if (!scene || !ob || !(ob->mode & OB_MODE_PARTICLE_EDIT))
115                 return 0;
116         
117         return (PE_get_current(scene, ob) != NULL);
118 }
119
120 int PE_hair_poll(bContext *C)
121 {
122         Scene *scene= CTX_data_scene(C);
123         Object *ob= CTX_data_active_object(C);
124         PTCacheEdit *edit;
125
126         if (!scene || !ob || !(ob->mode & OB_MODE_PARTICLE_EDIT))
127                 return 0;
128         
129         edit= PE_get_current(scene, ob);
130
131         return (edit && edit->psys);
132 }
133
134 int PE_poll_view3d(bContext *C)
135 {
136         return PE_poll(C) && CTX_wm_area(C)->spacetype == SPACE_VIEW3D &&
137                 CTX_wm_region(C)->regiontype == RGN_TYPE_WINDOW;
138 }
139
140 void PE_free_ptcache_edit(PTCacheEdit *edit)
141 {
142         POINT_P;
143
144         if (edit==0) return;
145
146         PTCacheUndo_clear(edit);
147
148         if (edit->points) {
149                 LOOP_POINTS {
150                         if (point->keys)
151                                 MEM_freeN(point->keys);
152                 }
153
154                 MEM_freeN(edit->points);
155         }
156
157         if (edit->mirror_cache)
158                 MEM_freeN(edit->mirror_cache);
159
160         if (edit->emitter_cosnos) {
161                 MEM_freeN(edit->emitter_cosnos);
162                 edit->emitter_cosnos= 0;
163         }
164
165         if (edit->emitter_field) {
166                 BLI_kdtree_free(edit->emitter_field);
167                 edit->emitter_field= 0;
168         }
169
170         psys_free_path_cache(edit->psys, edit);
171
172         MEM_freeN(edit);
173 }
174
175 /************************************************/
176 /*                      Edit Mode Helpers                                       */
177 /************************************************/
178
179 int PE_start_edit(PTCacheEdit *edit)
180 {
181         if (edit) {
182                 edit->edited = 1;
183                 if (edit->psys)
184                         edit->psys->flag |= PSYS_EDITED;
185                 return 1;
186         }
187
188         return 0;
189 }
190
191 ParticleEditSettings *PE_settings(Scene *scene)
192 {
193         return scene->toolsettings ? &scene->toolsettings->particle : NULL;
194 }
195
196 /* always gets at least the first particlesystem even if PSYS_CURRENT flag is not set
197  *
198  * note: this function runs on poll, therefor it can runs many times a second
199  * keep it fast! */
200 static PTCacheEdit *pe_get_current(Scene *scene, Object *ob, int create)
201 {
202         ParticleEditSettings *pset= PE_settings(scene);
203         PTCacheEdit *edit = NULL;
204         ListBase pidlist;
205         PTCacheID *pid;
206
207         if (pset==NULL || ob==NULL)
208                 return NULL;
209
210         pset->scene = scene;
211         pset->object = ob;
212
213         BKE_ptcache_ids_from_object(&pidlist, ob, NULL, 0);
214
215         /* in the case of only one editable thing, set pset->edittype accordingly */
216         if (pidlist.first && pidlist.first == pidlist.last) {
217                 pid = pidlist.first;
218                 switch (pid->type) {
219                         case PTCACHE_TYPE_PARTICLES:
220                                 pset->edittype = PE_TYPE_PARTICLES;
221                                 break;
222                         case PTCACHE_TYPE_SOFTBODY:
223                                 pset->edittype = PE_TYPE_SOFTBODY;
224                                 break;
225                         case PTCACHE_TYPE_CLOTH:
226                                 pset->edittype = PE_TYPE_CLOTH;
227                                 break;
228                 }
229         }
230
231         for (pid=pidlist.first; pid; pid=pid->next) {
232                 if (pset->edittype == PE_TYPE_PARTICLES && pid->type == PTCACHE_TYPE_PARTICLES) {
233                         ParticleSystem *psys = pid->calldata;
234
235                         if (psys->flag & PSYS_CURRENT) {
236                                 if (psys->part && psys->part->type == PART_HAIR) {
237                                         if (psys->flag & PSYS_HAIR_DYNAMICS && psys->pointcache->flag & PTCACHE_BAKED) {
238                                                 if (create && !psys->pointcache->edit)
239                                                         PE_create_particle_edit(scene, ob, pid->cache, NULL);
240                                                 edit = pid->cache->edit;
241                                         }
242                                         else {
243                                                 if (create && !psys->edit && psys->flag & PSYS_HAIR_DONE)
244                                                         PE_create_particle_edit(scene, ob, NULL, psys);
245                                                 edit = psys->edit;
246                                         }
247                                 }
248                                 else {
249                                         if (create && pid->cache->flag & PTCACHE_BAKED && !pid->cache->edit)
250                                                 PE_create_particle_edit(scene, ob, pid->cache, psys);
251                                         edit = pid->cache->edit;
252                                 }
253
254                                 break;
255                         }
256                 }
257                 else if (pset->edittype == PE_TYPE_SOFTBODY && pid->type == PTCACHE_TYPE_SOFTBODY) {
258                         if (create && pid->cache->flag & PTCACHE_BAKED && !pid->cache->edit) {
259                                 pset->flag |= PE_FADE_TIME;
260                                 // NICE TO HAVE but doesn't work: pset->brushtype = PE_BRUSH_COMB;
261                                 PE_create_particle_edit(scene, ob, pid->cache, NULL);
262                         }
263                         edit = pid->cache->edit;
264                         break;
265                 }
266                 else if (pset->edittype == PE_TYPE_CLOTH && pid->type == PTCACHE_TYPE_CLOTH) {
267                         if (create && pid->cache->flag & PTCACHE_BAKED && !pid->cache->edit) {
268                                 pset->flag |= PE_FADE_TIME;
269                                 // NICE TO HAVE but doesn't work: pset->brushtype = PE_BRUSH_COMB;
270                                 PE_create_particle_edit(scene, ob, pid->cache, NULL);
271                         }
272                         edit = pid->cache->edit;
273                         break;
274                 }
275         }
276
277         if (edit)
278                 edit->pid = *pid;
279
280         BLI_freelistN(&pidlist);
281
282         return edit;
283 }
284
285 PTCacheEdit *PE_get_current(Scene *scene, Object *ob)
286 {
287         return pe_get_current(scene, ob, 0);
288 }
289
290 PTCacheEdit *PE_create_current(Scene *scene, Object *ob)
291 {
292         return pe_get_current(scene, ob, 1);
293 }
294
295 void PE_current_changed(Scene *scene, Object *ob)
296 {
297         if (ob->mode == OB_MODE_PARTICLE_EDIT)
298                 PE_create_current(scene, ob);
299 }
300
301 void PE_hide_keys_time(Scene *scene, PTCacheEdit *edit, float cfra)
302 {
303         ParticleEditSettings *pset=PE_settings(scene);
304         POINT_P; KEY_K;
305
306
307         if (pset->flag & PE_FADE_TIME && pset->selectmode==SCE_SELECT_POINT) {
308                 LOOP_POINTS {
309                         LOOP_KEYS {
310                                 if (fabs(cfra-*key->time) < pset->fade_frames)
311                                         key->flag &= ~PEK_HIDE;
312                                 else {
313                                         key->flag |= PEK_HIDE;
314                                         //key->flag &= ~PEK_SELECT;
315                                 }
316                         }
317                 }
318         }
319         else {
320                 LOOP_POINTS {
321                         LOOP_KEYS {
322                                 key->flag &= ~PEK_HIDE;
323                         }
324                 }
325         }
326 }
327
328 static int pe_x_mirror(Object *ob)
329 {
330         if (ob->type == OB_MESH)
331                 return (((Mesh*)ob->data)->editflag & ME_EDIT_MIRROR_X);
332         
333         return 0;
334 }
335
336 /****************** common struct passed to callbacks ******************/
337
338 typedef struct PEData {
339         ViewContext vc;
340         bglMats mats;
341         
342         Scene *scene;
343         Object *ob;
344         DerivedMesh *dm;
345         PTCacheEdit *edit;
346
347         const int *mval;
348         rcti *rect;
349         float rad;
350         float dist;
351         float dval;
352         int select;
353
354         float *dvec;
355         float combfac;
356         float pufffac;
357         float cutfac;
358         float smoothfac;
359         float weightfac;
360         float growfac;
361         int totrekey;
362
363         int invert;
364         int tot;
365         float vec[3];
366 } PEData;
367
368 static void PE_set_data(bContext *C, PEData *data)
369 {
370         memset(data, 0, sizeof(*data));
371
372         data->scene= CTX_data_scene(C);
373         data->ob= CTX_data_active_object(C);
374         data->edit= PE_get_current(data->scene, data->ob);
375 }
376
377 static void PE_set_view3d_data(bContext *C, PEData *data)
378 {
379         PE_set_data(C, data);
380
381         view3d_set_viewcontext(C, &data->vc);
382         /* note, the object argument means the modelview matrix does not account for the objects matrix, use viewmat rather than (obmat * viewmat) */
383         view3d_get_transformation(data->vc.ar, data->vc.rv3d, NULL, &data->mats);
384
385         if ((data->vc.v3d->drawtype>OB_WIRE) && (data->vc.v3d->flag & V3D_ZBUF_SELECT)) {
386                 if (data->vc.v3d->flag & V3D_INVALID_BACKBUF) {
387                         /* needed or else the draw matrix can be incorrect */
388                         view3d_operator_needs_opengl(C);
389
390                         view3d_validate_backbuf(&data->vc);
391                         /* we may need to force an update here by setting the rv3d as dirty
392                          * for now it seems ok, but take care!:
393                          * rv3d->depths->dirty = 1; */
394                         ED_view3d_depth_update(data->vc.ar);
395                 }
396         }
397 }
398
399 /*************************** selection utilities *******************************/
400
401 static int key_test_depth(PEData *data, const float co[3])
402 {
403         View3D *v3d= data->vc.v3d;
404         double ux, uy, uz;
405         float depth;
406         short wco[3], x, y;
407
408         /* nothing to do */
409         if ((v3d->drawtype<=OB_WIRE) || (v3d->flag & V3D_ZBUF_SELECT)==0)
410                 return 1;
411
412         project_short(data->vc.ar, co, wco);
413         
414         if (wco[0] == IS_CLIPPED)
415                 return 0;
416
417         gluProject(co[0], co[1], co[2], data->mats.modelview, data->mats.projection,
418                    (GLint *)data->mats.viewport, &ux, &uy, &uz);
419
420         x=wco[0];
421         y=wco[1];
422
423 #if 0 /* works well but too slow on some systems [#23118] */
424         x+= (short)data->vc.ar->winrct.xmin;
425         y+= (short)data->vc.ar->winrct.ymin;
426
427         /* PE_set_view3d_data calls this. no need to call here */
428         /* view3d_validate_backbuf(&data->vc); */
429         glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth);
430 #else /* faster to use depths, these are calculated in PE_set_view3d_data */
431         {
432                 ViewDepths *vd = data->vc.rv3d->depths;
433                 assert(vd && vd->depths);
434                 /* we know its not clipped */
435                 depth= vd->depths[y * vd->w + x];
436         }
437 #endif
438
439         if ((float)uz - 0.00001f > depth)
440                 return 0;
441         else
442                 return 1;
443 }
444
445 static int key_inside_circle(PEData *data, float rad, const float co[3], float *distance)
446 {
447         float dx, dy, dist;
448         int sco[2];
449
450         project_int(data->vc.ar, co, sco);
451         
452         if (sco[0] == IS_CLIPPED)
453                 return 0;
454         
455         dx= data->mval[0] - sco[0];
456         dy= data->mval[1] - sco[1];
457         dist= sqrt(dx*dx + dy*dy);
458
459         if (dist > rad)
460                 return 0;
461
462         if (key_test_depth(data, co)) {
463                 if (distance)
464                         *distance=dist;
465
466                 return 1;
467         }
468         
469         return 0;
470 }
471
472 static int key_inside_rect(PEData *data, const float co[3])
473 {
474         int sco[2];
475
476         project_int(data->vc.ar, co, sco);
477
478         if (sco[0] == IS_CLIPPED)
479                 return 0;
480
481         if (sco[0] > data->rect->xmin && sco[0] < data->rect->xmax &&
482             sco[1] > data->rect->ymin && sco[1] < data->rect->ymax)
483         {
484                 return key_test_depth(data, co);
485         }
486
487         return 0;
488 }
489
490 static int key_inside_test(PEData *data, const float co[3])
491 {
492         if (data->mval)
493                 return key_inside_circle(data, data->rad, co, NULL);
494         else
495                 return key_inside_rect(data, co);
496 }
497
498 static int point_is_selected(PTCacheEditPoint *point)
499 {
500         KEY_K;
501
502         if (point->flag & PEP_HIDE)
503                 return 0;
504
505         LOOP_SELECTED_KEYS {
506                 return 1;
507         }
508         
509         return 0;
510 }
511
512 /*************************** iterators *******************************/
513
514 typedef void (*ForPointFunc)(PEData *data, int point_index);
515 typedef void (*ForKeyFunc)(PEData *data, int point_index, int key_index);
516 typedef void (*ForKeyMatFunc)(PEData *data, float mat[][4], float imat[][4], int point_index, int key_index, PTCacheEditKey *key);
517
518 static void for_mouse_hit_keys(PEData *data, ForKeyFunc func, int nearest)
519 {
520         ParticleEditSettings *pset= PE_settings(data->scene);
521         PTCacheEdit *edit= data->edit;
522         POINT_P; KEY_K;
523         int nearest_point, nearest_key;
524         float dist= data->rad;
525
526         /* in path select mode we have no keys */
527         if (pset->selectmode==SCE_SELECT_PATH)
528                 return;
529
530         nearest_point= -1;
531         nearest_key= -1;
532
533         LOOP_VISIBLE_POINTS {
534                 if (pset->selectmode == SCE_SELECT_END) {
535                         /* only do end keys */
536                         key= point->keys + point->totkey-1;
537
538                         if (nearest) {
539                                 if (key_inside_circle(data, dist, KEY_WCO, &dist)) {
540                                         nearest_point= p;
541                                         nearest_key= point->totkey-1;
542                                 }
543                         }
544                         else if (key_inside_test(data, KEY_WCO))
545                                 func(data, p, point->totkey-1);
546                 }
547                 else {
548                         /* do all keys */
549                         LOOP_VISIBLE_KEYS {
550                                 if (nearest) {
551                                         if (key_inside_circle(data, dist, KEY_WCO, &dist)) {
552                                                 nearest_point= p;
553                                                 nearest_key= k;
554                                         }
555                                 }
556                                 else if (key_inside_test(data, KEY_WCO))
557                                         func(data, p, k);
558                         }
559                 }
560         }
561
562         /* do nearest only */
563         if (nearest && nearest_point > -1)
564                 func(data, nearest_point, nearest_key);
565 }
566
567 static void foreach_mouse_hit_point(PEData *data, ForPointFunc func, int selected)
568 {
569         ParticleEditSettings *pset= PE_settings(data->scene);
570         PTCacheEdit *edit= data->edit;
571         POINT_P; KEY_K;
572
573         /* all is selected in path mode */
574         if (pset->selectmode==SCE_SELECT_PATH)
575                 selected=0;
576
577         LOOP_VISIBLE_POINTS {
578                 if (pset->selectmode==SCE_SELECT_END) {
579                         /* only do end keys */
580                         key= point->keys + point->totkey - 1;
581
582                         if (selected==0 || key->flag & PEK_SELECT)
583                                 if (key_inside_circle(data, data->rad, KEY_WCO, &data->dist))
584                                         func(data, p);
585                 }
586                 else {
587                         /* do all keys */
588                         LOOP_VISIBLE_KEYS {
589                                 if (selected==0 || key->flag & PEK_SELECT) {
590                                         if (key_inside_circle(data, data->rad, KEY_WCO, &data->dist)) {
591                                                 func(data, p);
592                                                 break;
593                                         }
594                                 }
595                         }
596                 }
597         }
598 }
599
600 static void foreach_mouse_hit_key(PEData *data, ForKeyMatFunc func, int selected)
601 {
602         PTCacheEdit *edit = data->edit;
603         ParticleSystem *psys = edit->psys;
604         ParticleSystemModifierData *psmd = NULL;
605         ParticleEditSettings *pset= PE_settings(data->scene);
606         POINT_P; KEY_K;
607         float mat[4][4]= MAT4_UNITY, imat[4][4]= MAT4_UNITY;
608
609         if (edit->psys)
610                 psmd= psys_get_modifier(data->ob, edit->psys);
611
612         /* all is selected in path mode */
613         if (pset->selectmode==SCE_SELECT_PATH)
614                 selected= 0;
615
616         LOOP_VISIBLE_POINTS {
617                 if (pset->selectmode==SCE_SELECT_END) {
618                         /* only do end keys */
619                         key= point->keys + point->totkey-1;
620
621                         if (selected==0 || key->flag & PEK_SELECT) {
622                                 if (key_inside_circle(data, data->rad, KEY_WCO, &data->dist)) {
623                                         if (edit->psys && !(edit->psys->flag & PSYS_GLOBAL_HAIR)) {
624                                                 psys_mat_hair_to_global(data->ob, psmd->dm, psys->part->from, psys->particles + p, mat);
625                                                 invert_m4_m4(imat, mat);
626                                         }
627
628                                         func(data, mat, imat, p, point->totkey-1, key);
629                                 }
630                         }
631                 }
632                 else {
633                         /* do all keys */
634                         LOOP_VISIBLE_KEYS {
635                                 if (selected==0 || key->flag & PEK_SELECT) {
636                                         if (key_inside_circle(data, data->rad, KEY_WCO, &data->dist)) {
637                                                 if (edit->psys && !(edit->psys->flag & PSYS_GLOBAL_HAIR)) {
638                                                         psys_mat_hair_to_global(data->ob, psmd->dm, psys->part->from, psys->particles + p, mat);
639                                                         invert_m4_m4(imat, mat);
640                                                 }
641
642                                                 func(data, mat, imat, p, k, key);
643                                         }
644                                 }
645                         }
646                 }
647         }
648 }
649
650 static void foreach_selected_point(PEData *data, ForPointFunc func)
651 {
652         PTCacheEdit *edit = data->edit;
653         POINT_P;
654
655         LOOP_SELECTED_POINTS {
656                 func(data, p);
657         }
658 }
659
660 static void foreach_selected_key(PEData *data, ForKeyFunc func)
661 {
662         PTCacheEdit *edit = data->edit;
663         POINT_P; KEY_K;
664
665         LOOP_VISIBLE_POINTS {
666                 LOOP_SELECTED_KEYS {
667                         func(data, p, k);
668                 }
669         }
670 }
671
672 static void foreach_point(PEData *data, ForPointFunc func)
673 {
674         PTCacheEdit *edit = data->edit;
675         POINT_P;
676
677         LOOP_POINTS { 
678                 func(data, p);
679         }
680 }
681
682 static int count_selected_keys(Scene *scene, PTCacheEdit *edit)
683 {
684         ParticleEditSettings *pset= PE_settings(scene);
685         POINT_P; KEY_K;
686         int sel= 0;
687
688         LOOP_VISIBLE_POINTS {
689                 if (pset->selectmode==SCE_SELECT_POINT) {
690                         LOOP_SELECTED_KEYS {
691                                 sel++;
692                         }
693                 }
694                 else if (pset->selectmode==SCE_SELECT_END) {
695                         key = point->keys + point->totkey - 1;
696                         if (key->flag & PEK_SELECT)
697                                 sel++;
698                 }
699         }
700
701         return sel;
702 }
703
704 /************************************************/
705 /*                      Particle Edit Mirroring                         */
706 /************************************************/
707
708 static void PE_update_mirror_cache(Object *ob, ParticleSystem *psys)
709 {
710         PTCacheEdit *edit;
711         ParticleSystemModifierData *psmd;
712         KDTree *tree;
713         KDTreeNearest nearest;
714         HairKey *key;
715         PARTICLE_P;
716         float mat[4][4], co[3];
717         int index, totpart;
718
719         edit= psys->edit;
720         psmd= psys_get_modifier(ob, psys);
721         totpart= psys->totpart;
722
723         if (!psmd->dm)
724                 return;
725
726         tree= BLI_kdtree_new(totpart);
727
728         /* insert particles into kd tree */
729         LOOP_PARTICLES {
730                 key = pa->hair;
731                 psys_mat_hair_to_orco(ob, psmd->dm, psys->part->from, pa, mat);
732                 copy_v3_v3(co, key->co);
733                 mul_m4_v3(mat, co);
734                 BLI_kdtree_insert(tree, p, co, NULL);
735         }
736
737         BLI_kdtree_balance(tree);
738
739         /* lookup particles and set in mirror cache */
740         if (!edit->mirror_cache)
741                 edit->mirror_cache= MEM_callocN(sizeof(int)*totpart, "PE mirror cache");
742         
743         LOOP_PARTICLES {
744                 key = pa->hair;
745                 psys_mat_hair_to_orco(ob, psmd->dm, psys->part->from, pa, mat);
746                 copy_v3_v3(co, key->co);
747                 mul_m4_v3(mat, co);
748                 co[0]= -co[0];
749
750                 index= BLI_kdtree_find_nearest(tree, co, NULL, &nearest);
751
752                 /* this needs a custom threshold still, duplicated for editmode mirror */
753                 if (index != -1 && index != p && (nearest.dist <= 0.0002f))
754                         edit->mirror_cache[p]= index;
755                 else
756                         edit->mirror_cache[p]= -1;
757         }
758
759         /* make sure mirrors are in two directions */
760         LOOP_PARTICLES {
761                 if (edit->mirror_cache[p]) {
762                         index= edit->mirror_cache[p];
763                         if (edit->mirror_cache[index] != p)
764                                 edit->mirror_cache[p]= -1;
765                 }
766         }
767
768         BLI_kdtree_free(tree);
769 }
770
771 static void PE_mirror_particle(Object *ob, DerivedMesh *dm, ParticleSystem *psys, ParticleData *pa, ParticleData *mpa)
772 {
773         HairKey *hkey, *mhkey;
774         PTCacheEditPoint *point, *mpoint;
775         PTCacheEditKey *key, *mkey;
776         PTCacheEdit *edit;
777         float mat[4][4], mmat[4][4], immat[4][4];
778         int i, mi, k;
779
780         edit= psys->edit;
781         i= pa - psys->particles;
782
783         /* find mirrored particle if needed */
784         if (!mpa) {
785                 if (!edit->mirror_cache)
786                         PE_update_mirror_cache(ob, psys);
787                 
788                 if (!edit->mirror_cache)
789                         return; /* something went wrong! */
790
791                 mi= edit->mirror_cache[i];
792                 if (mi == -1)
793                         return;
794                 mpa= psys->particles + mi;
795         }
796         else
797                 mi= mpa - psys->particles;
798
799         point = edit->points + i;
800         mpoint = edit->points + mi;
801
802         /* make sure they have the same amount of keys */
803         if (pa->totkey != mpa->totkey) {
804                 if (mpa->hair) MEM_freeN(mpa->hair);
805                 if (mpoint->keys) MEM_freeN(mpoint->keys);
806
807                 mpa->hair= MEM_dupallocN(pa->hair);
808                 mpa->totkey= pa->totkey;
809                 mpoint->keys= MEM_dupallocN(point->keys);
810                 mpoint->totkey= point->totkey;
811
812                 mhkey= mpa->hair;
813                 mkey= mpoint->keys;
814                 for (k=0; k<mpa->totkey; k++, mkey++, mhkey++) {
815                         mkey->co= mhkey->co;
816                         mkey->time= &mhkey->time;
817                         mkey->flag &= ~PEK_SELECT;
818                 }
819         }
820
821         /* mirror positions and tags */
822         psys_mat_hair_to_orco(ob, dm, psys->part->from, pa, mat);
823         psys_mat_hair_to_orco(ob, dm, psys->part->from, mpa, mmat);
824         invert_m4_m4(immat, mmat);
825
826         hkey=pa->hair;
827         mhkey=mpa->hair;
828         key= point->keys;
829         mkey= mpoint->keys;
830         for (k=0; k<pa->totkey; k++, hkey++, mhkey++, key++, mkey++) {
831                 copy_v3_v3(mhkey->co, hkey->co);
832                 mul_m4_v3(mat, mhkey->co);
833                 mhkey->co[0]= -mhkey->co[0];
834                 mul_m4_v3(immat, mhkey->co);
835
836                 if (key->flag & PEK_TAG)
837                         mkey->flag |= PEK_TAG;
838
839                 mkey->length = key->length;
840         }
841
842         if (point->flag & PEP_TAG)
843                 mpoint->flag |= PEP_TAG;
844         if (point->flag & PEP_EDIT_RECALC)
845                 mpoint->flag |= PEP_EDIT_RECALC;
846 }
847
848 static void PE_apply_mirror(Object *ob, ParticleSystem *psys)
849 {
850         PTCacheEdit *edit;
851         ParticleSystemModifierData *psmd;
852         POINT_P;
853
854         if (!psys)
855                 return;
856
857         edit= psys->edit;
858         psmd= psys_get_modifier(ob, psys);
859
860         if (!psmd->dm)
861                 return;
862
863         if (!edit->mirror_cache)
864                 PE_update_mirror_cache(ob, psys);
865
866         if (!edit->mirror_cache)
867                 return; /* something went wrong */
868
869         /* we delay settings the PARS_EDIT_RECALC for mirrored particles
870          * to avoid doing mirror twice */
871         LOOP_POINTS {
872                 if (point->flag & PEP_EDIT_RECALC) {
873                         PE_mirror_particle(ob, psmd->dm, psys, psys->particles + p, NULL);
874
875                         if (edit->mirror_cache[p] != -1)
876                                 edit->points[edit->mirror_cache[p]].flag &= ~PEP_EDIT_RECALC;
877                 }
878         }
879
880         LOOP_POINTS {
881                 if (point->flag & PEP_EDIT_RECALC)
882                         if (edit->mirror_cache[p] != -1)
883                                 edit->points[edit->mirror_cache[p]].flag |= PEP_EDIT_RECALC;
884         }
885 }
886
887 /************************************************/
888 /*                      Edit Calculation                                        */
889 /************************************************/
890 /* tries to stop edited particles from going through the emitter's surface */
891 static void pe_deflect_emitter(Scene *scene, Object *ob, PTCacheEdit *edit)
892 {
893         ParticleEditSettings *pset= PE_settings(scene);
894         ParticleSystem *psys;
895         ParticleSystemModifierData *psmd;
896         POINT_P; KEY_K;
897         int index;
898         float *vec, *nor, dvec[3], dot, dist_1st=0.0f;
899         float hairimat[4][4], hairmat[4][4];
900
901         if (edit==NULL || edit->psys==NULL || (pset->flag & PE_DEFLECT_EMITTER)==0 || (edit->psys->flag & PSYS_GLOBAL_HAIR))
902                 return;
903
904         psys = edit->psys;
905         psmd = psys_get_modifier(ob, psys);
906
907         if (!psmd->dm)
908                 return;
909
910         LOOP_EDITED_POINTS {
911                 psys_mat_hair_to_object(ob, psmd->dm, psys->part->from, psys->particles + p, hairmat);
912         
913                 LOOP_KEYS {
914                         mul_m4_v3(hairmat, key->co);
915                 }
916
917                 LOOP_KEYS {
918                         if (k==0) {
919                                 dist_1st = len_v3v3((key+1)->co, key->co);
920                                 dist_1st *= 0.75f * pset->emitterdist;
921                         }
922                         else {
923                                 index= BLI_kdtree_find_nearest(edit->emitter_field, key->co, NULL, NULL);
924                                 
925                                 vec=edit->emitter_cosnos +index*6;
926                                 nor=vec+3;
927
928                                 sub_v3_v3v3(dvec, key->co, vec);
929
930                                 dot=dot_v3v3(dvec, nor);
931                                 copy_v3_v3(dvec, nor);
932
933                                 if (dot>0.0f) {
934                                         if (dot<dist_1st) {
935                                                 normalize_v3(dvec);
936                                                 mul_v3_fl(dvec, dist_1st-dot);
937                                                 add_v3_v3(key->co, dvec);
938                                         }
939                                 }
940                                 else {
941                                         normalize_v3(dvec);
942                                         mul_v3_fl(dvec, dist_1st-dot);
943                                         add_v3_v3(key->co, dvec);
944                                 }
945                                 if (k==1)
946                                         dist_1st*=1.3333f;
947                         }
948                 }
949                 
950                 invert_m4_m4(hairimat, hairmat);
951
952                 LOOP_KEYS {
953                         mul_m4_v3(hairimat, key->co);
954                 }
955         }
956 }
957 /* force set distances between neighboring keys */
958 static void PE_apply_lengths(Scene *scene, PTCacheEdit *edit)
959 {
960         
961         ParticleEditSettings *pset=PE_settings(scene);
962         POINT_P; KEY_K;
963         float dv1[3];
964
965         if (edit==0 || (pset->flag & PE_KEEP_LENGTHS)==0)
966                 return;
967
968         if (edit->psys && edit->psys->flag & PSYS_GLOBAL_HAIR)
969                 return;
970
971         LOOP_EDITED_POINTS {
972                 LOOP_KEYS {
973                         if (k) {
974                                 sub_v3_v3v3(dv1, key->co, (key - 1)->co);
975                                 normalize_v3(dv1);
976                                 mul_v3_fl(dv1, (key - 1)->length);
977                                 add_v3_v3v3(key->co, (key - 1)->co, dv1);
978                         }
979                 }
980         }
981 }
982 /* try to find a nice solution to keep distances between neighboring keys */
983 static void pe_iterate_lengths(Scene *scene, PTCacheEdit *edit)
984 {
985         ParticleEditSettings *pset=PE_settings(scene);
986         POINT_P;
987         PTCacheEditKey *key;
988         int j, k;
989         float tlen;
990         float dv0[3]= {0.0f, 0.0f, 0.0f};
991         float dv1[3]= {0.0f, 0.0f, 0.0f};
992         float dv2[3]= {0.0f, 0.0f, 0.0f};
993
994         if (edit==0 || (pset->flag & PE_KEEP_LENGTHS)==0)
995                 return;
996
997         if (edit->psys && edit->psys->flag & PSYS_GLOBAL_HAIR)
998                 return;
999
1000         LOOP_EDITED_POINTS {
1001                 for (j=1; j<point->totkey; j++) {
1002                         float mul= 1.0f / (float)point->totkey;
1003
1004                         if (pset->flag & PE_LOCK_FIRST) {
1005                                 key= point->keys + 1;
1006                                 k= 1;
1007                                 dv1[0]= dv1[1]= dv1[2]= 0.0;
1008                         }
1009                         else {
1010                                 key= point->keys;
1011                                 k= 0;
1012                                 dv0[0]= dv0[1]= dv0[2]= 0.0;
1013                         }
1014
1015                         for (; k<point->totkey; k++, key++) {
1016                                 if (k) {
1017                                         sub_v3_v3v3(dv0, (key - 1)->co, key->co);
1018                                         tlen= normalize_v3(dv0);
1019                                         mul_v3_fl(dv0, (mul * (tlen - (key - 1)->length)));
1020                                 }
1021
1022                                 if (k < point->totkey - 1) {
1023                                         sub_v3_v3v3(dv2, (key + 1)->co, key->co);
1024                                         tlen= normalize_v3(dv2);
1025                                         mul_v3_fl(dv2, mul * (tlen - key->length));
1026                                 }
1027
1028                                 if (k) {
1029                                         add_v3_v3((key-1)->co, dv1);
1030                                 }
1031
1032                                 add_v3_v3v3(dv1, dv0, dv2);
1033                         }
1034                 }
1035         }
1036 }
1037 /* set current distances to be kept between neighbouting keys */
1038 static void recalc_lengths(PTCacheEdit *edit)
1039 {
1040         POINT_P; KEY_K;
1041
1042         if (edit==0)
1043                 return;
1044
1045         LOOP_EDITED_POINTS {
1046                 key= point->keys;
1047                 for (k=0; k<point->totkey-1; k++, key++) {
1048                         key->length= len_v3v3(key->co, (key + 1)->co);
1049                 }
1050         }
1051 }
1052
1053 /* calculate a tree for finding nearest emitter's vertice */
1054 static void recalc_emitter_field(Object *ob, ParticleSystem *psys)
1055 {
1056         DerivedMesh *dm=psys_get_modifier(ob, psys)->dm;
1057         PTCacheEdit *edit= psys->edit;
1058         float *vec, *nor;
1059         int i, totface /*, totvert*/;
1060
1061         if (!dm)
1062                 return;
1063
1064         if (edit->emitter_cosnos)
1065                 MEM_freeN(edit->emitter_cosnos);
1066
1067         BLI_kdtree_free(edit->emitter_field);
1068
1069         totface=dm->getNumTessFaces(dm);
1070         /*totvert=dm->getNumVerts(dm);*/ /*UNSUED*/
1071
1072         edit->emitter_cosnos=MEM_callocN(totface*6*sizeof(float), "emitter cosnos");
1073
1074         edit->emitter_field= BLI_kdtree_new(totface);
1075
1076         vec=edit->emitter_cosnos;
1077         nor=vec+3;
1078
1079         for (i=0; i<totface; i++, vec+=6, nor+=6) {
1080                 MFace *mface=dm->getTessFaceData(dm, i, CD_MFACE);
1081                 MVert *mvert;
1082
1083                 mvert=dm->getVertData(dm, mface->v1, CD_MVERT);
1084                 copy_v3_v3(vec, mvert->co);
1085                 VECCOPY(nor, mvert->no);
1086
1087                 mvert=dm->getVertData(dm, mface->v2, CD_MVERT);
1088                 add_v3_v3v3(vec, vec, mvert->co);
1089                 VECADD(nor, nor, mvert->no);
1090
1091                 mvert=dm->getVertData(dm, mface->v3, CD_MVERT);
1092                 add_v3_v3v3(vec, vec, mvert->co);
1093                 VECADD(nor, nor, mvert->no);
1094
1095                 if (mface->v4) {
1096                         mvert=dm->getVertData(dm, mface->v4, CD_MVERT);
1097                         add_v3_v3v3(vec, vec, mvert->co);
1098                         VECADD(nor, nor, mvert->no);
1099                         
1100                         mul_v3_fl(vec, 0.25);
1101                 }
1102                 else
1103                         mul_v3_fl(vec, 0.3333f);
1104
1105                 normalize_v3(nor);
1106
1107                 BLI_kdtree_insert(edit->emitter_field, i, vec, NULL);
1108         }
1109
1110         BLI_kdtree_balance(edit->emitter_field);
1111 }
1112
1113 static void PE_update_selection(Scene *scene, Object *ob, int useflag)
1114 {
1115         PTCacheEdit *edit= PE_get_current(scene, ob);
1116         HairKey *hkey;
1117         POINT_P; KEY_K;
1118
1119         /* flag all particles to be updated if not using flag */
1120         if (!useflag)
1121                 LOOP_POINTS
1122                         point->flag |= PEP_EDIT_RECALC;
1123
1124         /* flush edit key flag to hair key flag to preserve selection 
1125          * on save */
1126         if (edit->psys) LOOP_POINTS {
1127                 hkey = edit->psys->particles[p].hair;
1128                 LOOP_KEYS {
1129                         hkey->editflag= key->flag;
1130                         hkey++;
1131                 }
1132         }
1133
1134         psys_cache_edit_paths(scene, ob, edit, CFRA);
1135
1136
1137         /* disable update flag */
1138         LOOP_POINTS
1139                 point->flag &= ~PEP_EDIT_RECALC;
1140 }
1141
1142 static void update_world_cos(Object *ob, PTCacheEdit *edit)
1143 {
1144         ParticleSystem *psys = edit->psys;
1145         ParticleSystemModifierData *psmd= psys_get_modifier(ob, psys);
1146         POINT_P; KEY_K;
1147         float hairmat[4][4];
1148
1149         if (psys==0 || psys->edit==0 || psmd->dm==NULL)
1150                 return;
1151
1152         LOOP_POINTS {
1153                 if (!(psys->flag & PSYS_GLOBAL_HAIR))
1154                         psys_mat_hair_to_global(ob, psmd->dm, psys->part->from, psys->particles+p, hairmat);
1155
1156                 LOOP_KEYS {
1157                         copy_v3_v3(key->world_co, key->co);
1158                         if (!(psys->flag & PSYS_GLOBAL_HAIR))
1159                                 mul_m4_v3(hairmat, key->world_co);
1160                 }
1161         }
1162 }
1163 static void update_velocities(PTCacheEdit *edit)
1164 {
1165         /*TODO: get frs_sec properly */
1166         float vec1[3], vec2[3], frs_sec, dfra;
1167         POINT_P; KEY_K;
1168
1169         /* hair doesn't use velocities */
1170         if (edit->psys || !edit->points || !edit->points->keys->vel)
1171                 return;
1172
1173         frs_sec = edit->pid.flag & PTCACHE_VEL_PER_SEC ? 25.0f : 1.0f;
1174
1175         LOOP_EDITED_POINTS {
1176                 LOOP_KEYS {
1177                         if (k==0) {
1178                                 dfra = *(key+1)->time - *key->time;
1179
1180                                 if (dfra <= 0.0f)
1181                                         continue;
1182
1183                                 sub_v3_v3v3(key->vel, (key+1)->co, key->co);
1184
1185                                 if (point->totkey>2) {
1186                                         sub_v3_v3v3(vec1, (key+1)->co, (key+2)->co);
1187                                         project_v3_v3v3(vec2, vec1, key->vel);
1188                                         sub_v3_v3v3(vec2, vec1, vec2);
1189                                         madd_v3_v3fl(key->vel, vec2, 0.5f);
1190                                 }
1191                         }
1192                         else if (k==point->totkey-1) {
1193                                 dfra = *key->time - *(key-1)->time;
1194
1195                                 if (dfra <= 0.0f)
1196                                         continue;
1197
1198                                 sub_v3_v3v3(key->vel, key->co, (key-1)->co);
1199
1200                                 if (point->totkey>2) {
1201                                         sub_v3_v3v3(vec1, (key-2)->co, (key-1)->co);
1202                                         project_v3_v3v3(vec2, vec1, key->vel);
1203                                         sub_v3_v3v3(vec2, vec1, vec2);
1204                                         madd_v3_v3fl(key->vel, vec2, 0.5f);
1205                                 }
1206                         }
1207                         else {
1208                                 dfra = *(key+1)->time - *(key-1)->time;
1209                                 
1210                                 if (dfra <= 0.0f)
1211                                         continue;
1212
1213                                 sub_v3_v3v3(key->vel, (key+1)->co, (key-1)->co);
1214                         }
1215                         mul_v3_fl(key->vel, frs_sec/dfra);
1216                 }
1217         }
1218 }
1219
1220 void PE_update_object(Scene *scene, Object *ob, int useflag)
1221 {
1222         /* use this to do partial particle updates, not usable when adding or
1223          * removing, then a full redo is necessary and calling this may crash */
1224         ParticleEditSettings *pset= PE_settings(scene);
1225         PTCacheEdit *edit = PE_get_current(scene, ob);
1226         POINT_P;
1227
1228         if (!edit)
1229                 return;
1230
1231         /* flag all particles to be updated if not using flag */
1232         if (!useflag)
1233                 LOOP_POINTS {
1234                         point->flag |= PEP_EDIT_RECALC;
1235                 }
1236
1237         /* do post process on particle edit keys */
1238         pe_iterate_lengths(scene, edit);
1239         pe_deflect_emitter(scene, ob, edit);
1240         PE_apply_lengths(scene, edit);
1241         if (pe_x_mirror(ob))
1242                 PE_apply_mirror(ob, edit->psys);
1243         if (edit->psys)
1244                 update_world_cos(ob, edit);
1245         if (pset->flag & PE_AUTO_VELOCITY)
1246                 update_velocities(edit);
1247         PE_hide_keys_time(scene, edit, CFRA);
1248
1249         /* regenerate path caches */
1250         psys_cache_edit_paths(scene, ob, edit, CFRA);
1251
1252         /* disable update flag */
1253         LOOP_POINTS {
1254                 point->flag &= ~PEP_EDIT_RECALC;
1255         }
1256
1257         if (edit->psys)
1258                 edit->psys->flag &= ~PSYS_HAIR_UPDATED;
1259 }
1260
1261 /************************************************/
1262 /*                      Edit Selections                                         */
1263 /************************************************/
1264
1265 /*-----selection callbacks-----*/
1266
1267 static void select_key(PEData *data, int point_index, int key_index)
1268 {
1269         PTCacheEdit *edit = data->edit;
1270         PTCacheEditPoint *point = edit->points + point_index;
1271         PTCacheEditKey *key = point->keys + key_index;
1272
1273         if (data->select)
1274                 key->flag |= PEK_SELECT;
1275         else
1276                 key->flag &= ~PEK_SELECT;
1277
1278         point->flag |= PEP_EDIT_RECALC;
1279 }
1280
1281 static void select_keys(PEData *data, int point_index, int UNUSED(key_index))
1282 {
1283         PTCacheEdit *edit = data->edit;
1284         PTCacheEditPoint *point = edit->points + point_index;
1285         KEY_K;
1286
1287         LOOP_KEYS {
1288                 if (data->select)
1289                         key->flag |= PEK_SELECT;
1290                 else
1291                         key->flag &= ~PEK_SELECT;
1292         }
1293
1294         point->flag |= PEP_EDIT_RECALC;
1295 }
1296
1297 static void toggle_key_select(PEData *data, int point_index, int key_index)
1298 {
1299         PTCacheEdit *edit = data->edit;
1300         PTCacheEditPoint *point = edit->points + point_index;
1301         PTCacheEditKey *key = point->keys + key_index;
1302
1303         key->flag ^= PEK_SELECT;
1304         point->flag |= PEP_EDIT_RECALC;
1305 }
1306
1307 /************************ de select all operator ************************/
1308
1309 static int pe_select_all_exec(bContext *C, wmOperator *op)
1310 {
1311         Scene *scene= CTX_data_scene(C);
1312         Object *ob= CTX_data_active_object(C);
1313         PTCacheEdit *edit= PE_get_current(scene, ob);
1314         POINT_P; KEY_K;
1315         int action = RNA_enum_get(op->ptr, "action");
1316
1317         if (action == SEL_TOGGLE) {
1318                 action = SEL_SELECT;
1319                 LOOP_VISIBLE_POINTS {
1320                         LOOP_SELECTED_KEYS {
1321                                 action = SEL_DESELECT;
1322                                 break;
1323                         }
1324
1325                         if (action == SEL_DESELECT)
1326                                 break;
1327                 }
1328         }
1329
1330         LOOP_VISIBLE_POINTS {
1331                 LOOP_VISIBLE_KEYS {
1332                         switch (action) {
1333                         case SEL_SELECT:
1334                                 if ((key->flag & PEK_SELECT) == 0) {
1335                                         key->flag |= PEK_SELECT;
1336                                         point->flag |= PEP_EDIT_RECALC;
1337                                 }
1338                                 break;
1339                         case SEL_DESELECT:
1340                                 if (key->flag & PEK_SELECT) {
1341                                         key->flag &= ~PEK_SELECT;
1342                                         point->flag |= PEP_EDIT_RECALC;
1343                                 }
1344                                 break;
1345                         case SEL_INVERT:
1346                                 if ((key->flag & PEK_SELECT) == 0) {
1347                                         key->flag |= PEK_SELECT;
1348                                         point->flag |= PEP_EDIT_RECALC;
1349                                 }
1350                                 else {
1351                                         key->flag &= ~PEK_SELECT;
1352                                         point->flag |= PEP_EDIT_RECALC;
1353                                 }
1354                                 break;
1355                         }
1356                 }
1357         }
1358
1359         PE_update_selection(scene, ob, 1);
1360         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, ob);
1361
1362         return OPERATOR_FINISHED;
1363 }
1364
1365 void PARTICLE_OT_select_all(wmOperatorType *ot)
1366 {
1367         /* identifiers */
1368         ot->name = "(De)select All";
1369         ot->idname = "PARTICLE_OT_select_all";
1370         
1371         /* api callbacks */
1372         ot->exec = pe_select_all_exec;
1373         ot->poll = PE_poll;
1374
1375         /* flags */
1376         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1377
1378         WM_operator_properties_select_all(ot);
1379 }
1380
1381 /************************ pick select operator ************************/
1382
1383 int PE_mouse_particles(bContext *C, const int mval[2], int extend)
1384 {
1385         PEData data;
1386         Scene *scene= CTX_data_scene(C);
1387         Object *ob= CTX_data_active_object(C);
1388         PTCacheEdit *edit= PE_get_current(scene, ob);
1389         POINT_P; KEY_K;
1390         
1391         if (!PE_start_edit(edit))
1392                 return OPERATOR_CANCELLED;
1393
1394         if (!extend) {
1395                 LOOP_VISIBLE_POINTS {
1396                         LOOP_SELECTED_KEYS {
1397                                 key->flag &= ~PEK_SELECT;
1398                                 point->flag |= PEP_EDIT_RECALC;
1399                         }
1400                 }
1401         }
1402
1403         PE_set_view3d_data(C, &data);
1404         data.mval= mval;
1405         data.rad= 75.0f;
1406
1407         for_mouse_hit_keys(&data, toggle_key_select, 1);  /* nearest only */
1408
1409         PE_update_selection(scene, ob, 1);
1410         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, data.ob);
1411
1412         return OPERATOR_FINISHED;
1413 }
1414
1415 /************************ select first operator ************************/
1416
1417 static void select_root(PEData *data, int point_index)
1418 {
1419         if (data->edit->points[point_index].flag & PEP_HIDE)
1420                 return;
1421         
1422         data->edit->points[point_index].keys->flag |= PEK_SELECT;
1423         data->edit->points[point_index].flag |= PEP_EDIT_RECALC; /* redraw selection only */
1424 }
1425
1426 static int select_roots_exec(bContext *C, wmOperator *UNUSED(op))
1427 {
1428         PEData data;
1429
1430         PE_set_data(C, &data);
1431         foreach_point(&data, select_root);
1432
1433         PE_update_selection(data.scene, data.ob, 1);
1434         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, data.ob);
1435
1436         return OPERATOR_FINISHED;
1437 }
1438
1439 void PARTICLE_OT_select_roots(wmOperatorType *ot)
1440 {
1441         /* identifiers */
1442         ot->name = "Select Roots";
1443         ot->idname = "PARTICLE_OT_select_roots";
1444         
1445         /* api callbacks */
1446         ot->exec = select_roots_exec;
1447         ot->poll = PE_poll;
1448
1449         /* flags */
1450         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1451 }
1452
1453 /************************ select last operator ************************/
1454
1455 static void select_tip(PEData *data, int point_index)
1456 {
1457         PTCacheEditPoint *point = data->edit->points + point_index;
1458         
1459         if (point->flag & PEP_HIDE)
1460                 return;
1461         
1462         point->keys[point->totkey - 1].flag |= PEK_SELECT;
1463         point->flag |= PEP_EDIT_RECALC; /* redraw selection only */
1464 }
1465
1466 static int select_tips_exec(bContext *C, wmOperator *UNUSED(op))
1467 {
1468         PEData data;
1469
1470         PE_set_data(C, &data);
1471         foreach_point(&data, select_tip);
1472
1473         PE_update_selection(data.scene, data.ob, 1);
1474         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, data.ob);
1475
1476         return OPERATOR_FINISHED;
1477 }
1478
1479 void PARTICLE_OT_select_tips(wmOperatorType *ot)
1480 {
1481         /* identifiers */
1482         ot->name = "Select Tips";
1483         ot->idname = "PARTICLE_OT_select_tips";
1484         
1485         /* api callbacks */
1486         ot->exec = select_tips_exec;
1487         ot->poll = PE_poll;
1488
1489         /* flags */
1490         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1491 }
1492
1493 /************************ select linked operator ************************/
1494
1495 static int select_linked_exec(bContext *C, wmOperator *op)
1496 {
1497         PEData data;
1498         int mval[2];
1499         int location[2];
1500
1501         RNA_int_get_array(op->ptr, "location", location);
1502         mval[0]= location[0];
1503         mval[1]= location[1];
1504
1505         PE_set_view3d_data(C, &data);
1506         data.mval= mval;
1507         data.rad=75.0f;
1508         data.select= !RNA_boolean_get(op->ptr, "deselect");
1509
1510         for_mouse_hit_keys(&data, select_keys, 1);  /* nearest only */
1511         PE_update_selection(data.scene, data.ob, 1);
1512         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, data.ob);
1513
1514         return OPERATOR_FINISHED;
1515 }
1516
1517 static int select_linked_invoke(bContext *C, wmOperator *op, wmEvent *event)
1518 {
1519         RNA_int_set_array(op->ptr, "location", event->mval);
1520         return select_linked_exec(C, op);
1521 }
1522
1523 void PARTICLE_OT_select_linked(wmOperatorType *ot)
1524 {
1525         /* identifiers */
1526         ot->name = "Select Linked";
1527         ot->idname = "PARTICLE_OT_select_linked";
1528         
1529         /* api callbacks */
1530         ot->exec = select_linked_exec;
1531         ot->invoke = select_linked_invoke;
1532         ot->poll = PE_poll_view3d;
1533
1534         /* flags */
1535         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1536
1537         /* properties */
1538         RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "Deselect linked keys rather than selecting them");
1539         RNA_def_int_vector(ot->srna, "location", 2, NULL, 0, INT_MAX, "Location", "", 0, 16384);
1540 }
1541
1542 /************************ border select operator ************************/
1543 void PE_deselect_all_visible(PTCacheEdit *edit)
1544 {
1545         POINT_P; KEY_K;
1546
1547         LOOP_VISIBLE_POINTS {
1548                 LOOP_SELECTED_KEYS {
1549                         key->flag &= ~PEK_SELECT;
1550                         point->flag |= PEP_EDIT_RECALC;
1551                 }
1552         }
1553 }
1554
1555 int PE_border_select(bContext *C, rcti *rect, int select, int extend)
1556 {
1557         Scene *scene= CTX_data_scene(C);
1558         Object *ob= CTX_data_active_object(C);
1559         PTCacheEdit *edit= PE_get_current(scene, ob);
1560         PEData data;
1561
1562         if (!PE_start_edit(edit))
1563                 return OPERATOR_CANCELLED;
1564
1565         if (extend == 0 && select)
1566                 PE_deselect_all_visible(edit);
1567
1568         PE_set_view3d_data(C, &data);
1569         data.rect= rect;
1570         data.select= select;
1571
1572         for_mouse_hit_keys(&data, select_key, 0);
1573
1574         PE_update_selection(scene, ob, 1);
1575         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, ob);
1576
1577         return OPERATOR_FINISHED;
1578 }
1579
1580 /************************ circle select operator ************************/
1581
1582 int PE_circle_select(bContext *C, int selecting, const int mval[2], float rad)
1583 {
1584         Scene *scene= CTX_data_scene(C);
1585         Object *ob= CTX_data_active_object(C);
1586         PTCacheEdit *edit= PE_get_current(scene, ob);
1587         PEData data;
1588
1589         if (!PE_start_edit(edit))
1590                 return OPERATOR_FINISHED;
1591
1592         PE_set_view3d_data(C, &data);
1593         data.mval= mval;
1594         data.rad= rad;
1595         data.select= selecting;
1596
1597         for_mouse_hit_keys(&data, select_key, 0);
1598
1599         PE_update_selection(scene, ob, 1);
1600         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, ob);
1601
1602         return OPERATOR_FINISHED;
1603 }
1604
1605 /************************ lasso select operator ************************/
1606
1607 int PE_lasso_select(bContext *C, int mcords[][2], short moves, short extend, short select)
1608 {
1609         Scene *scene= CTX_data_scene(C);
1610         Object *ob= CTX_data_active_object(C);
1611         ARegion *ar= CTX_wm_region(C);
1612         ParticleEditSettings *pset= PE_settings(scene);
1613         PTCacheEdit *edit = PE_get_current(scene, ob);
1614         ParticleSystem *psys = edit->psys;
1615         ParticleSystemModifierData *psmd = psys_get_modifier(ob, psys);
1616         POINT_P; KEY_K;
1617         float co[3], mat[4][4]= MAT4_UNITY;
1618         int vertco[2];
1619
1620         PEData data;
1621
1622         if (!PE_start_edit(edit))
1623                 return OPERATOR_CANCELLED;
1624
1625         if (extend == 0 && select)
1626                 PE_deselect_all_visible(edit);
1627
1628         /* only for depths */
1629         PE_set_view3d_data(C, &data);
1630
1631         LOOP_VISIBLE_POINTS {
1632                 if (edit->psys && !(psys->flag & PSYS_GLOBAL_HAIR))
1633                         psys_mat_hair_to_global(ob, psmd->dm, psys->part->from, psys->particles + p, mat);
1634
1635                 if (pset->selectmode==SCE_SELECT_POINT) {
1636                         LOOP_KEYS {
1637                                 copy_v3_v3(co, key->co);
1638                                 mul_m4_v3(mat, co);
1639                                 project_int(ar, co, vertco);
1640                                 if (BLI_lasso_is_point_inside(mcords, moves, vertco[0], vertco[1], IS_CLIPPED) &&
1641                                     key_test_depth(&data, co))
1642                                 {
1643                                         if (select && !(key->flag & PEK_SELECT)) {
1644                                                 key->flag |= PEK_SELECT;
1645                                                 point->flag |= PEP_EDIT_RECALC;
1646                                         }
1647                                         else if (key->flag & PEK_SELECT) {
1648                                                 key->flag &= ~PEK_SELECT;
1649                                                 point->flag |= PEP_EDIT_RECALC;
1650                                         }
1651                                 }
1652                         }
1653                 }
1654                 else if (pset->selectmode==SCE_SELECT_END) {
1655                         key= point->keys + point->totkey - 1;
1656
1657                         copy_v3_v3(co, key->co);
1658                         mul_m4_v3(mat, co);
1659                         project_int(ar, co, vertco);
1660                         if (BLI_lasso_is_point_inside(mcords, moves, vertco[0], vertco[1], IS_CLIPPED) &&
1661                             key_test_depth(&data, co))
1662                         {
1663                                 if (select && !(key->flag & PEK_SELECT)) {
1664                                         key->flag |= PEK_SELECT;
1665                                         point->flag |= PEP_EDIT_RECALC;
1666                                 }
1667                                 else if (key->flag & PEK_SELECT) {
1668                                         key->flag &= ~PEK_SELECT;
1669                                         point->flag |= PEP_EDIT_RECALC;
1670                                 }
1671                         }
1672                 }
1673         }
1674
1675         PE_update_selection(scene, ob, 1);
1676         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, ob);
1677
1678         return OPERATOR_FINISHED;
1679 }
1680
1681 /*************************** hide operator **************************/
1682
1683 static int hide_exec(bContext *C, wmOperator *op)
1684 {
1685         Object *ob= CTX_data_active_object(C);
1686         Scene *scene= CTX_data_scene(C);
1687         PTCacheEdit *edit= PE_get_current(scene, ob);
1688         POINT_P; KEY_K;
1689         
1690         if (RNA_enum_get(op->ptr, "unselected")) {
1691                 LOOP_UNSELECTED_POINTS {
1692                         point->flag |= PEP_HIDE;
1693                         point->flag |= PEP_EDIT_RECALC;
1694
1695                         LOOP_KEYS
1696                                 key->flag &= ~PEK_SELECT;
1697                 }
1698         }
1699         else {
1700                 LOOP_SELECTED_POINTS {
1701                         point->flag |= PEP_HIDE;
1702                         point->flag |= PEP_EDIT_RECALC;
1703
1704                         LOOP_KEYS
1705                                 key->flag &= ~PEK_SELECT;
1706                 }
1707         }
1708
1709         PE_update_selection(scene, ob, 1);
1710         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, ob);
1711
1712         return OPERATOR_FINISHED;
1713 }
1714
1715 void PARTICLE_OT_hide(wmOperatorType *ot)
1716 {
1717         /* identifiers */
1718         ot->name = "Hide Selected";
1719         ot->idname = "PARTICLE_OT_hide";
1720         
1721         /* api callbacks */
1722         ot->exec = hide_exec;
1723         ot->poll = PE_poll;
1724
1725         /* flags */
1726         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1727
1728         /* props */
1729         RNA_def_boolean(ot->srna, "unselected", 0, "Unselected", "Hide unselected rather than selected");
1730 }
1731
1732 /*************************** reveal operator **************************/
1733
1734 static int reveal_exec(bContext *C, wmOperator *UNUSED(op))
1735 {
1736         Object *ob= CTX_data_active_object(C);
1737         Scene *scene= CTX_data_scene(C);
1738         PTCacheEdit *edit= PE_get_current(scene, ob);
1739         POINT_P; KEY_K;
1740
1741         LOOP_POINTS {
1742                 if (point->flag & PEP_HIDE) {
1743                         point->flag &= ~PEP_HIDE;
1744                         point->flag |= PEP_EDIT_RECALC;
1745
1746                         LOOP_KEYS
1747                                 key->flag |= PEK_SELECT;
1748                 }
1749         }
1750
1751         PE_update_selection(scene, ob, 1);
1752         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, ob);
1753
1754         return OPERATOR_FINISHED;
1755 }
1756
1757 void PARTICLE_OT_reveal(wmOperatorType *ot)
1758 {
1759         /* identifiers */
1760         ot->name = "Reveal";
1761         ot->idname = "PARTICLE_OT_reveal";
1762         
1763         /* api callbacks */
1764         ot->exec = reveal_exec;
1765         ot->poll = PE_poll;
1766
1767         /* flags */
1768         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1769 }
1770
1771 /************************ select less operator ************************/
1772
1773 static void select_less_keys(PEData *data, int point_index)
1774 {
1775         PTCacheEdit *edit= data->edit;
1776         PTCacheEditPoint *point = edit->points + point_index;
1777         KEY_K;
1778
1779         LOOP_SELECTED_KEYS {
1780                 if (k==0) {
1781                         if (((key+1)->flag&PEK_SELECT)==0)
1782                                 key->flag |= PEK_TAG;
1783                 }
1784                 else if (k==point->totkey-1) {
1785                         if (((key-1)->flag&PEK_SELECT)==0)
1786                                 key->flag |= PEK_TAG;
1787                 }
1788                 else {
1789                         if ((((key-1)->flag & (key+1)->flag) & PEK_SELECT)==0)
1790                                 key->flag |= PEK_TAG;
1791                 }
1792         }
1793
1794         LOOP_KEYS {
1795                 if (key->flag&PEK_TAG) {
1796                         key->flag &= ~(PEK_TAG|PEK_SELECT);
1797                         point->flag |= PEP_EDIT_RECALC; /* redraw selection only */
1798                 }
1799         }
1800 }
1801
1802 static int select_less_exec(bContext *C, wmOperator *UNUSED(op))
1803 {
1804         PEData data;
1805
1806         PE_set_data(C, &data);
1807         foreach_point(&data, select_less_keys);
1808
1809         PE_update_selection(data.scene, data.ob, 1);
1810         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, data.ob);
1811
1812         return OPERATOR_FINISHED;
1813 }
1814
1815 void PARTICLE_OT_select_less(wmOperatorType *ot)
1816 {
1817         /* identifiers */
1818         ot->name = "Select Less";
1819         ot->idname = "PARTICLE_OT_select_less";
1820         
1821         /* api callbacks */
1822         ot->exec = select_less_exec;
1823         ot->poll = PE_poll;
1824
1825         /* flags */
1826         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1827 }
1828
1829 /************************ select more operator ************************/
1830
1831 static void select_more_keys(PEData *data, int point_index)
1832 {
1833         PTCacheEdit *edit= data->edit;
1834         PTCacheEditPoint *point = edit->points + point_index;
1835         KEY_K;
1836
1837         LOOP_KEYS {
1838                 if (key->flag & PEK_SELECT) continue;
1839
1840                 if (k==0) {
1841                         if ((key+1)->flag&PEK_SELECT)
1842                                 key->flag |= PEK_TAG;
1843                 }
1844                 else if (k==point->totkey-1) {
1845                         if ((key-1)->flag&PEK_SELECT)
1846                                 key->flag |= PEK_TAG;
1847                 }
1848                 else {
1849                         if (((key-1)->flag | (key+1)->flag) & PEK_SELECT)
1850                                 key->flag |= PEK_TAG;
1851                 }
1852         }
1853
1854         LOOP_KEYS {
1855                 if (key->flag&PEK_TAG) {
1856                         key->flag &= ~PEK_TAG;
1857                         key->flag |= PEK_SELECT;
1858                         point->flag |= PEP_EDIT_RECALC; /* redraw selection only */
1859                 }
1860         }
1861 }
1862
1863 static int select_more_exec(bContext *C, wmOperator *UNUSED(op))
1864 {
1865         PEData data;
1866
1867         PE_set_data(C, &data);
1868         foreach_point(&data, select_more_keys);
1869
1870         PE_update_selection(data.scene, data.ob, 1);
1871         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, data.ob);
1872
1873         return OPERATOR_FINISHED;
1874 }
1875
1876 void PARTICLE_OT_select_more(wmOperatorType *ot)
1877 {
1878         /* identifiers */
1879         ot->name = "Select More";
1880         ot->idname = "PARTICLE_OT_select_more";
1881         
1882         /* api callbacks */
1883         ot->exec = select_more_exec;
1884         ot->poll = PE_poll;
1885
1886         /* flags */
1887         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1888 }
1889
1890 /************************ rekey operator ************************/
1891
1892 static void rekey_particle(PEData *data, int pa_index)
1893 {
1894         PTCacheEdit *edit= data->edit;
1895         ParticleSystem *psys= edit->psys;
1896         ParticleSimulationData sim= {0};
1897         ParticleData *pa= psys->particles + pa_index;
1898         PTCacheEditPoint *point = edit->points + pa_index;
1899         ParticleKey state;
1900         HairKey *key, *new_keys, *okey;
1901         PTCacheEditKey *ekey;
1902         float dval, sta, end;
1903         int k;
1904
1905         sim.scene= data->scene;
1906         sim.ob= data->ob;
1907         sim.psys= edit->psys;
1908
1909         pa->flag |= PARS_REKEY;
1910
1911         key= new_keys= MEM_callocN(data->totrekey * sizeof(HairKey), "Hair re-key keys");
1912
1913         okey = pa->hair;
1914         /* root and tip stay the same */
1915         copy_v3_v3(key->co, okey->co);
1916         copy_v3_v3((key + data->totrekey - 1)->co, (okey + pa->totkey - 1)->co);
1917
1918         sta= key->time= okey->time;
1919         end= (key + data->totrekey - 1)->time= (okey + pa->totkey - 1)->time;
1920         dval= (end - sta) / (float)(data->totrekey - 1);
1921
1922         /* interpolate new keys from old ones */
1923         for (k=1, key++; k<data->totrekey-1; k++, key++) {
1924                 state.time= (float)k / (float)(data->totrekey-1);
1925                 psys_get_particle_on_path(&sim, pa_index, &state, 0);
1926                 copy_v3_v3(key->co, state.co);
1927                 key->time= sta + k * dval;
1928         }
1929
1930         /* replace keys */
1931         if (pa->hair)
1932                 MEM_freeN(pa->hair);
1933         pa->hair= new_keys;
1934
1935         point->totkey=pa->totkey=data->totrekey;
1936
1937
1938         if (point->keys)
1939                 MEM_freeN(point->keys);
1940         ekey= point->keys= MEM_callocN(pa->totkey * sizeof(PTCacheEditKey), "Hair re-key edit keys");
1941                 
1942         for (k=0, key=pa->hair; k<pa->totkey; k++, key++, ekey++) {
1943                 ekey->co= key->co;
1944                 ekey->time= &key->time;
1945                 ekey->flag |= PEK_SELECT;
1946                 if (!(psys->flag & PSYS_GLOBAL_HAIR))
1947                         ekey->flag |= PEK_USE_WCO;
1948         }
1949
1950         pa->flag &= ~PARS_REKEY;
1951         point->flag |= PEP_EDIT_RECALC;
1952 }
1953
1954 static int rekey_exec(bContext *C, wmOperator *op)
1955 {
1956         PEData data;
1957
1958         PE_set_data(C, &data);
1959
1960         data.dval= 1.0f / (float)(data.totrekey-1);
1961         data.totrekey= RNA_int_get(op->ptr, "keys");
1962
1963         foreach_selected_point(&data, rekey_particle);
1964         
1965         recalc_lengths(data.edit);
1966         PE_update_object(data.scene, data.ob, 1);
1967         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, data.ob);
1968
1969         return OPERATOR_FINISHED;
1970 }
1971
1972 void PARTICLE_OT_rekey(wmOperatorType *ot)
1973 {
1974         /* identifiers */
1975         ot->name = "Rekey";
1976         ot->idname = "PARTICLE_OT_rekey";
1977         
1978         /* api callbacks */
1979         ot->exec = rekey_exec;
1980         ot->invoke = WM_operator_props_popup;
1981         ot->poll = PE_hair_poll;
1982
1983         /* flags */
1984         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1985
1986         /* properties */
1987         RNA_def_int(ot->srna, "keys", 2, 2, INT_MAX, "Number of Keys", "", 2, 100);
1988 }
1989
1990 static void rekey_particle_to_time(Scene *scene, Object *ob, int pa_index, float path_time)
1991 {
1992         PTCacheEdit *edit= PE_get_current(scene, ob);
1993         ParticleSystem *psys;
1994         ParticleSimulationData sim= {0};
1995         ParticleData *pa;
1996         ParticleKey state;
1997         HairKey *new_keys, *key;
1998         PTCacheEditKey *ekey;
1999         int k;
2000
2001         if (!edit || !edit->psys) return;
2002
2003         psys = edit->psys;
2004
2005         sim.scene= scene;
2006         sim.ob= ob;
2007         sim.psys= psys;
2008
2009         pa= psys->particles + pa_index;
2010
2011         pa->flag |= PARS_REKEY;
2012
2013         key= new_keys= MEM_dupallocN(pa->hair);
2014         
2015         /* interpolate new keys from old ones (roots stay the same) */
2016         for (k=1, key++; k < pa->totkey; k++, key++) {
2017                 state.time= path_time * (float)k / (float)(pa->totkey-1);
2018                 psys_get_particle_on_path(&sim, pa_index, &state, 0);
2019                 copy_v3_v3(key->co, state.co);
2020         }
2021
2022         /* replace hair keys */
2023         if (pa->hair)
2024                 MEM_freeN(pa->hair);
2025         pa->hair= new_keys;
2026
2027         /* update edit pointers */
2028         for (k=0, key=pa->hair, ekey=edit->points[pa_index].keys; k<pa->totkey; k++, key++, ekey++) {
2029                 ekey->co= key->co;
2030                 ekey->time= &key->time;
2031         }
2032
2033         pa->flag &= ~PARS_REKEY;
2034 }
2035
2036 /************************* utilities **************************/
2037
2038 static int remove_tagged_particles(Object *ob, ParticleSystem *psys, int mirror)
2039 {
2040         PTCacheEdit *edit = psys->edit;
2041         ParticleData *pa, *npa=0, *new_pars=0;
2042         POINT_P;
2043         PTCacheEditPoint *npoint=0, *new_points=0;
2044         ParticleSystemModifierData *psmd;
2045         int i, new_totpart= psys->totpart, removed= 0;
2046
2047         if (mirror) {
2048                 /* mirror tags */
2049                 psmd= psys_get_modifier(ob, psys);
2050
2051                 LOOP_TAGGED_POINTS {
2052                         PE_mirror_particle(ob, psmd->dm, psys, psys->particles + p, NULL);
2053                 }
2054         }
2055
2056         LOOP_TAGGED_POINTS {
2057                 new_totpart--;
2058                 removed++;
2059         }
2060
2061         if (new_totpart != psys->totpart) {
2062                 if (new_totpart) {
2063                         npa= new_pars= MEM_callocN(new_totpart * sizeof(ParticleData), "ParticleData array");
2064                         npoint= new_points= MEM_callocN(new_totpart * sizeof(PTCacheEditPoint), "PTCacheEditKey array");
2065
2066                         if (ELEM(NULL, new_pars, new_points)) {
2067                                  /* allocation error! */
2068                                 if (new_pars)
2069                                         MEM_freeN(new_pars);
2070                                 if (new_points)
2071                                         MEM_freeN(new_points);
2072                                 return 0;
2073                         }
2074                 }
2075
2076                 pa= psys->particles;
2077                 point= edit->points;
2078                 for (i=0; i<psys->totpart; i++, pa++, point++) {
2079                         if (point->flag & PEP_TAG) {
2080                                 if (point->keys)
2081                                         MEM_freeN(point->keys);
2082                                 if (pa->hair)
2083                                         MEM_freeN(pa->hair);
2084                         }
2085                         else {
2086                                 memcpy(npa, pa, sizeof(ParticleData));
2087                                 memcpy(npoint, point, sizeof(PTCacheEditPoint));
2088                                 npa++;
2089                                 npoint++;
2090                         }
2091                 }
2092
2093                 if (psys->particles) MEM_freeN(psys->particles);
2094                 psys->particles= new_pars;
2095
2096                 if (edit->points) MEM_freeN(edit->points);
2097                 edit->points= new_points;
2098
2099                 if (edit->mirror_cache) {
2100                         MEM_freeN(edit->mirror_cache);
2101                         edit->mirror_cache= NULL;
2102                 }
2103
2104                 if (psys->child) {
2105                         MEM_freeN(psys->child);
2106                         psys->child= NULL;
2107                         psys->totchild=0;
2108                 }
2109
2110                 edit->totpoint= psys->totpart= new_totpart;
2111         }
2112
2113         return removed;
2114 }
2115
2116 static void remove_tagged_keys(Object *ob, ParticleSystem *psys)
2117 {
2118         PTCacheEdit *edit= psys->edit;
2119         ParticleData *pa;
2120         HairKey *hkey, *nhkey, *new_hkeys=0;
2121         POINT_P; KEY_K;
2122         PTCacheEditKey *nkey, *new_keys;
2123         ParticleSystemModifierData *psmd;
2124         short new_totkey;
2125
2126         if (pe_x_mirror(ob)) {
2127                 /* mirror key tags */
2128                 psmd= psys_get_modifier(ob, psys);
2129
2130                 LOOP_POINTS {
2131                         LOOP_TAGGED_KEYS {
2132                                 PE_mirror_particle(ob, psmd->dm, psys, psys->particles + p, NULL);
2133                                 break;
2134                         }
2135                 }
2136         }
2137
2138         LOOP_POINTS {
2139                 new_totkey= point->totkey;
2140                 LOOP_TAGGED_KEYS {
2141                         new_totkey--;
2142                 }
2143                 /* we can't have elements with less than two keys*/
2144                 if (new_totkey < 2)
2145                         point->flag |= PEP_TAG;
2146         }
2147         remove_tagged_particles(ob, psys, pe_x_mirror(ob));
2148
2149         LOOP_POINTS {
2150                 pa = psys->particles + p;
2151                 new_totkey= pa->totkey;
2152
2153                 LOOP_TAGGED_KEYS {
2154                         new_totkey--;
2155                 }
2156
2157                 if (new_totkey != pa->totkey) {
2158                         nhkey= new_hkeys= MEM_callocN(new_totkey*sizeof(HairKey), "HairKeys");
2159                         nkey= new_keys= MEM_callocN(new_totkey*sizeof(PTCacheEditKey), "particle edit keys");
2160
2161                         hkey= pa->hair;
2162                         LOOP_KEYS {
2163                                 while (key->flag & PEK_TAG && hkey < pa->hair + pa->totkey) {
2164                                         key++;
2165                                         hkey++;
2166                                 }
2167
2168                                 if (hkey < pa->hair + pa->totkey) {
2169                                         copy_v3_v3(nhkey->co, hkey->co);
2170                                         nhkey->editflag = hkey->editflag;
2171                                         nhkey->time= hkey->time;
2172                                         nhkey->weight= hkey->weight;
2173                                         
2174                                         nkey->co= nhkey->co;
2175                                         nkey->time= &nhkey->time;
2176                                         /* these can be copied from old edit keys */
2177                                         nkey->flag = key->flag;
2178                                         nkey->ftime = key->ftime;
2179                                         nkey->length = key->length;
2180                                         copy_v3_v3(nkey->world_co, key->world_co);
2181                                 }
2182                                 nkey++;
2183                                 nhkey++;
2184                                 hkey++;
2185                         }
2186
2187                         if (pa->hair)
2188                                 MEM_freeN(pa->hair);
2189
2190                         if (point->keys)
2191                                 MEM_freeN(point->keys);
2192                         
2193                         pa->hair= new_hkeys;
2194                         point->keys= new_keys;
2195
2196                         point->totkey= pa->totkey= new_totkey;
2197
2198                         /* flag for recalculating length */
2199                         point->flag |= PEP_EDIT_RECALC;
2200                 }
2201         }
2202 }
2203
2204 /************************ subdivide opertor *********************/
2205
2206 /* works like normal edit mode subdivide, inserts keys between neighboring selected keys */
2207 static void subdivide_particle(PEData *data, int pa_index)
2208 {
2209         PTCacheEdit *edit= data->edit;
2210         ParticleSystem *psys= edit->psys;
2211         ParticleSimulationData sim= {0};
2212         ParticleData *pa= psys->particles + pa_index;
2213         PTCacheEditPoint *point = edit->points + pa_index;
2214         ParticleKey state;
2215         HairKey *key, *nkey, *new_keys;
2216         PTCacheEditKey *ekey, *nekey, *new_ekeys;
2217
2218         int k;
2219         short totnewkey=0;
2220         float endtime;
2221
2222         sim.scene= data->scene;
2223         sim.ob= data->ob;
2224         sim.psys= edit->psys;
2225
2226         for (k=0, ekey=point->keys; k<pa->totkey-1; k++, ekey++) {
2227                 if (ekey->flag&PEK_SELECT && (ekey+1)->flag&PEK_SELECT)
2228                         totnewkey++;
2229         }
2230
2231         if (totnewkey==0) return;
2232
2233         pa->flag |= PARS_REKEY;
2234
2235         nkey= new_keys= MEM_callocN((pa->totkey+totnewkey)*(sizeof(HairKey)), "Hair subdivide keys");
2236         nekey= new_ekeys= MEM_callocN((pa->totkey+totnewkey)*(sizeof(PTCacheEditKey)), "Hair subdivide edit keys");
2237         
2238         key = pa->hair;
2239         endtime= key[pa->totkey-1].time;
2240
2241         for (k=0, ekey=point->keys; k<pa->totkey-1; k++, key++, ekey++) {
2242
2243                 memcpy(nkey, key, sizeof(HairKey));
2244                 memcpy(nekey, ekey, sizeof(PTCacheEditKey));
2245
2246                 nekey->co= nkey->co;
2247                 nekey->time= &nkey->time;
2248
2249                 nkey++;
2250                 nekey++;
2251
2252                 if (ekey->flag & PEK_SELECT && (ekey+1)->flag & PEK_SELECT) {
2253                         nkey->time= (key->time + (key+1)->time)*0.5f;
2254                         state.time= (endtime != 0.0f)? nkey->time/endtime: 0.0f;
2255                         psys_get_particle_on_path(&sim, pa_index, &state, 0);
2256                         copy_v3_v3(nkey->co, state.co);
2257
2258                         nekey->co= nkey->co;
2259                         nekey->time= &nkey->time;
2260                         nekey->flag |= PEK_SELECT;
2261                         if (!(psys->flag & PSYS_GLOBAL_HAIR))
2262                                 nekey->flag |= PEK_USE_WCO;
2263
2264                         nekey++;
2265                         nkey++;
2266                 }
2267         }
2268         /*tip still not copied*/
2269         memcpy(nkey, key, sizeof(HairKey));
2270         memcpy(nekey, ekey, sizeof(PTCacheEditKey));
2271
2272         nekey->co= nkey->co;
2273         nekey->time= &nkey->time;
2274
2275         if (pa->hair)
2276                 MEM_freeN(pa->hair);
2277         pa->hair= new_keys;
2278
2279         if (point->keys)
2280                 MEM_freeN(point->keys);
2281         point->keys= new_ekeys;
2282
2283         point->totkey = pa->totkey = pa->totkey + totnewkey;
2284         point->flag |= PEP_EDIT_RECALC;
2285         pa->flag &= ~PARS_REKEY;
2286 }
2287
2288 static int subdivide_exec(bContext *C, wmOperator *UNUSED(op))
2289 {
2290         PEData data;
2291
2292         PE_set_data(C, &data);
2293         foreach_point(&data, subdivide_particle);
2294         
2295         recalc_lengths(data.edit);
2296         PE_update_object(data.scene, data.ob, 1);
2297         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, data.ob);
2298
2299         return OPERATOR_FINISHED;
2300 }
2301
2302 void PARTICLE_OT_subdivide(wmOperatorType *ot)
2303 {
2304         /* identifiers */
2305         ot->name = "Subdivide";
2306         ot->idname = "PARTICLE_OT_subdivide";
2307         
2308         /* api callbacks */
2309         ot->exec = subdivide_exec;
2310         ot->poll = PE_hair_poll;
2311
2312         /* flags */
2313         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2314 }
2315
2316 /************************ remove doubles opertor *********************/
2317
2318 static int remove_doubles_exec(bContext *C, wmOperator *op)
2319 {
2320         Scene *scene= CTX_data_scene(C);
2321         Object *ob= CTX_data_active_object(C);
2322         PTCacheEdit *edit= PE_get_current(scene, ob);
2323         ParticleSystem *psys = edit->psys;
2324         ParticleSystemModifierData *psmd;
2325         KDTree *tree;
2326         KDTreeNearest nearest[10];
2327         POINT_P;
2328         float mat[4][4], co[3], threshold= RNA_float_get(op->ptr, "threshold");
2329         int n, totn, removed, totremoved;
2330
2331         if (psys->flag & PSYS_GLOBAL_HAIR)
2332                 return OPERATOR_CANCELLED;
2333
2334         edit= psys->edit;
2335         psmd= psys_get_modifier(ob, psys);
2336         totremoved= 0;
2337
2338         do {
2339                 removed= 0;
2340
2341                 tree=BLI_kdtree_new(psys->totpart);
2342                         
2343                 /* insert particles into kd tree */
2344                 LOOP_SELECTED_POINTS {
2345                         psys_mat_hair_to_object(ob, psmd->dm, psys->part->from, psys->particles+p, mat);
2346                         copy_v3_v3(co, point->keys->co);
2347                         mul_m4_v3(mat, co);
2348                         BLI_kdtree_insert(tree, p, co, NULL);
2349                 }
2350
2351                 BLI_kdtree_balance(tree);
2352
2353                 /* tag particles to be removed */
2354                 LOOP_SELECTED_POINTS {
2355                         psys_mat_hair_to_object(ob, psmd->dm, psys->part->from, psys->particles+p, mat);
2356                         copy_v3_v3(co, point->keys->co);
2357                         mul_m4_v3(mat, co);
2358
2359                         totn= BLI_kdtree_find_n_nearest(tree, 10, co, NULL, nearest);
2360
2361                         for (n=0; n<totn; n++) {
2362                                 /* this needs a custom threshold still */
2363                                 if (nearest[n].index > p && nearest[n].dist < threshold) {
2364                                         if (!(point->flag & PEP_TAG)) {
2365                                                 point->flag |= PEP_TAG;
2366                                                 removed++;
2367                                         }
2368                                 }
2369                         }
2370                 }
2371
2372                 BLI_kdtree_free(tree);
2373
2374                 /* remove tagged particles - don't do mirror here! */
2375                 remove_tagged_particles(ob, psys, 0);
2376                 totremoved += removed;
2377         } while (removed);
2378
2379         if (totremoved == 0)
2380                 return OPERATOR_CANCELLED;
2381
2382         BKE_reportf(op->reports, RPT_INFO, "Remove %d double particles", totremoved);
2383
2384         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2385         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, ob);
2386
2387         return OPERATOR_FINISHED;
2388 }
2389
2390 void PARTICLE_OT_remove_doubles(wmOperatorType *ot)
2391 {
2392         /* identifiers */
2393         ot->name = "Remove Doubles";
2394         ot->idname = "PARTICLE_OT_remove_doubles";
2395         
2396         /* api callbacks */
2397         ot->exec = remove_doubles_exec;
2398         ot->poll = PE_hair_poll;
2399
2400         /* flags */
2401         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2402
2403         /* properties */
2404         RNA_def_float(ot->srna, "threshold", 0.0002f, 0.0f, FLT_MAX, "Threshold", "Threshold distance withing which particles are removed", 0.00001f, 0.1f);
2405 }
2406
2407
2408 static int weight_set_exec(bContext *C, wmOperator *op)
2409 {
2410         Scene *scene= CTX_data_scene(C);
2411         ParticleEditSettings *pset= PE_settings(scene);
2412         Object *ob= CTX_data_active_object(C);
2413         PTCacheEdit *edit= PE_get_current(scene, ob);
2414         ParticleSystem *psys = edit->psys;
2415         POINT_P;
2416         KEY_K;
2417         HairKey *hkey;
2418         float weight;
2419         ParticleBrushData *brush= &pset->brush[pset->brushtype];
2420         float factor= RNA_float_get(op->ptr, "factor");
2421
2422         weight= brush->strength;
2423         edit= psys->edit;
2424
2425         LOOP_SELECTED_POINTS {
2426                 ParticleData *pa= psys->particles + p;
2427
2428                 LOOP_SELECTED_KEYS {
2429                         hkey= pa->hair + k;
2430                         hkey->weight= interpf(weight, hkey->weight, factor);
2431                 }
2432         }
2433
2434         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2435         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, ob);
2436
2437         return OPERATOR_FINISHED;
2438 }
2439
2440 void PARTICLE_OT_weight_set(wmOperatorType *ot)
2441 {
2442         /* identifiers */
2443         ot->name = "Weight Set";
2444         ot->idname = "PARTICLE_OT_weight_set";
2445
2446         /* api callbacks */
2447         ot->exec = weight_set_exec;
2448         ot->poll = PE_hair_poll;
2449
2450         /* flags */
2451         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2452
2453         RNA_def_float(ot->srna, "factor", 1, 0, 1, "Factor", "", 0, 1);
2454 }
2455
2456 /************************ cursor drawing *******************************/
2457
2458 static void brush_drawcursor(bContext *C, int x, int y, void *UNUSED(customdata))
2459 {
2460         ParticleEditSettings *pset= PE_settings(CTX_data_scene(C));
2461         ParticleBrushData *brush;
2462
2463         if (pset->brushtype < 0)
2464                 return;
2465
2466         brush= &pset->brush[pset->brushtype];
2467
2468         if (brush) {
2469                 glPushMatrix();
2470
2471                 glTranslatef((float)x, (float)y, 0.0f);
2472
2473                 glColor4ub(255, 255, 255, 128);
2474                 glEnable(GL_LINE_SMOOTH);
2475                 glEnable(GL_BLEND);
2476                 glutil_draw_lined_arc(0.0, M_PI*2.0, brush->size, 40);
2477                 glDisable(GL_BLEND);
2478                 glDisable(GL_LINE_SMOOTH);
2479                 
2480                 glPopMatrix();
2481         }
2482 }
2483
2484 static void toggle_particle_cursor(bContext *C, int enable)
2485 {
2486         ParticleEditSettings *pset= PE_settings(CTX_data_scene(C));
2487
2488         if (pset->paintcursor && !enable) {
2489                 WM_paint_cursor_end(CTX_wm_manager(C), pset->paintcursor);
2490                 pset->paintcursor = NULL;
2491         }
2492         else if (enable)
2493                 pset->paintcursor= WM_paint_cursor_activate(CTX_wm_manager(C), PE_poll_view3d, brush_drawcursor, NULL);
2494 }
2495
2496 /*************************** delete operator **************************/
2497
2498 enum { DEL_PARTICLE, DEL_KEY };
2499
2500 static EnumPropertyItem delete_type_items[]= {
2501         {DEL_PARTICLE, "PARTICLE", 0, "Particle", ""},
2502         {DEL_KEY, "KEY", 0, "Key", ""},
2503         {0, NULL, 0, NULL, NULL}};
2504
2505 static void set_delete_particle(PEData *data, int pa_index)
2506 {
2507         PTCacheEdit *edit= data->edit;
2508
2509         edit->points[pa_index].flag |= PEP_TAG;
2510 }
2511
2512 static void set_delete_particle_key(PEData *data, int pa_index, int key_index)
2513 {
2514         PTCacheEdit *edit= data->edit;
2515
2516         edit->points[pa_index].keys[key_index].flag |= PEK_TAG;
2517 }
2518
2519 static int delete_exec(bContext *C, wmOperator *op)
2520 {
2521         PEData data;
2522         int type= RNA_enum_get(op->ptr, "type");
2523
2524         PE_set_data(C, &data);
2525
2526         if (type == DEL_KEY) {
2527                 foreach_selected_key(&data, set_delete_particle_key);
2528                 remove_tagged_keys(data.ob, data.edit->psys);
2529                 recalc_lengths(data.edit);
2530         }
2531         else if (type == DEL_PARTICLE) {
2532                 foreach_selected_point(&data, set_delete_particle);
2533                 remove_tagged_particles(data.ob, data.edit->psys, pe_x_mirror(data.ob));
2534                 recalc_lengths(data.edit);
2535         }
2536
2537         DAG_id_tag_update(&data.ob->id, OB_RECALC_DATA);
2538         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, data.ob);
2539
2540         return OPERATOR_FINISHED;
2541 }
2542
2543 void PARTICLE_OT_delete(wmOperatorType *ot)
2544 {
2545         /* identifiers */
2546         ot->name = "Delete";
2547         ot->idname = "PARTICLE_OT_delete";
2548         
2549         /* api callbacks */
2550         ot->exec = delete_exec;
2551         ot->invoke = WM_menu_invoke;
2552         ot->poll = PE_hair_poll;
2553
2554         /* flags */
2555         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2556
2557         /* properties */
2558         ot->prop = RNA_def_enum(ot->srna, "type", delete_type_items, DEL_PARTICLE, "Type", "Delete a full particle or only keys");
2559 }
2560
2561 /*************************** mirror operator **************************/
2562
2563 static void PE_mirror_x(Scene *scene, Object *ob, int tagged)
2564 {
2565         Mesh *me= (Mesh*)(ob->data);
2566         ParticleSystemModifierData *psmd;
2567         PTCacheEdit *edit= PE_get_current(scene, ob);
2568         ParticleSystem *psys = edit->psys;
2569         ParticleData *pa, *newpa, *new_pars;
2570         PTCacheEditPoint *newpoint, *new_points;
2571         POINT_P; KEY_K;
2572         HairKey *hkey;
2573         int *mirrorfaces = NULL;
2574         int rotation, totpart, newtotpart;
2575
2576         if (psys->flag & PSYS_GLOBAL_HAIR)
2577                 return;
2578
2579         psmd= psys_get_modifier(ob, psys);
2580         if (!psmd->dm)
2581                 return;
2582
2583         /* NOTE: this is not nice to use tessfaces but hard to avoid since pa->num uses tessfaces */
2584         BKE_mesh_tessface_ensure(me);
2585
2586         mirrorfaces= mesh_get_x_mirror_faces(ob, NULL);
2587
2588         if (!edit->mirror_cache)
2589                 PE_update_mirror_cache(ob, psys);
2590
2591         totpart= psys->totpart;
2592         newtotpart= psys->totpart;
2593         LOOP_VISIBLE_POINTS {
2594                 pa = psys->particles + p;
2595                 if (!tagged) {
2596                         if (point_is_selected(point)) {
2597                                 if (edit->mirror_cache[p] != -1) {
2598                                         /* already has a mirror, don't need to duplicate */
2599                                         PE_mirror_particle(ob, psmd->dm, psys, pa, NULL);
2600                                         continue;
2601                                 }
2602                                 else
2603                                         point->flag |= PEP_TAG;
2604                         }
2605                 }
2606
2607                 if ((point->flag & PEP_TAG) && mirrorfaces[pa->num*2] != -1)
2608                         newtotpart++;
2609         }
2610
2611         if (newtotpart != psys->totpart) {
2612                 /* allocate new arrays and copy existing */
2613                 new_pars= MEM_callocN(newtotpart*sizeof(ParticleData), "ParticleData new");
2614                 new_points= MEM_callocN(newtotpart*sizeof(PTCacheEditPoint), "PTCacheEditPoint new");
2615
2616                 if (psys->particles) {
2617                         memcpy(new_pars, psys->particles, totpart*sizeof(ParticleData));
2618                         MEM_freeN(psys->particles);
2619                 }
2620                 psys->particles= new_pars;
2621
2622                 if (edit->points) {
2623                         memcpy(new_points, edit->points, totpart*sizeof(PTCacheEditPoint));
2624                         MEM_freeN(edit->points);
2625                 }
2626                 edit->points= new_points;
2627
2628                 if (edit->mirror_cache) {
2629                         MEM_freeN(edit->mirror_cache);
2630                         edit->mirror_cache= NULL;
2631                 }
2632
2633                 edit->totpoint= psys->totpart= newtotpart;
2634                         
2635                 /* create new elements */
2636                 newpa= psys->particles + totpart;
2637                 newpoint= edit->points + totpart;
2638
2639                 for (p=0, point=edit->points; p<totpart; p++, point++) {
2640                         pa = psys->particles + p;
2641
2642                         if (point->flag & PEP_HIDE)
2643                                 continue;
2644                         if (!(point->flag & PEP_TAG) || mirrorfaces[pa->num*2] == -1)
2645                                 continue;
2646
2647                         /* duplicate */
2648                         *newpa= *pa;
2649                         *newpoint= *point;
2650                         if (pa->hair) newpa->hair= MEM_dupallocN(pa->hair);
2651                         if (point->keys) newpoint->keys= MEM_dupallocN(point->keys);
2652
2653                         /* rotate weights according to vertex index rotation */
2654                         rotation= mirrorfaces[pa->num*2+1];
2655                         newpa->fuv[0]= pa->fuv[2];
2656                         newpa->fuv[1]= pa->fuv[1];
2657                         newpa->fuv[2]= pa->fuv[0];
2658                         newpa->fuv[3]= pa->fuv[3];
2659                         while (rotation-- > 0)
2660                                 if (me->mface[pa->num].v4) {
2661                                         SHIFT4(float, newpa->fuv[0], newpa->fuv[1], newpa->fuv[2], newpa->fuv[3]);
2662                                 }
2663                                 else {
2664                                         SHIFT3(float, newpa->fuv[0], newpa->fuv[1], newpa->fuv[2]);
2665                                 }
2666
2667                         /* assign face inddex */
2668                         newpa->num= mirrorfaces[pa->num*2];
2669                         newpa->num_dmcache= psys_particle_dm_face_lookup(ob, psmd->dm, newpa->num, newpa->fuv, NULL);
2670
2671                         /* update edit key pointers */
2672                         key= newpoint->keys;
2673                         for (k=0, hkey=newpa->hair; k<newpa->totkey; k++, hkey++, key++) {
2674                                 key->co= hkey->co;
2675                                 key->time= &hkey->time;
2676                         }
2677
2678                         /* map key positions as mirror over x axis */
2679                         PE_mirror_particle(ob, psmd->dm, psys, pa, newpa);
2680
2681                         newpa++;
2682                         newpoint++;
2683                 }
2684         }
2685
2686         LOOP_POINTS {
2687                 point->flag &= ~PEP_TAG;
2688         }
2689
2690         MEM_freeN(mirrorfaces);
2691 }
2692
2693 static int mirror_exec(bContext *C, wmOperator *UNUSED(op))
2694 {
2695         Scene *scene= CTX_data_scene(C);
2696         Object *ob= CTX_data_active_object(C);
2697         PTCacheEdit *edit= PE_get_current(scene, ob);
2698         
2699         PE_mirror_x(scene, ob, 0);
2700
2701         update_world_cos(ob, edit);
2702         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, ob);
2703         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
2704
2705         return OPERATOR_FINISHED;
2706 }
2707
2708 void PARTICLE_OT_mirror(wmOperatorType *ot)
2709 {
2710         /* identifiers */
2711         ot->name = "Mirror";
2712         ot->idname = "PARTICLE_OT_mirror";
2713         
2714         /* api callbacks */
2715         ot->exec = mirror_exec;
2716         ot->poll = PE_hair_poll;
2717
2718         /* flags */
2719         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2720 }
2721
2722 /************************* brush edit callbacks ********************/
2723
2724 static void brush_comb(PEData *data, float UNUSED(mat[][4]), float imat[][4], int point_index, int key_index, PTCacheEditKey *key)
2725 {
2726         ParticleEditSettings *pset= PE_settings(data->scene);
2727         float cvec[3], fac;
2728
2729         if (pset->flag & PE_LOCK_FIRST && key_index == 0) return;
2730
2731         fac= (float)pow((double)(1.0f - data->dist / data->rad), (double)data->combfac);
2732
2733         copy_v3_v3(cvec, data->dvec);
2734         mul_mat3_m4_v3(imat, cvec);
2735         mul_v3_fl(cvec, fac);
2736         add_v3_v3(key->co, cvec);
2737
2738         (data->edit->points + point_index)->flag |= PEP_EDIT_RECALC;
2739 }
2740
2741 static void brush_cut(PEData *data, int pa_index)
2742 {
2743         PTCacheEdit *edit = data->edit;
2744         ARegion *ar= data->vc.ar;
2745         Object *ob= data->ob;
2746         ParticleEditSettings *pset= PE_settings(data->scene);
2747         ParticleCacheKey *key= edit->pathcache[pa_index];
2748         float rad2, cut_time= 1.0;
2749         float x0, x1, v0, v1, o0, o1, xo0, xo1, d, dv;
2750         int k, cut, keys= (int)pow(2.0, (double)pset->draw_step);
2751         int vertco[2];
2752
2753         /* blunt scissors */
2754         if (BLI_frand() > data->cutfac) return;
2755
2756         /* don't cut hidden */
2757         if (edit->points[pa_index].flag & PEP_HIDE)
2758                 return;
2759
2760         rad2= data->rad * data->rad;
2761
2762         cut=0;
2763
2764         project_int_noclip(ar, key->co, vertco);
2765         x0= (float)vertco[0];
2766         x1= (float)vertco[1];
2767
2768         o0= (float)data->mval[0];
2769         o1= (float)data->mval[1];
2770         
2771         xo0= x0 - o0;
2772         xo1= x1 - o1;
2773
2774         /* check if root is inside circle */
2775         if (xo0*xo0 + xo1*xo1 < rad2 && key_test_depth(data, key->co)) {
2776                 cut_time= -1.0f;
2777                 cut= 1;
2778         }
2779         else {
2780                 /* calculate path time closest to root that was inside the circle */
2781                 for (k=1, key++; k<=keys; k++, key++) {
2782                         project_int_noclip(ar, key->co, vertco);
2783
2784                         if (key_test_depth(data, key->co) == 0) {
2785                                 x0= (float)vertco[0];
2786                                 x1= (float)vertco[1];
2787
2788                                 xo0= x0 - o0;
2789                                 xo1= x1 - o1;
2790                                 continue;
2791                         }
2792
2793                         v0= (float)vertco[0] - x0;
2794                         v1= (float)vertco[1] - x1;
2795
2796                         dv= v0*v0 + v1*v1;
2797
2798                         d= (v0*xo1 - v1*xo0);
2799                         
2800                         d= dv * rad2 - d*d;
2801
2802                         if (d > 0.0f) {
2803                                 d= sqrt(d);
2804
2805                                 cut_time= -(v0*xo0 + v1*xo1 + d);
2806
2807                                 if (cut_time > 0.0f) {
2808                                         cut_time /= dv;
2809
2810                                         if (cut_time < 1.0f) {
2811                                                 cut_time += (float)(k-1);
2812                                                 cut_time /= (float)keys;
2813                                                 cut= 1;
2814                                                 break;
2815                                         }
2816                                 }
2817                         }
2818
2819                         x0= (float)vertco[0];
2820                         x1= (float)vertco[1];
2821
2822                         xo0= x0 - o0;
2823                         xo1= x1 - o1;
2824                 }
2825         }
2826
2827         if (cut) {
2828                 if (cut_time < 0.0f) {
2829                         edit->points[pa_index].flag |= PEP_TAG;
2830                 }
2831                 else {
2832                         rekey_particle_to_time(data->scene, ob, pa_index, cut_time);
2833                         edit->points[pa_index].flag |= PEP_EDIT_RECALC;
2834                 }
2835         }
2836 }
2837
2838 static void brush_length(PEData *data, int point_index)
2839 {
2840         PTCacheEdit *edit= data->edit;
2841         PTCacheEditPoint *point = edit->points + point_index;
2842         KEY_K;
2843         float dvec[3], pvec[3] = {0.0f, 0.0f, 0.0f};
2844
2845         LOOP_KEYS {
2846                 if (k==0) {
2847                         copy_v3_v3(pvec, key->co);
2848                 }
2849                 else {
2850                         sub_v3_v3v3(dvec, key->co, pvec);
2851                         copy_v3_v3(pvec, key->co);
2852                         mul_v3_fl(dvec, data->growfac);
2853                         add_v3_v3v3(key->co, (key-1)->co, dvec);
2854                 }
2855         }
2856
2857         point->flag |= PEP_EDIT_RECALC;
2858 }
2859
2860 static void brush_puff(PEData *data, int point_index)
2861 {
2862         PTCacheEdit *edit = data->edit;
2863         ParticleSystem *psys = edit->psys;
2864         PTCacheEditPoint *point = edit->points + point_index;
2865         KEY_K;
2866         float mat[4][4], imat[4][4];
2867
2868         float lastco[3], rootco[3] = {0.0f, 0.0f, 0.0f}, co[3], nor[3], kco[3], dco[3], ofs[3] = {0.0f, 0.0f, 0.0f}, fac=0.0f, length=0.0f;
2869         int puff_volume = 0;
2870         int change= 0;
2871
2872         {
2873                 ParticleEditSettings *pset= PE_settings(data->scene);
2874                 ParticleBrushData *brush= &pset->brush[pset->brushtype];
2875                 puff_volume = brush->flag & PE_BRUSH_DATA_PUFF_VOLUME;
2876         }
2877
2878         if (psys && !(psys->flag & PSYS_GLOBAL_HAIR)) {
2879                 psys_mat_hair_to_global(data->ob, data->dm, psys->part->from, psys->particles + point_index, mat);
2880                 invert_m4_m4(imat, mat);
2881         }
2882         else {
2883                 unit_m4(mat);
2884                 unit_m4(imat);
2885         }
2886
2887         LOOP_KEYS {
2888                 if (k==0) {
2889                         /* find root coordinate and normal on emitter */
2890                         copy_v3_v3(co, key->co);
2891                         mul_m4_v3(mat, co);
2892                         mul_v3_m4v3(kco, data->ob->imat, co); /* use 'kco' as the object space version of worldspace 'co', ob->imat is set before calling */
2893
2894                         point_index= BLI_kdtree_find_nearest(edit->emitter_field, kco, NULL, NULL);
2895                         if (point_index == -1) return;
2896
2897                         copy_v3_v3(rootco, co);
2898                         copy_v3_v3(nor, &edit->emitter_cosnos[point_index*6+3]);
2899                         mul_mat3_m4_v3(data->ob->obmat, nor); /* normal into worldspace */
2900
2901                         normalize_v3(nor);
2902                         length= 0.0f;
2903
2904                         fac= (float)pow((double)(1.0f - data->dist / data->rad), (double)data->pufffac);
2905                         fac *= 0.025f;
2906                         if (data->invert)
2907                                 fac= -fac;
2908                 }
2909                 else {
2910                         /* compute position as if hair was standing up straight.
2911                          * */
2912                         copy_v3_v3(lastco, co);
2913                         copy_v3_v3(co, key->co);
2914                         mul_m4_v3(mat, co);
2915                         length += len_v3v3(lastco, co);
2916                         if ((data->select==0 || (key->flag & PEK_SELECT)) && !(key->flag & PEK_HIDE)) {
2917                                 madd_v3_v3v3fl(kco, rootco, nor, length);
2918
2919                                 /* blend between the current and straight position */
2920                                 sub_v3_v3v3(dco, kco, co);
2921                                 madd_v3_v3fl(co, dco, fac);
2922
2923                                 /* re-use dco to compare before and after translation and add to the offset  */
2924                                 copy_v3_v3(dco, key->co);
2925
2926                                 mul_v3_m4v3(key->co, imat, co);
2927
2928                                 if (puff_volume) {
2929                                         /* accumulate the total distance moved to apply to unselected
2930                                          * keys that come after */
2931                                         ofs[0] += key->co[0] - dco[0];
2932                                         ofs[1] += key->co[1] - dco[1];
2933                                         ofs[2] += key->co[2] - dco[2];
2934                                 }
2935                                 change = 1;
2936                         }
2937                         else {
2938
2939                                 if (puff_volume) {
2940 #if 0
2941                                         /* this is simple but looks bad, adds annoying kinks */
2942                                         add_v3_v3(key->co, ofs);
2943 #else
2944                                         /* translate (not rotate) the rest of the hair if its not selected  */
2945                                         if (ofs[0] || ofs[1] || ofs[2]) {
2946 #if 0                                   /* kindof works but looks worse then whats below */
2947
2948                                                 /* Move the unselected point on a vector based on the
2949                                                  * hair direction and the offset */
2950                                                 float c1[3], c2[3];
2951                                                 sub_v3_v3v3(dco, lastco, co);
2952                                                 mul_mat3_m4_v3(imat, dco); /* into particle space */
2953
2954                                                 /* move the point along a vector perpendicular to the
2955                                                  * hairs direction, reduces odd kinks, */
2956                                                 cross_v3_v3v3(c1, ofs, dco);
2957                                                 cross_v3_v3v3(c2, c1, dco);
2958                                                 normalize_v3(c2);
2959                                                 mul_v3_fl(c2, len_v3(ofs));
2960                                                 add_v3_v3(key->co, c2);
2961 #else
2962                                                 /* Move the unselected point on a vector based on the
2963                                                  * the normal of the closest geometry */
2964                                                 float oco[3], onor[3];
2965                                                 copy_v3_v3(oco, key->co);
2966                                                 mul_m4_v3(mat, oco);
2967                                                 mul_v3_m4v3(kco, data->ob->imat, oco); /* use 'kco' as the object space version of worldspace 'co', ob->imat is set before calling */
2968
2969                                                 point_index= BLI_kdtree_find_nearest(edit->emitter_field, kco, NULL, NULL);
2970                                                 if (point_index != -1) {
2971                                                         copy_v3_v3(onor, &edit->emitter_cosnos[point_index*6+3]);
2972                                                         mul_mat3_m4_v3(data->ob->obmat, onor); /* normal into worldspace */
2973                                                         mul_mat3_m4_v3(imat, onor); /* worldspace into particle space */
2974                                                         normalize_v3(onor);
2975
2976
2977                                                         mul_v3_fl(onor, len_v3(ofs));
2978                                                         add_v3_v3(key->co, onor);
2979                                                 }
2980 #endif
2981                                         }
2982 #endif
2983                                 }
2984                         }
2985                 }
2986         }
2987
2988         if (change)
2989                 point->flag |= PEP_EDIT_RECALC;
2990 }
2991
2992
2993 static void brush_weight(PEData *data, float UNUSED(mat[][4]), float UNUSED(imat[][4]), int point_index, int key_index, PTCacheEditKey *UNUSED(key))
2994 {
2995         /* roots have full weight allways */
2996         if (key_index) {
2997                 PTCacheEdit *edit = data->edit;
2998                 ParticleSystem *psys = edit->psys;
2999
3000                 ParticleData *pa= psys->particles + point_index;
3001                 pa->hair[key_index].weight = data->weightfac;
3002
3003                 (data->edit->points + point_index)->flag |= PEP_EDIT_RECALC;
3004         }
3005 }
3006
3007 static void brush_smooth_get(PEData *data, float mat[][4], float UNUSED(imat[][4]), int UNUSED(point_index), int key_index, PTCacheEditKey *key)
3008 {       
3009         if (key_index) {
3010                 float dvec[3];
3011
3012                 sub_v3_v3v3(dvec, key->co, (key-1)->co);
3013                 mul_mat3_m4_v3(mat, dvec);
3014                 add_v3_v3(data->vec, dvec);
3015                 data->tot++;
3016         }
3017 }
3018
3019 static void brush_smooth_do(PEData *data, float UNUSED(mat[][4]), float imat[][4], int point_index, int key_index, PTCacheEditKey *key)
3020 {
3021         float vec[3], dvec[3];
3022         
3023         if (key_index) {
3024                 copy_v3_v3(vec, data->vec);
3025                 mul_mat3_m4_v3(imat, vec);
3026
3027                 sub_v3_v3v3(dvec, key->co, (key-1)->co);
3028
3029                 sub_v3_v3v3(dvec, vec, dvec);
3030                 mul_v3_fl(dvec, data->smoothfac);
3031                 
3032                 add_v3_v3(key->co, dvec);
3033         }
3034
3035         (data->edit->points + point_index)->flag |= PEP_EDIT_RECALC;
3036 }
3037
3038 /* convert from triangle barycentric weights to quad mean value weights */
3039 static void intersect_dm_quad_weights(const float v1[3], const float v2[3], const float v3[3], const float v4[3], float w[4])
3040 {
3041         float co[3], vert[4][3];
3042
3043         copy_v3_v3(vert[0], v1);
3044         copy_v3_v3(vert[1], v2);
3045         copy_v3_v3(vert[2], v3);
3046         copy_v3_v3(vert[3], v4);
3047
3048         co[0]= v1[0]*w[0] + v2[0]*w[1] + v3[0]*w[2] + v4[0]*w[3];
3049         co[1]= v1[1]*w[0] + v2[1]*w[1] + v3[1]*w[2] + v4[1]*w[3];
3050         co[2]= v1[2]*w[0] + v2[2]*w[1] + v3[2]*w[2] + v4[2]*w[3];
3051
3052         interp_weights_poly_v3(w, vert, 4, co);
3053 }
3054
3055 /* check intersection with a derivedmesh */
3056 static int particle_intersect_dm(Scene *scene, Object *ob, DerivedMesh *dm,
3057                                  float *vert_cos,
3058                                  const float co1[3], const float co2[3],
3059                                  float *min_d, int *min_face, float *min_w,
3060                                  float *face_minmax, float *pa_minmax,
3061                                  float radius, float *ipoint)
3062 {
3063         MFace *mface= NULL;
3064         MVert *mvert= NULL;
3065         int i, totface, intersect=0;
3066         float cur_d, cur_uv[2], v1[3], v2[3], v3[3], v4[3], min[3], max[3], p_min[3], p_max[3];
3067         float cur_ipoint[3];
3068         
3069         if (dm == NULL) {
3070                 psys_disable_all(ob);
3071
3072                 dm=mesh_get_derived_final(scene, ob, 0);
3073                 if (dm == NULL)
3074                         dm=mesh_get_derived_deform(scene, ob, 0);
3075
3076                 psys_enable_all(ob);
3077
3078                 if (dm == NULL)
3079                         return 0;
3080         }
3081
3082         /* BMESH_ONLY, deform dm may not have tessface */
3083         DM_ensure_tessface(dm);
3084         
3085
3086         if (pa_minmax==0) {
3087                 INIT_MINMAX(p_min, p_max);
3088                 DO_MINMAX(co1, p_min, p_max);
3089                 DO_MINMAX(co2, p_min, p_max);
3090         }
3091         else {
3092                 copy_v3_v3(p_min, pa_minmax);
3093                 copy_v3_v3(p_max, pa_minmax+3);
3094         }
3095
3096         totface=dm->getNumTessFaces(dm);
3097         mface=dm->getTessFaceDataArray(dm, CD_MFACE);
3098         mvert=dm->getVertDataArray(dm, CD_MVERT);
3099         
3100         /* lets intersect the faces */
3101         for (i=0; i<totface; i++, mface++) {
3102                 if (vert_cos) {
3103                         copy_v3_v3(v1, vert_cos+3*mface->v1);
3104                         copy_v3_v3(v2, vert_cos+3*mface->v2);
3105                         copy_v3_v3(v3, vert_cos+3*mface->v3);
3106                         if (mface->v4)
3107                                 copy_v3_v3(v4, vert_cos+3*mface->v4);
3108                 }
3109                 else {
3110                         copy_v3_v3(v1, mvert[mface->v1].co);
3111                         copy_v3_v3(v2, mvert[mface->v2].co);
3112                         copy_v3_v3(v3, mvert[mface->v3].co);
3113                         if (mface->v4)
3114                                 copy_v3_v3(v4, mvert[mface->v4].co);
3115                 }
3116
3117                 if (face_minmax==0) {
3118                         INIT_MINMAX(min, max);
3119                         DO_MINMAX(v1, min, max);
3120                         DO_MINMAX(v2, min, max);
3121                         DO_MINMAX(v3, min, max);
3122                         if (mface->v4)
3123                                 DO_MINMAX(v4, min, max);
3124                         if (isect_aabb_aabb_v3(min, max, p_min, p_max)==0)
3125                                 continue;
3126                 }
3127                 else {
3128                         copy_v3_v3(min, face_minmax+6*i);
3129                         copy_v3_v3(max, face_minmax+6*i+3);
3130                         if (isect_aabb_aabb_v3(min, max, p_min, p_max)==0)
3131                                 continue;
3132                 }
3133
3134                 if (radius>0.0f) {
3135                         if (isect_sweeping_sphere_tri_v3(co1, co2, radius, v2, v3, v1, &cur_d, cur_ipoint)) {
3136                                 if (cur_d<*min_d) {
3137                                         *min_d=cur_d;
3138                                         copy_v3_v3(ipoint, cur_ipoint);
3139                                         *min_face=i;
3140                                         intersect=1;
3141                                 }
3142                         }
3143                         if (mface->v4) {
3144              &