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