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