2.5
authorTon Roosendaal <ton@blender.org>
Sat, 24 Jan 2009 13:45:24 +0000 (13:45 +0000)
committerTon Roosendaal <ton@blender.org>
Sat, 24 Jan 2009 13:45:24 +0000 (13:45 +0000)
- Brought back code for particle edit and fluidsim
- Sanitized code from globals and bad level calls,
  so its ready to come back working.
- Fixed cirle selecting (Ckey now)
- Enabled undo for editmode curve, armature, particle
  and lattice

(another commit following)

26 files changed:
source/Makefile
source/blender/blenkernel/BKE_particle.h
source/blender/blenkernel/intern/BME_conversions.c
source/blender/blenkernel/intern/effect.c
source/blender/blenkernel/intern/fluidsim.c
source/blender/blenkernel/intern/particle_system.c
source/blender/editors/SConscript
source/blender/editors/armature/editarmature.c
source/blender/editors/include/ED_armature.h
source/blender/editors/include/ED_curve.h
source/blender/editors/include/ED_editparticle.h [new file with mode: 0644]
source/blender/editors/include/ED_fluidsim.h [new file with mode: 0644]
source/blender/editors/include/ED_object.h
source/blender/editors/include/ED_view3d.h
source/blender/editors/object/object_edit.c
source/blender/editors/physics/editparticle.c [new file with mode: 0644]
source/blender/editors/physics/fluidsim.c [new file with mode: 0644]
source/blender/editors/physics/physics_intern.h [new file with mode: 0644]
source/blender/editors/space_view3d/drawobject.c
source/blender/editors/space_view3d/view3d_edit.c
source/blender/editors/space_view3d/view3d_header.c
source/blender/editors/space_view3d/view3d_intern.h
source/blender/editors/space_view3d/view3d_select.c
source/blender/editors/transform/transform_conversions.c
source/blender/editors/util/undo.c
source/blender/windowmanager/intern/wm_operators.c

index 0f46e6abfafdb943053b78b8e4a42012d3476e17..46fbffeb610e10759d52f0489407d71c711cda47 100644 (file)
@@ -243,6 +243,7 @@ PULIB += $(OCGDIR)/blender/ed_curve/libed_curve.a
 PULIB += $(OCGDIR)/blender/ed_armature/libed_armature.a
 PULIB += $(OCGDIR)/blender/ed_mesh/libed_mesh.a
 PULIB += $(OCGDIR)/blender/ed_sculpt/libed_sculpt.a
+PULIB += $(OCGDIR)/blender/ed_physics/libed_physics.a
 PULIB += $(OCGDIR)/blender/ed_animation/libed_animation.a
 PULIB += $(OCGDIR)/blender/ed_transform/libed_transform.a
 PULIB += $(OCGDIR)/blender/ed_util/libed_util.a
index 5c11a56452760c1c90dcb7fdcf194717e1376441..616bf737889f77b4cd128bd80e151c96ae58b385 100644 (file)
@@ -301,6 +301,10 @@ void do_effectors(int pa_no, struct ParticleData *pa, struct ParticleKey *state,
 void psys_calc_dmcache(struct Object *ob, struct DerivedMesh *dm, struct ParticleSystem *psys);
 int psys_particle_dm_face_lookup(struct Object *ob, struct DerivedMesh *dm, int index, float *fw, struct LinkNode *node);
 
+void reset_particle(struct Scene *scene, struct ParticleData *pa, struct ParticleSystem *psys, struct ParticleSystemModifierData *psmd, struct Object *ob,
+                                       float dtime, float cfra, float *vg_vel, float *vg_tan, float *vg_rot);
+
+
 /* psys_reset */
 #define PSYS_RESET_ALL                 1
 #define PSYS_RESET_DEPSGRAPH   2
index 58bd4b59181f80a71f42cf9e173f0898f0844b7c..1e332bcf393ea335d328ce375c7d264f8e5163f0 100644 (file)
@@ -427,8 +427,9 @@ void BME_bmesh_to_editmesh(BME_Mesh *bm, BME_TransData_Head *td, EditMesh *em) {
                                efa->f |= SELECT;
                        }
                        if(f->flag & ME_HIDE) efa->h= 1;
-                       if((G.f & G_FACESELECT) && (efa->f & SELECT))
-                               ; //XXX EM_select_face(efa, 1); /* flush down */
+                       // XXX flag depricated
+                       // if((G.f & G_FACESELECT) && (efa->f & SELECT))
+                               //XXX EM_select_face(efa, 1); /* flush down */
                        CustomData_em_copy_data(&bm->pdata, &em->fdata, f->data, &efa->data);
                        BME_loops_to_corners(bm, &em->fdata, efa->data, f,numCol,numTex);
                }
index 6c959f2190e9027a205d630bcf70442b97a99454..d28d4206768cc772c05fc7ec314b075f5f467720 100644 (file)
@@ -86,7 +86,6 @@
 #ifndef DISABLE_ELBEEM
 #include "DNA_object_fluidsim.h"
 #include "LBM_fluidsim.h"
-#include "elbeem.h"
 #include <zlib.h>
 #include <string.h>
 #endif // DISABLE_ELBEEM
index 060f92087966395e8c1e839587f266e95237e211..9eefd48cae49e58c854494cde768b0f625096300 100644 (file)
@@ -52,7 +52,6 @@
 // headers for fluidsim bobj meshes
 #include <stdlib.h>
 #include "LBM_fluidsim.h"
-#include "elbeem.h"
 #include <zlib.h>
 #include <string.h>
 #include <stdio.h>
index 0973ed90c8bcad01d20dd4705ce7c736aacc50f8..4a4a8b2e5b7344cccbae26358ff0d37c27e6b186 100644 (file)
@@ -84,7 +84,6 @@
 #ifndef DISABLE_ELBEEM
 #include "DNA_object_fluidsim.h"
 #include "LBM_fluidsim.h"
-#include "elbeem.h"
 #include <zlib.h>
 #include <string.h>
 
@@ -1689,7 +1688,7 @@ static void initialize_all_particles(Object *ob, ParticleSystem *psys, ParticleS
        }
 }
 /* sets particle to the emitter surface with initial velocity & rotation */
-static void reset_particle(Scene *scene, ParticleData *pa, ParticleSystem *psys, ParticleSystemModifierData *psmd, Object *ob,
+void reset_particle(Scene *scene, ParticleData *pa, ParticleSystem *psys, ParticleSystemModifierData *psmd, Object *ob,
                                        float dtime, float cfra, float *vg_vel, float *vg_tan, float *vg_rot)
 {
        ParticleSettings *part;
@@ -4364,7 +4363,7 @@ static void particles_fluid_step(Scene *scene, Object *ob, ParticleSystem *psys,
                        gzf = gzopen(filename, "rb");
                        if (!gzf) {
                                snprintf(debugStrBuffer,256,"readFsPartData::error - Unable to open file for reading '%s' \n", filename); 
-                               //elbeemDebugOut(debugStrBuffer);
+                               elbeemDebugOut(debugStrBuffer);
                                return;
                        }
        
@@ -4424,7 +4423,9 @@ static void particles_fluid_step(Scene *scene, Object *ob, ParticleSystem *psys,
        
                        totpart = psys->totpart = activeParts;
                        snprintf(debugStrBuffer,256,"readFsPartData::done - particles:%d, active:%d, file:%d, mask:%d  \n", psys->totpart,activeParts,fileParts,readMask);
-                       elbeemDebugOut(debugStrBuffer);
+                       // bad level call
+                       // XXX elbeemDebugOut(debugStrBuffer);
+                       
                } // fluid sim particles done
        }
        #endif // DISABLE_ELBEEM
index 40969a4b885fc12f23ce1f592cc698333dedbae0..fc71319afa1e69f62c7ba9f3f69f542dc556f663 100644 (file)
@@ -12,7 +12,7 @@ SConscript(['datafiles/SConscript',
                        'object/SConscript',
                        'curve/SConscript',
                        'gpencil/SConscript',
-                       #'physics/SConscript', enable this when there is actually code in physics/
+                       'physics/SConscript',
                        'preview/SConscript',
                        'space_buttons/SConscript',
                        'space_file/SConscript',
index 67b8f211eaad57a6feb8892d5857e38cd742cfb4..c776f7959da6b3d0332680b6659cced586fbe02c 100644 (file)
@@ -1984,11 +1984,21 @@ static void free_undoBones(void *lbv)
        MEM_freeN(lb);
 }
 
+static void *get_armature_edit(bContext *C)
+{
+       Object *obedit= CTX_data_edit_object(C);
+       if(obedit && obedit->type==OB_ARMATURE) {
+               bArmature *arm= obedit->data;
+               return arm->edbo;
+       }
+       return NULL;
+}
+
 /* and this is all the undo system needs to know */
 void undo_push_armature(bContext *C, char *name)
 {
        // XXX solve getdata()
-       undo_editmode_push(C, name, NULL, free_undoBones, undoBones_to_editBones, editBones_to_undoBones, NULL);
+       undo_editmode_push(C, name, get_armature_edit, free_undoBones, undoBones_to_editBones, editBones_to_undoBones, NULL);
 }
 
 
index c3c757b1a306b8c035eb7fc5ec29d0db6369c000..556aac51e209a156bac510611a601c59aaf6e1bd 100644 (file)
@@ -104,6 +104,8 @@ void docenter_armature (struct Scene *scene, struct View3D *v3d, struct Object *
 void auto_align_armature(struct Scene *scene, struct View3D *v3d, short mode);
 void unique_editbone_name (ListBase *edbo, char *name);
 
+void undo_push_armature(struct bContext *C, char *name);
+
 /* poseobject.c */
 void ED_armature_exit_posemode(struct Base *base);
 void ED_armature_enter_posemode(struct Base *base);
index b725ad46124187d5201c9923f253d7b2f8701b51..076f82c0a70265010788a29a3f9f68015bfb7446 100644 (file)
@@ -36,8 +36,8 @@ struct Base;
 struct View3D;
 
 /* curve_ops.c */
-void ED_operatortypes_curve(void);
-void ED_keymap_curve(struct wmWindowManager *wm);
+void   ED_operatortypes_curve(void);
+void   ED_keymap_curve (struct wmWindowManager *wm);
 
 /* editcurve.c */
 void   undo_push_curve (struct bContext *C, char *name);
@@ -48,13 +48,14 @@ void        make_editNurb   (struct Object *obedit);
 void   remake_editNurb (struct Object *obedit);
 void   free_editNurb   (struct Object *obedit);
 
-void mouse_nurb(struct bContext *C, short mval[2], int extend);
+void   mouse_nurb              (struct bContext *C, short mval[2], int extend);
 
 /* editfont.h */
-void make_editText             (struct Object *obedit);
-void load_editText             (struct Object *obedit);
-void remake_editText   (struct Object *obedit);
-void free_editText             (struct Object *obedit);
+void   undo_push_font  (struct bContext *C, char *name);
+void   make_editText   (struct Object *obedit);
+void   load_editText   (struct Object *obedit);
+void   remake_editText (struct Object *obedit);
+void   free_editText   (struct Object *obedit);
 
 #endif /* ED_CURVE_H */
 
diff --git a/source/blender/editors/include/ED_editparticle.h b/source/blender/editors/include/ED_editparticle.h
new file mode 100644 (file)
index 0000000..e719562
--- /dev/null
@@ -0,0 +1,96 @@
+/* 
+ * $Id: ED_editparticle.h $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2007 by Janne Karhu.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef ED_EDITPARTICLE_H
+#define ED_EDITPARTICLE_H
+
+struct Object;
+struct ParticleSystem;
+struct ParticleEditSettings;
+struct RadialControl;
+struct ViewContext;
+struct rcti;
+
+/* particle edit mode */
+void PE_set_particle_edit(struct Scene *scene);
+void PE_create_particle_edit(struct Object *ob, struct ParticleSystem *psys);
+void PE_free_particle_edit(struct ParticleSystem *psys);
+
+void PE_change_act(void *ob_v, void *act_v);
+void PE_change_act_psys(struct Object *ob, struct ParticleSystem *psys);
+int PE_can_edit(struct ParticleSystem *psys);
+
+/* access */
+struct ParticleSystem *PE_get_current(struct Object *ob);
+short PE_get_current_num(struct Object *ob);
+int PE_minmax(struct Scene *scene, float *min, float *max);
+void PE_get_colors(char sel[4], char nosel[4]);
+struct ParticleEditSettings *PE_settings(Scene *scene);
+struct RadialControl **PE_radialcontrol(void);
+
+/* update calls */
+void PE_hide_keys_time(struct Scene *scene, struct ParticleSystem *psys, float cfra);
+void PE_update_object(struct Scene *scene, struct Object *ob, int useflag);
+void PE_update_selection(struct Scene *scene, struct Object *ob, int useflag);
+void PE_recalc_world_cos(struct Object *ob, struct ParticleSystem *psys);
+
+/* selection tools */
+void PE_select_root(void);
+void PE_select_tip(void);
+void PE_deselectall(void);
+void PE_select_linked(void);
+void PE_select_less(void);
+void PE_select_more(void);
+
+void PE_mouse_particles(void);
+void PE_borderselect(struct ViewContext *vc, struct rcti *rect, int select);
+void PE_selectionCB(short selecting, struct Object *editobj, short *mval, float rad);
+void PE_do_lasso_select(struct ViewContext *, short mcords[][2], short moves, short select);
+
+/* tools */
+void PE_hide(int mode);
+void PE_rekey(void);
+void PE_subdivide(Object *ob);
+int PE_brush_particles(void);
+void PE_delete_particle(void);
+void PE_remove_doubles(void);
+void PE_mirror_x(Scene *scene, int tagged);
+void PE_selectbrush_menu(Scene *scene);
+void PE_remove_doubles(void);
+void PE_radialcontrol_start(const int mode);
+
+/* undo */
+void PE_undo_push(Scene *scene, char *str);
+void PE_undo_step(Scene *scene, int step);
+void PE_undo(Scene *scene);
+void PE_redo(Scene *scene);
+void PE_undo_menu(Scene *scene);
+
+#endif /* ED_EDITPARTICLE_H */
+
diff --git a/source/blender/editors/include/ED_fluidsim.h b/source/blender/editors/include/ED_fluidsim.h
new file mode 100644 (file)
index 0000000..bda8791
--- /dev/null
@@ -0,0 +1,52 @@
+/**
+ * BKE_fluidsim.h 
+ *     
+ * $Id: LBM_fluidsim.h 17433 2008-11-12 21:16:53Z blendix $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#ifndef ED_FLUIDSIM_H
+#define ED_FLUIDSIM_H
+
+struct Object;
+struct FluidsimSettings;
+
+extern double fluidsimViscosityPreset[6];
+extern char* fluidsimViscosityPresetString[6];
+
+/* allocates and initializes fluidsim data */
+struct FluidsimSettings* fluidsimSettingsNew(struct Object *srcob);
+
+/* frees internal data itself */
+void fluidsimSettingsFree(struct FluidsimSettings* sb);
+
+/* duplicate internal data */
+struct FluidsimSettings* fluidsimSettingsCopy(struct FluidsimSettings* sb);
+
+
+#endif /* ED_FLUIDSIM_H */
+
+
index d0815bba65c8248615edabd16bc1bb6cdd4b7ced..e0a6ed86695f936a3bda59344792b1745c5afd9a 100644 (file)
@@ -71,6 +71,7 @@ void add_constraint_to_object (struct bConstraint *con, struct Object *ob);
 
 /* editlattice.c */
 void mouse_lattice(struct bContext *C, short mval[2], int extend);
+void undo_push_lattice(struct bContext *C, char *name);
 
 /* editkey.c */
 void insert_shapekey(struct Scene *scene, struct Object *ob);
index b7ec74b777f6c68c3de540ae9ae4d4c433f18378..794ef0232364be68374a9f9541a5492af2e87804 100644 (file)
@@ -55,6 +55,14 @@ typedef struct ViewContext {
        short mval[2];
 } ViewContext;
 
+typedef struct ViewDepths {
+       unsigned short w, h;
+       float *depths;
+       double depth_range[2];
+       
+       char damaged;
+} ViewDepths;
+
 
 float *give_cursor(struct Scene *scene, struct View3D *v3d);
 
@@ -67,6 +75,7 @@ float read_cached_depth(struct ViewContext *vc, int x, int y);
 void request_depth_update(struct ViewContext *vc);
 
 /* Projection */
+#define IS_CLIPPED        12000
 
 void project_short(struct ARegion *ar, float *vec, short *adr);
 void project_short_noclip(struct ARegion *ar, float *vec, short *adr);
index 69655a202af962f34adb0a289d433efb508b5b93..0de7e114cce5e165332ef91d796870dacb75aa2b 100644 (file)
 #include "ED_anim_api.h"
 #include "ED_armature.h"
 #include "ED_curve.h"
+#include "ED_editparticle.h"
 #include "ED_mesh.h"
 #include "ED_object.h"
 #include "ED_screen.h"
@@ -6131,8 +6132,10 @@ void texspace_edit(Scene *scene, View3D *v3d)
 
 void mirrormenu(void)
 {
+       Scene *scene= NULL; // XXX
+       
        if(G.f & G_PARTICLEEDIT) {
-// XXX         PE_mirror_x(0);
+               PE_mirror_x(scene, 0);
        }
        else {
 // XXX         initTransform(TFM_MIRROR, CTX_NO_PET);
diff --git a/source/blender/editors/physics/editparticle.c b/source/blender/editors/physics/editparticle.c
new file mode 100644 (file)
index 0000000..89d4466
--- /dev/null
@@ -0,0 +1,3262 @@
+/* editparticle.c
+ *
+ *
+ * $Id: editparticle.c $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2007 by Janne Karhu.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include <stdlib.h>
+#include <math.h>
+#include <string.h>
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_scene_types.h"
+#include "DNA_mesh_types.h"
+#include "DNA_meshdata_types.h"
+#include "DNA_modifier_types.h"
+#include "DNA_object_force.h"
+#include "DNA_object_types.h"
+#include "DNA_vec_types.h"
+#include "DNA_userdef_types.h"
+#include "DNA_view3d_types.h"
+#include "DNA_screen_types.h"
+#include "DNA_space_types.h"
+
+#include "BKE_DerivedMesh.h"
+#include "BKE_depsgraph.h"
+
+#include "BKE_context.h"
+#include "BKE_global.h"
+#include "BKE_object.h"
+#include "BKE_mesh.h"
+#include "BKE_modifier.h"
+#include "BKE_particle.h"
+#include "BKE_scene.h"
+#include "BKE_utildefines.h" 
+
+#include "BLI_arithb.h"
+#include "BLI_blenlib.h"
+#include "BLI_dynstr.h"
+#include "BLI_kdtree.h"
+#include "BLI_rand.h"
+
+#include "PIL_time.h"
+
+#include "BIF_gl.h"
+#include "BIF_glutil.h"
+
+#include "ED_editparticle.h"
+#include "ED_view3d.h"
+
+#include "UI_resources.h"
+
+#include "physics_intern.h"
+
+static void ParticleUndo_clear(ParticleSystem *psys);
+
+#define LOOP_PARTICLES(i,pa) for(i=0, pa=psys->particles; i<totpart; i++, pa++)
+#define LOOP_KEYS(k,key) if(psys->edit)for(k=0, key=psys->edit->keys[i]; k<pa->totkey; k++, key++)
+
+/* XXX */
+static void BIF_undo_push() {}
+static void error() {}
+static int pupmenu() {return 0;}
+static int lasso_inside() {return 0;}
+static void *mesh_get_x_mirror_faces() {return NULL;}
+#define LEFTMOUSE 0
+#define RADIALCONTROL_SIZE             0
+#define RADIALCONTROL_STRENGTH 0
+#define RADIALCONTROL_NONE             0
+/* XXX */
+
+void PE_free_particle_edit(ParticleSystem *psys)
+{
+       ParticleEdit *edit=psys->edit;
+       int i, totpart=psys->totpart;
+
+       if(edit==0) return;
+
+       ParticleUndo_clear(psys);
+
+       if(edit->keys){
+               for(i=0; i<totpart; i++){
+                       if(edit->keys[i])
+                               MEM_freeN(edit->keys[i]);
+               }
+               MEM_freeN(edit->keys);
+       }
+
+       if(edit->mirror_cache)
+               MEM_freeN(edit->mirror_cache);
+
+       if(edit->emitter_cosnos){
+               MEM_freeN(edit->emitter_cosnos);
+               edit->emitter_cosnos=0;
+       }
+
+       if(edit->emitter_field){
+               BLI_kdtree_free(edit->emitter_field);
+               edit->emitter_field=0;
+       }
+
+       MEM_freeN(edit);
+
+       psys->edit=NULL;
+}
+/************************************************/
+/*                     Edit Mode Helpers                                       */
+/************************************************/
+int PE_can_edit(ParticleSystem *psys)
+{
+       return (psys && psys->edit && (G.f & G_PARTICLEEDIT));
+}
+
+ParticleEditSettings *PE_settings(Scene *scene)
+{
+       return &scene->toolsettings->particle;
+}
+
+void PE_change_act(void *ob_v, void *act_v)
+{
+       Object *ob = ob_v;
+       ParticleSystem *psys;
+       short act = *((short*)act_v) - 1;
+
+       if((psys=psys_get_current(ob)))
+               psys->flag &= ~PSYS_CURRENT;
+
+       if(act>=0){
+               if((psys=BLI_findlink(&ob->particlesystem,act))) {
+                       psys->flag |= PSYS_CURRENT;
+
+                       if(psys_check_enabled(ob, psys)) {
+                               if(G.f & G_PARTICLEEDIT && !psys->edit)
+                                       PE_create_particle_edit(ob, psys);
+                               PE_recalc_world_cos(ob, psys);
+                       }
+               }
+       }
+}
+
+void PE_change_act_psys(Object *ob, ParticleSystem *psys)
+{
+       ParticleSystem *p;
+       
+       if((p=psys_get_current(ob)))
+               p->flag &= ~PSYS_CURRENT;
+       
+       psys->flag |= PSYS_CURRENT;
+       
+       if(psys_check_enabled(ob, psys)) {
+               if(G.f & G_PARTICLEEDIT && !psys->edit)
+                       PE_create_particle_edit(ob, psys);
+               PE_recalc_world_cos(ob, psys);
+       }
+}
+
+/* always gets atleast the first particlesystem even if PSYS_CURRENT flag is not set */
+ParticleSystem *PE_get_current(Object *ob)
+{
+       ParticleSystem *psys;
+
+       if(ob==NULL)
+               return NULL;
+
+       psys= ob->particlesystem.first;
+       while(psys){
+               if(psys->flag & PSYS_CURRENT)
+                       break;
+               psys=psys->next;
+       }
+
+       if(psys==NULL && ob->particlesystem.first) {
+               psys=ob->particlesystem.first;
+               psys->flag |= PSYS_CURRENT;
+       }
+
+       if(psys && psys_check_enabled(ob, psys)) // XXX && ob == OBACT && (G.f & G_PARTICLEEDIT))
+               if(psys->part->type == PART_HAIR && psys->flag & PSYS_EDITED)
+                       if(psys->edit == NULL)
+                               PE_create_particle_edit(ob, psys);
+
+       return psys;
+}
+
+/* returns -1 if no system has PSYS_CURRENT flag */
+short PE_get_current_num(Object *ob)
+{
+       short num=0;
+       ParticleSystem *psys = ob->particlesystem.first;
+
+       while(psys){
+               if(psys->flag & PSYS_CURRENT)
+                       return num;
+               num++;
+               psys=psys->next;
+       }
+
+       return -1;
+}
+
+void PE_hide_keys_time(Scene *scene, ParticleSystem *psys, float cfra)
+{
+       ParticleData *pa;
+       ParticleEditKey *key;
+       ParticleEditSettings *pset=PE_settings(scene);
+       int i,k,totpart=psys->totpart;
+
+       if(pset->draw_timed && scene->selectmode==SCE_SELECT_POINT){
+               LOOP_PARTICLES(i,pa){
+                       LOOP_KEYS(k,key){
+                               if(fabs(cfra-*key->time) < pset->draw_timed)
+                                       key->flag &= ~PEK_HIDE;
+                               else{
+                                       key->flag |= PEK_HIDE;
+                                       key->flag &= ~PEK_SELECT;
+                               }
+                       }
+               }
+       }
+       else{
+               LOOP_PARTICLES(i,pa){
+                       LOOP_KEYS(k,key){
+                               key->flag &= ~PEK_HIDE;
+                       }
+               }
+       }
+}
+
+static int key_inside_circle(short mco[2], float rad, float co[3], float *distance)
+{
+       ARegion *ar= NULL; // XXX
+       float dx,dy,dist;
+       short vertco[2];
+
+       project_short(ar, co, vertco);
+       
+       if (vertco[0]==IS_CLIPPED)
+               return 0;
+       
+       dx=(float)(mco[0]-vertco[0]);
+       dy=(float)(mco[1]-vertco[1]);
+       dist=(float)sqrt((double)(dx*dx + dy*dy));
+
+       if(dist<=rad){
+               if(distance) *distance=dist;
+               return 1;
+       }
+       else
+               return 0;
+}
+static int key_inside_rect(rcti *rect, float co[3])
+{
+       ARegion *ar= NULL; // XXX
+       short vertco[2];
+
+       project_short(ar, co,vertco);
+
+       if (vertco[0]==IS_CLIPPED)
+               return 0;
+       
+       if(vertco[0] > rect->xmin && vertco[0] < rect->xmax &&
+                       vertco[1] > rect->ymin && vertco[1] < rect->ymax)
+               return 1;
+       else
+               return 0;
+}
+
+static int test_key_depth(float *co, bglMats *mats)
+{
+       ARegion *ar= NULL; // XXX
+       View3D *v3d= NULL;
+       RegionView3D *rv3d= ar->regiondata;
+       double ux, uy, uz;
+       float depth;
+       short wco[3], x,y;
+
+       if((v3d->drawtype<=OB_WIRE) || (v3d->flag & V3D_ZBUF_SELECT)==0) return 1;
+
+       gluProject(co[0],co[1],co[2], mats->modelview, mats->projection,
+                       (GLint *)mats->viewport, &ux, &uy, &uz );
+
+       project_short(ar, co, wco);
+       
+       if (wco[0]==IS_CLIPPED)
+               return 0;
+       
+       x=wco[0];
+       y=wco[1];
+
+       if(rv3d->depths && x<rv3d->depths->w && y<rv3d->depths->h){
+               /* the 0.0001 is an experimental threshold to make selecting keys right next to a surface work better */
+               if((float)uz - 0.0001 > rv3d->depths->depths[y*rv3d->depths->w+x])
+                       return 0;
+               else
+                       return 1;
+       }
+       else{
+               x+= (short)ar->winrct.xmin;
+               y+= (short)ar->winrct.ymin;
+
+               glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth);
+
+               if((float)uz - 0.0001 > depth)
+                       return 0;
+               else
+                       return 1;
+       }
+}
+
+static int particle_is_selected(ParticleSystem *psys, ParticleData *pa)
+{
+       ParticleEditKey *key;
+       int sel, i, k;
+
+       if(pa->flag&PARS_HIDE) return 0;
+
+       sel=0;
+       i= pa - psys->particles;
+       LOOP_KEYS(k,key)
+               if(key->flag&PEK_SELECT)
+                       return 1;
+       
+       return 0;
+}
+
+/*-----iterators over editable particles-----*/
+static void for_mouse_hit_keys(int nearest, ParticleSystem *psys, void (*func)(ParticleSystem *psys, 
+                                                                                                       int pa_index, int key_index, void *userData), void *userData)
+{
+       /* these are allways the first in this userData */
+       struct {Scene *scene; short *mval; float rad; rcti *rect;} *data = userData;
+       ParticleData *pa;
+       ParticleEditKey *key;
+       bglMats mats;
+       int i,k, totpart, nearest_pa=-1, nearest_key=-1;
+       float dist=data->rad;
+
+       if(psys==0 || data->scene->selectmode==SCE_SELECT_PATH) return;
+
+       totpart=psys->totpart;
+
+       bgl_get_mats(&mats);
+
+       LOOP_PARTICLES(i,pa){
+               if(pa->flag & PARS_HIDE) continue;
+
+               if(data->scene->selectmode==SCE_SELECT_END){
+                       key=psys->edit->keys[i]+pa->totkey-1;
+
+                       if(nearest){
+                               if(key_inside_circle(data->mval,dist,key->world_co,&dist) && test_key_depth(key->world_co,&mats)){
+                                       nearest_pa=i;
+                                       nearest_key=pa->totkey-1;
+                               }
+                       }
+                       else if(((data->mval)?
+                                               key_inside_circle(data->mval,data->rad,key->world_co,0):
+                                               key_inside_rect(data->rect,key->world_co)) && test_key_depth(key->world_co,&mats))
+                               func(psys,i,pa->totkey-1,userData);
+               }
+               else{
+                       key=psys->edit->keys[i];
+
+                       LOOP_KEYS(k,key){
+                               if(key->flag&PEK_HIDE) continue;
+
+                               if(nearest){
+                                       if(key_inside_circle(data->mval,dist,key->world_co,&dist) && test_key_depth(key->world_co,&mats)){
+                                               nearest_pa=i;
+                                               nearest_key=k;
+                                       }
+                               }
+                               else if(((data->mval)?
+                                                       key_inside_circle(data->mval,data->rad,key->world_co,0):
+                                                       key_inside_rect(data->rect,key->world_co)) && test_key_depth(key->world_co,&mats))
+                                       func(psys,i,k,userData);
+                       }
+               }
+       }
+       if(nearest && nearest_pa>-1){
+               func(psys,nearest_pa,nearest_key,userData);
+       }
+}
+
+static void foreach_mouse_hit_element(int selected, ParticleSystem *psys,void (*func)(ParticleSystem *psys, int index, void *userData), void *userData)
+{
+       /* these are allways the first in this userData */
+       struct {Scene *scene; short *mval; float rad; rcti* rect; float dist;} *data = userData;
+       ParticleData *pa;
+       ParticleEditKey *key;
+       bglMats mats;
+       int i,k, totpart;
+
+       if(psys==0) return;
+
+       totpart=psys->totpart;
+
+       bgl_get_mats(&mats);
+
+       if(data->scene->selectmode==SCE_SELECT_PATH)
+               selected=0;
+
+       LOOP_PARTICLES(i,pa){
+               if(pa->flag & PARS_HIDE) continue;
+
+               if(data->scene->selectmode==SCE_SELECT_END){
+                       key=psys->edit->keys[i]+pa->totkey-1;
+                       if(key_inside_circle(data->mval,data->rad,key->world_co,&data->dist) && (selected==0 || key->flag&PEK_SELECT) && test_key_depth(key->world_co,&mats))
+                               func(psys,i,userData);
+               }
+               else{
+                       LOOP_KEYS(k,key){
+                               if(key->flag&PEK_HIDE) continue;
+
+                               if(key_inside_circle(data->mval,data->rad,key->world_co,&data->dist) && (selected==0 || key->flag&PEK_SELECT) && test_key_depth(key->world_co,&mats)){
+                                       func(psys,i,userData);
+                                       break;
+                               }
+                       }
+               }
+       }
+}
+
+static void foreach_mouse_hit_key(int selected, ParticleSystem *psys,void (*func)(ParticleSystem *psys, float mat[][4], float imat[][4], int bel_index, int key_index, void *userData), void *userData)
+{
+       /* these are allways the first in this userData */
+       struct {Scene *scene; Object *ob; short *mval; float rad; rcti* rect; float dist;} *data = userData;
+       ParticleData *pa;
+       ParticleEditKey *key;
+       ParticleSystemModifierData *psmd=0;
+       bglMats mats;
+       int i,k, totpart;
+       float mat[4][4], imat[4][4];
+
+       if(psys==0) return;
+
+       psmd=psys_get_modifier(data->ob,psys);
+
+       totpart=psys->totpart;
+
+       bgl_get_mats(&mats);
+
+       if(data->scene->selectmode==SCE_SELECT_PATH)
+               selected=0;
+
+       Mat4One(imat);
+       Mat4One(mat);
+
+       LOOP_PARTICLES(i,pa){
+               if(pa->flag & PARS_HIDE) continue;
+
+               psys_mat_hair_to_global(data->ob, psmd->dm, psys->part->from, pa, mat);
+               //psys_geometry_mat(psmd->dm,pa,tmat);
+               //Mat4MulMat4(mat,tmat,data->ob->obmat);
+               Mat4Invert(imat,mat);
+
+               if(data->scene->selectmode==SCE_SELECT_END){
+                       key=psys->edit->keys[i]+pa->totkey-1;
+                       if(key_inside_circle(data->mval,data->rad,key->world_co,&data->dist) && (selected==0 || key->flag&PEK_SELECT) && test_key_depth(key->world_co,&mats))
+                               func(psys,mat,imat,i,pa->totkey-1,userData);
+               }
+               else{
+                       LOOP_KEYS(k,key){
+                               if(key->flag&PEK_HIDE) continue;
+
+                               if(key_inside_circle(data->mval,data->rad,key->world_co,&data->dist) && (selected==0 || key->flag&PEK_SELECT) && test_key_depth(key->world_co,&mats)){
+                                       func(psys,mat,imat,i,k,userData);
+                               }
+                       }
+               }
+       }
+}
+
+static void foreach_selected_element(ParticleSystem *psys, void (*func)(ParticleSystem *psys, int index, void *userData), void *userData)
+{
+       ParticleData *pa;
+       int i,totpart;
+
+       if(psys==0) return;
+
+       totpart=psys->totpart;
+
+       LOOP_PARTICLES(i,pa)
+               if(particle_is_selected(psys, pa))
+                       func(psys,i,userData);
+}
+
+static void foreach_selected_key(ParticleSystem *psys, void (*func)(ParticleSystem *psys, int pa_index, int key_index, void *userData), void *userData)
+{
+       ParticleData *pa;
+       ParticleEditKey *key;
+       int i,k,totpart;
+
+       if(psys==0) return;
+
+       totpart=psys->totpart;
+
+       LOOP_PARTICLES(i,pa){
+               if(pa->flag&PARS_HIDE) continue;
+
+               key=psys->edit->keys[i];
+               LOOP_KEYS(k,key){
+                       if(key->flag&PEK_SELECT)
+                               func(psys,i,k,userData);
+               }
+       }
+}
+void PE_foreach_element(ParticleSystem *psys, void (*func)(ParticleSystem *psys, int index, void *userData), void *userData)
+{
+       int i,totpart;
+
+       if(psys==0) return;
+
+       totpart=psys->totpart;
+
+       for(i=0; i<totpart; i++)
+               func(psys,i,userData);
+}
+static int count_selected_keys(Scene *scene, ParticleSystem *psys)
+{
+       ParticleData *pa;
+       ParticleEditKey *key;
+       int i,k,totpart,sel=0;
+
+       if(psys==0) return 0;
+
+       totpart=psys->totpart;
+
+       LOOP_PARTICLES(i,pa){
+               if(pa->flag&PARS_HIDE) continue;
+
+               key=psys->edit->keys[i];
+               if(scene->selectmode==SCE_SELECT_POINT){
+                       for(k=0; k<pa->totkey; k++,key++){
+                               if(key->flag&PEK_SELECT)
+                                       sel++;
+                       }
+               }
+               else if(scene->selectmode==SCE_SELECT_END){
+                       key+=pa->totkey-1;
+                       if(key->flag&PEK_SELECT)
+                               sel++;
+               }
+       }
+       return sel;
+}
+
+/************************************************/
+/*                     Particle Edit Mirroring                         */
+/************************************************/
+
+static void PE_update_mirror_cache(Object *ob, ParticleSystem *psys)
+{
+       ParticleEdit *edit;
+       ParticleData *pa;
+       ParticleSystemModifierData *psmd;
+       KDTree *tree;
+       KDTreeNearest nearest;
+       float mat[4][4], co[3];
+       int i, index, totpart;
+
+       edit= psys->edit;
+       psmd= psys_get_modifier(ob, psys);
+       totpart= psys->totpart;
+
+       tree= BLI_kdtree_new(totpart);
+
+       /* insert particles into kd tree */
+       LOOP_PARTICLES(i,pa) {
+               psys_mat_hair_to_orco(ob, psmd->dm, psys->part->from, pa, mat);
+               VECCOPY(co, pa->hair[0].co);
+               Mat4MulVecfl(mat, co);
+               BLI_kdtree_insert(tree, i, co, NULL);
+       }
+
+       BLI_kdtree_balance(tree);
+
+       /* lookup particles and set in mirror cache */
+       if(!edit->mirror_cache)
+               edit->mirror_cache= MEM_callocN(sizeof(int)*totpart, "PE mirror cache");
+       
+       LOOP_PARTICLES(i,pa) {
+               psys_mat_hair_to_orco(ob, psmd->dm, psys->part->from, pa, mat);
+               VECCOPY(co, pa->hair[0].co);
+               Mat4MulVecfl(mat, co);
+               co[0]= -co[0];
+
+               index= BLI_kdtree_find_nearest(tree, co, NULL, &nearest);
+
+               /* this needs a custom threshold still, duplicated for editmode mirror */
+               if(index != -1 && index != i && (nearest.dist <= 0.0002f))
+                       edit->mirror_cache[i]= index;
+               else
+                       edit->mirror_cache[i]= -1;
+       }
+
+       /* make sure mirrors are in two directions */
+       LOOP_PARTICLES(i,pa) {
+               if(edit->mirror_cache[i]) {
+                       index= edit->mirror_cache[i];
+                       if(edit->mirror_cache[index] != i)
+                               edit->mirror_cache[i]= -1;
+               }
+       }
+
+       BLI_kdtree_free(tree);
+}
+
+static void PE_mirror_particle(Object *ob, DerivedMesh *dm, ParticleSystem *psys, ParticleData *pa, ParticleData *mpa)
+{
+       HairKey *hkey, *mhkey;
+       ParticleEditKey *key, *mkey;
+       ParticleEdit *edit;
+       float mat[4][4], mmat[4][4], immat[4][4];
+       int i, mi, k;
+
+       edit= psys->edit;
+       i= pa - psys->particles;
+
+       /* find mirrored particle if needed */
+       if(!mpa) {
+               if(!edit->mirror_cache)
+                       PE_update_mirror_cache(ob, psys);
+
+               mi= edit->mirror_cache[i];
+               if(mi == -1)
+                       return;
+               mpa= psys->particles + mi;
+       }
+       else
+               mi= mpa - psys->particles;
+
+       /* make sure they have the same amount of keys */
+       if(pa->totkey != mpa->totkey) {
+               if(mpa->hair) MEM_freeN(mpa->hair);
+               if(edit->keys[mi]) MEM_freeN(edit->keys[mi]);
+
+               mpa->hair= MEM_dupallocN(pa->hair);
+               edit->keys[mi]= MEM_dupallocN(edit->keys[i]);
+               mpa->totkey= pa->totkey;
+
+               mhkey= mpa->hair;
+               mkey= edit->keys[mi];
+               for(k=0; k<mpa->totkey; k++, mkey++, mhkey++) {
+                       mkey->co= mhkey->co;
+                       mkey->time= &mhkey->time;
+                       mkey->flag &= PEK_SELECT;
+               }
+       }
+
+       /* mirror positions and tags */
+       psys_mat_hair_to_orco(ob, dm, psys->part->from, pa, mat);
+       psys_mat_hair_to_orco(ob, dm, psys->part->from, mpa, mmat);
+       Mat4Invert(immat, mmat);
+
+       hkey=pa->hair;
+       mhkey=mpa->hair;
+       key= edit->keys[i];
+       mkey= edit->keys[mi];
+       for(k=0; k<pa->totkey; k++, hkey++, mhkey++, key++, mkey++) {
+               VECCOPY(mhkey->co, hkey->co);
+               Mat4MulVecfl(mat, mhkey->co);
+               mhkey->co[0]= -mhkey->co[0];
+               Mat4MulVecfl(immat, mhkey->co);
+
+               if(key->flag & PEK_TAG)
+                       mkey->flag |= PEK_TAG;
+       }
+
+       if(pa->flag & PARS_TAG)
+               mpa->flag |= PARS_TAG;
+       if(pa->flag & PARS_EDIT_RECALC)
+               mpa->flag |= PARS_EDIT_RECALC;
+}
+
+static void PE_apply_mirror(Object *ob, ParticleSystem *psys)
+{
+       ParticleEdit *edit;
+       ParticleData *pa;
+       ParticleSystemModifierData *psmd;
+       int i, totpart;
+
+       edit= psys->edit;
+       psmd= psys_get_modifier(ob, psys);
+       totpart= psys->totpart;
+
+       /* we delay settings the PARS_EDIT_RECALC for mirrored particles
+        * to avoid doing mirror twice */
+       LOOP_PARTICLES(i,pa) {
+               if(pa->flag & PARS_EDIT_RECALC) {
+                       PE_mirror_particle(ob, psmd->dm, psys, pa, NULL);
+
+                       if(edit->mirror_cache[i] != -1)
+                               psys->particles[edit->mirror_cache[i]].flag &= ~PARS_EDIT_RECALC;
+               }
+       }
+
+       LOOP_PARTICLES(i,pa)
+               if(pa->flag & PARS_EDIT_RECALC)
+                       if(edit->mirror_cache[i] != -1)
+                               psys->particles[edit->mirror_cache[i]].flag |= PARS_EDIT_RECALC;
+
+       edit->totkeys= psys_count_keys(psys);
+}
+
+/************************************************/
+/*                     Edit Calculation                                        */
+/************************************************/
+/* tries to stop edited particles from going through the emitter's surface */
+static void pe_deflect_emitter(Scene *scene, Object *ob, ParticleSystem *psys)
+{
+       ParticleEdit *edit;
+       ParticleData *pa;
+       ParticleEditKey *key;
+       ParticleEditSettings *pset = PE_settings(scene);
+       ParticleSystemModifierData *psmd = psys_get_modifier(ob,psys);
+       int i,k,totpart,index;
+       float *vec, *nor, dvec[3], dot, dist_1st;
+       float hairimat[4][4], hairmat[4][4];
+
+       if(psys==0)
+               return;
+
+       if((pset->flag & PE_DEFLECT_EMITTER)==0)
+               return;
+
+       edit=psys->edit;
+       totpart=psys->totpart;
+
+       LOOP_PARTICLES(i,pa){
+               if(!(pa->flag & PARS_EDIT_RECALC))
+                       continue;
+               
+               psys_mat_hair_to_object(ob, psmd->dm, psys->part->from, pa, hairmat);
+               
+               LOOP_KEYS(k,key){
+                       Mat4MulVecfl(hairmat, key->co);
+               }
+       //}
+
+       //LOOP_PARTICLES(i,pa){
+               key=psys->edit->keys[i]+1;
+
+               dist_1st=VecLenf((key-1)->co,key->co);
+               dist_1st*=0.75f*pset->emitterdist;
+
+               for(k=1; k<pa->totkey; k++, key++){
+                       index= BLI_kdtree_find_nearest(edit->emitter_field,key->co,NULL,NULL);
+                       
+                       vec=edit->emitter_cosnos +index*6;
+                       nor=vec+3;
+
+                       VecSubf(dvec, key->co, vec);
+
+                       dot=Inpf(dvec,nor);
+                       VECCOPY(dvec,nor);
+
+                       if(dot>0.0f){
+                               if(dot<dist_1st){
+                                       Normalize(dvec);
+                                       VecMulf(dvec,dist_1st-dot);
+                                       VecAddf(key->co,key->co,dvec);
+                               }
+                       }
+                       else{
+                               Normalize(dvec);
+                               VecMulf(dvec,dist_1st-dot);
+                               VecAddf(key->co,key->co,dvec);
+                       }
+                       if(k==1)
+                               dist_1st*=1.3333f;
+               }
+       //}
+
+       //LOOP_PARTICLES(i,pa){
+               
+               Mat4Invert(hairimat,hairmat);
+
+               LOOP_KEYS(k,key){
+                       Mat4MulVecfl(hairimat, key->co);
+               }
+       }
+}
+/* force set distances between neighbouring keys */
+void PE_apply_lengths(Scene *scene, ParticleSystem *psys)
+{
+       ParticleEdit *edit;
+       ParticleData *pa;
+       ParticleEditKey *key;
+       ParticleEditSettings *pset=PE_settings(scene);
+       int i,k,totpart;
+       float dv1[3];
+
+       if(psys==0)
+               return;
+
+       if((pset->flag & PE_KEEP_LENGTHS)==0)
+               return;
+
+       edit=psys->edit;
+       totpart=psys->totpart;
+
+       LOOP_PARTICLES(i,pa){
+               if(!(pa->flag & PARS_EDIT_RECALC))
+                       continue;
+               
+               for(k=1, key=edit->keys[i] + 1; k<pa->totkey; k++, key++){
+                       VecSubf(dv1, key->co, (key - 1)->co);
+                       Normalize(dv1);
+                       VecMulf(dv1, (key - 1)->length);
+                       VecAddf(key->co, (key - 1)->co, dv1);
+               }
+       }
+}
+/* try to find a nice solution to keep distances between neighbouring keys */
+static void pe_iterate_lengths(Scene *scene, ParticleSystem *psys)
+{
+       ParticleEdit *edit;
+       ParticleData *pa;
+       ParticleEditKey *key;
+       ParticleEditSettings *pset=PE_settings(scene);
+       int i, j, k,totpart;
+       float tlen;
+       float dv0[3] = {0.0f, 0.0f, 0.0f};
+       float dv1[3] = {0.0f, 0.0f, 0.0f};
+       float dv2[3] = {0.0f, 0.0f, 0.0f};
+
+       if(psys==0)
+               return;
+
+       if((pset->flag & PE_KEEP_LENGTHS)==0)
+               return;
+
+       edit=psys->edit;
+       totpart=psys->totpart;
+
+       LOOP_PARTICLES(i,pa){
+               if(!(pa->flag & PARS_EDIT_RECALC))
+                       continue;
+
+               for(j=1; j<pa->totkey; j++){
+                       float mul = 1.0f / (float)pa->totkey;
+
+                       if(pset->flag & PE_LOCK_FIRST){
+                               key = edit->keys[i] + 1;
+                               k = 1;
+                               dv1[0] = dv1[1] = dv1[2] = 0.0;
+                       }
+                       else{
+                               key = edit->keys[i];
+                               k = 0;
+                               dv0[0] = dv0[1] = dv0[2] = 0.0;
+                       }
+
+                       for(; k<pa->totkey; k++, key++){
+                               if(k){
+                                       VecSubf(dv0, (key - 1)->co, key->co);
+                                       tlen = Normalize(dv0);
+                                       VecMulf(dv0, (mul * (tlen - (key - 1)->length)));
+                               }
+
+                               if(k < pa->totkey - 1){
+                                       VecSubf(dv2, (key + 1)->co, key->co);
+                                       tlen = Normalize(dv2);
+                                       VecMulf(dv2, mul * (tlen - key->length));
+                               }
+
+                               if(k){
+                                       VecAddf((key-1)->co,(key-1)->co,dv1);
+                               }
+
+                               VECADD(dv1,dv0,dv2);
+                       }
+               }
+       }
+}
+/* set current distances to be kept between neighbouting keys */
+static void recalc_lengths(ParticleSystem *psys)
+{
+       ParticleData *pa;
+       ParticleEditKey *key;
+       int i, k, totpart;
+
+       if(psys==0)
+               return;
+
+       totpart = psys->totpart;
+
+       LOOP_PARTICLES(i,pa){
+               key = psys->edit->keys[i];
+               for(k=0; k<pa->totkey-1; k++, key++){
+                       key->length = VecLenf(key->co, (key + 1)->co);
+               }
+       }
+}
+/* calculate and store key locations in world coordinates */
+void PE_recalc_world_cos(Object *ob, ParticleSystem *psys)
+{
+       ParticleSystemModifierData *psmd = psys_get_modifier(ob, psys);
+       ParticleData *pa;
+       ParticleEditKey *key;
+       int i, k, totpart;
+       float hairmat[4][4];
+
+       if(psys==0)
+               return;
+
+       totpart = psys->totpart;
+
+       LOOP_PARTICLES(i,pa){
+               psys_mat_hair_to_global(ob, psmd->dm, psys->part->from, pa, hairmat);
+
+               LOOP_KEYS(k,key){
+                       VECCOPY(key->world_co,key->co);
+                       Mat4MulVecfl(hairmat, key->world_co);
+               }
+       }
+}
+/* calculate a tree for finding nearest emitter's vertice */
+static void recalc_emitter_field(Object *ob, ParticleSystem *psys)
+{
+       DerivedMesh *dm=psys_get_modifier(ob,psys)->dm;
+       ParticleEdit *edit = psys->edit;
+       MFace *mface;
+       MVert *mvert;
+       float *vec, *nor;
+       int i, totface, totvert;
+
+       if(edit->emitter_cosnos)
+               MEM_freeN(edit->emitter_cosnos);
+
+       BLI_kdtree_free(edit->emitter_field);
+
+       totface=dm->getNumFaces(dm);
+       totvert=dm->getNumVerts(dm);
+
+       edit->emitter_cosnos=MEM_callocN(totface*6*sizeof(float),"emitter cosnos");
+
+       edit->emitter_field= BLI_kdtree_new(totface);
+
+       vec=edit->emitter_cosnos;
+       nor=vec+3;
+
+       mvert=dm->getVertDataArray(dm,CD_MVERT);
+       for(i=0; i<totface; i++, vec+=6, nor+=6){
+               mface=dm->getFaceData(dm,i,CD_MFACE);
+
+               mvert=dm->getVertData(dm,mface->v1,CD_MVERT);
+               VECCOPY(vec,mvert->co);
+               VECCOPY(nor,mvert->no);
+
+               mvert=dm->getVertData(dm,mface->v2,CD_MVERT);
+               VECADD(vec,vec,mvert->co);
+               VECADD(nor,nor,mvert->no);
+
+               mvert=dm->getVertData(dm,mface->v3,CD_MVERT);
+               VECADD(vec,vec,mvert->co);
+               VECADD(nor,nor,mvert->no);
+
+               if (mface->v4){
+                       mvert=dm->getVertData(dm,mface->v4,CD_MVERT);
+                       VECADD(vec,vec,mvert->co);
+                       VECADD(nor,nor,mvert->no);
+                       
+                       VecMulf(vec,0.25);
+               }
+               else
+                       VecMulf(vec,0.3333f);
+
+               Normalize(nor);
+
+               BLI_kdtree_insert(edit->emitter_field, i, vec, NULL);
+       }
+
+       BLI_kdtree_balance(edit->emitter_field);
+}
+
+void PE_update_selection(Scene *scene, Object *ob, int useflag)
+{
+       ParticleSystem *psys= PE_get_current(ob);
+       ParticleEdit *edit= psys->edit;
+       ParticleEditSettings *pset= PE_settings(scene);
+       ParticleSettings *part= psys->part;
+       ParticleData *pa;
+       HairKey *hkey;
+       ParticleEditKey *key;
+       float cfra= CFRA;
+       int i, k, totpart;
+
+       totpart= psys->totpart;
+
+       /* flag all particles to be updated if not using flag */
+       if(!useflag)
+               LOOP_PARTICLES(i,pa)
+                       pa->flag |= PARS_EDIT_RECALC;
+
+       /* flush edit key flag to hair key flag to preserve selection 
+        * on save */
+       LOOP_PARTICLES(i,pa) {
+               key = edit->keys[i];
+
+               for(k=0, hkey=pa->hair; k<pa->totkey; k++, hkey++, key++)
+                       hkey->editflag= key->flag;
+       }
+
+       psys_cache_paths(scene, ob, psys, CFRA, 1);
+
+       if(part->childtype && (pset->flag & PE_SHOW_CHILD))
+               psys_cache_child_paths(scene, ob, psys, cfra, 1);
+
+       /* disable update flag */
+       LOOP_PARTICLES(i,pa)
+               pa->flag &= ~PARS_EDIT_RECALC;
+}
+
+void PE_update_object(Scene *scene, Object *ob, int useflag)
+{
+       ParticleSystem *psys= PE_get_current(ob);
+       ParticleEditSettings *pset= PE_settings(scene);
+       ParticleSettings *part= psys->part;
+       ParticleData *pa;
+       float cfra= CFRA;
+       int i, totpart= psys->totpart;
+
+       /* flag all particles to be updated if not using flag */
+       if(!useflag)
+               LOOP_PARTICLES(i,pa)
+                       pa->flag |= PARS_EDIT_RECALC;
+
+       /* do post process on particle edit keys */
+       pe_iterate_lengths(scene, psys);
+       pe_deflect_emitter(scene, ob, psys);
+       PE_apply_lengths(scene, psys);
+       if(pset->flag & PE_X_MIRROR)
+               PE_apply_mirror(ob,psys);
+       PE_recalc_world_cos(ob,psys);
+       PE_hide_keys_time(scene, psys, cfra);
+
+       /* regenerate path caches */
+       psys_cache_paths(scene, ob, psys, cfra, 1);
+
+       if(part->childtype && (pset->flag & PE_SHOW_CHILD))
+               psys_cache_child_paths(scene, ob, psys, cfra, 1);
+
+       /* disable update flag */
+       LOOP_PARTICLES(i,pa)
+               pa->flag &= ~PARS_EDIT_RECALC;
+}
+
+/* initialize needed data for bake edit */
+void PE_create_particle_edit(Object *ob, ParticleSystem *psys)
+{
+       Scene *scene= NULL; // XXX
+       ParticleEdit *edit=psys->edit;
+       ParticleData *pa;
+       ParticleEditKey *key;
+       HairKey *hkey;
+       int i,k, totpart=psys->totpart, alloc=1;
+
+       if((psys->flag & PSYS_EDITED)==0)
+               return;
+
+       if(edit){
+               int newtotkeys = psys_count_keys(psys);
+               if(newtotkeys == edit->totkeys)
+                       alloc=0;
+       }
+
+       if(alloc){
+               if(edit){
+                       error("ParticleEdit exists allready! Poke jahka!");
+                       PE_free_particle_edit(psys);
+               }
+
+               edit=psys->edit=MEM_callocN(sizeof(ParticleEdit), "PE_create_particle_edit");
+
+               edit->keys=MEM_callocN(totpart*sizeof(ParticleEditKey*),"ParticleEditKey array");
+
+               LOOP_PARTICLES(i,pa){
+                       key = edit->keys[i] = MEM_callocN(pa->totkey*sizeof(ParticleEditKey),"ParticleEditKeys");
+                       for(k=0, hkey=pa->hair; k<pa->totkey; k++, hkey++, key++){
+                               key->co = hkey->co;
+                               key->time = &hkey->time;
+                               key->flag= hkey->editflag;
+                       }
+               }
+
+               edit->totkeys = psys_count_keys(psys);
+       }
+
+       recalc_lengths(psys);
+       recalc_emitter_field(ob, psys);
+       PE_recalc_world_cos(ob, psys);
+
+       if(alloc) {
+               ParticleUndo_clear(psys);
+               PE_undo_push(scene, "Original");
+       }
+}
+
+/* toggle particle mode on & off */
+void PE_set_particle_edit(Scene *scene)
+{
+       Object *ob= OBACT;
+       ParticleSystem *psys = PE_get_current(ob);
+
+       
+       //if(!ob || ob->id.lib) return; /* is the id.lib test needed? -jahka*/
+       if(ob==0 || psys==0) return;
+       
+       if(psys==0){
+               if(ob->particlesystem.first){
+                       psys=ob->particlesystem.first;
+                       psys->flag |= PSYS_CURRENT;
+               }
+               else
+                       return;
+       }
+
+       if((G.f & G_PARTICLEEDIT)==0){
+               if(psys && psys->part->type == PART_HAIR && psys->flag & PSYS_EDITED) {
+                       if(psys_check_enabled(ob, psys)) {
+                               if(psys->edit==0)
+                                       PE_create_particle_edit(ob, psys);
+                               PE_recalc_world_cos(ob, psys);
+                       }
+               }
+
+               G.f |= G_PARTICLEEDIT;
+       }
+       else{
+               G.f &= ~G_PARTICLEEDIT;
+       }
+
+       DAG_object_flush_update(scene, OBACT, OB_RECALC_DATA);
+
+}
+
+/************************************************/
+/*                     Edit Selections                                         */
+/************************************************/
+/*-----selection callbacks-----*/
+static void select_key(ParticleSystem *psys, int pa_index, int key_index, void *userData)
+{
+       struct {Scene *scene; short *mval; float rad; rcti* rect; int select; } *data = userData;
+       ParticleData *pa = psys->particles + pa_index;
+       ParticleEditKey *key = psys->edit->keys[pa_index] + key_index;
+
+       if(data->select)
+               key->flag|=PEK_SELECT;
+       else
+               key->flag&=~PEK_SELECT;
+
+       pa->flag |= PARS_EDIT_RECALC;
+}
+
+static void select_keys(ParticleSystem *psys, int pa_index, int key_index, void *userData)
+{
+       struct {Scene *scene; short *mval; float rad; rcti* rect; int select; } *data = userData;
+       ParticleData *pa = psys->particles + pa_index;
+       ParticleEditKey *key = psys->edit->keys[pa_index];
+       int k;
+
+       for(k=0; k<pa->totkey; k++,key++){
+               if(data->select)
+                       key->flag|=PEK_SELECT;
+               else
+                       key->flag&=~PEK_SELECT;
+       }
+
+       pa->flag |= PARS_EDIT_RECALC;
+}
+
+static void toggle_key_select(ParticleSystem *psys, int pa_index, int key_index, void *userData)
+{
+       ParticleData *pa = psys->particles + pa_index;
+
+       if(psys->edit->keys[pa_index][key_index].flag&PEK_SELECT)
+               psys->edit->keys[pa_index][key_index].flag&=~PEK_SELECT;
+       else
+               psys->edit->keys[pa_index][key_index].flag|=PEK_SELECT;
+       
+       pa->flag |= PARS_EDIT_RECALC;
+}
+
+static void select_root(ParticleSystem *psys, int index, void *userData)
+{
+       psys->edit->keys[index]->flag |= PEK_SELECT;
+}
+
+static void select_tip(ParticleSystem *psys, int index, void *userData)
+{
+       ParticleData *pa = psys->particles + index;
+       ParticleEditKey *key = psys->edit->keys[index] + pa->totkey-1;
+
+       key->flag |= PEK_SELECT;
+}
+static void select_more_keys(ParticleSystem *psys, int index, void *userData)
+{
+       ParticleEdit *edit = psys->edit;
+       ParticleData *pa = psys->particles+index;
+       ParticleEditKey *key;
+       int k;
+
+       for(k=0,key=edit->keys[index]; k<pa->totkey; k++,key++){
+               if(key->flag&PEK_SELECT) continue;
+
+               if(k==0){
+                       if((key+1)->flag&PEK_SELECT)
+                               key->flag |= PEK_TO_SELECT;
+               }
+               else if(k==pa->totkey-1){
+                       if((key-1)->flag&PEK_SELECT)
+                               key->flag |= PEK_TO_SELECT;
+               }
+               else{
+                       if(((key-1)->flag | (key+1)->flag) & PEK_SELECT)
+                               key->flag |= PEK_TO_SELECT;
+               }
+       }
+
+       for(k=0,key=edit->keys[index]; k<pa->totkey; k++,key++){
+               if(key->flag&PEK_TO_SELECT){
+                       key->flag &= ~PEK_TO_SELECT;
+                       key->flag |= PEK_SELECT;
+               }
+       }
+}
+
+static void select_less_keys(ParticleSystem *psys, int index, void *userData)
+{
+       ParticleEdit *edit = psys->edit;
+       ParticleData *pa = psys->particles+index;
+       ParticleEditKey *key;
+       int k;
+
+       for(k=0,key=edit->keys[index]; k<pa->totkey; k++,key++){
+               if((key->flag&PEK_SELECT)==0) continue;
+
+               if(k==0){
+                       if(((key+1)->flag&PEK_SELECT)==0)
+                               key->flag |= PEK_TO_SELECT;
+               }
+               else if(k==pa->totkey-1){
+                       if(((key-1)->flag&PEK_SELECT)==0)
+                               key->flag |= PEK_TO_SELECT;
+               }
+               else{
+                       if((((key-1)->flag & (key+1)->flag) & PEK_SELECT)==0)
+                               key->flag |= PEK_TO_SELECT;
+               }
+       }
+
+       for(k=0,key=edit->keys[index]; k<pa->totkey; k++,key++){
+               if(key->flag&PEK_TO_SELECT)
+                       key->flag &= ~(PEK_TO_SELECT|PEK_SELECT);
+       }
+}
+
+/*-----using above callbacks-----*/
+void PE_deselectall(void)
+{
+       Scene *scene= NULL;
+       Object *ob = OBACT;
+       ParticleSystem *psys = PE_get_current(ob);
+       ParticleEdit *edit = 0;
+       ParticleData *pa;
+       ParticleEditKey *key;
+       int i,k,totpart, sel = 0;
+               
+       if(!PE_can_edit(psys)) return;
+       
+       edit = psys->edit;
+
+       totpart = psys->totpart;
+       
+       LOOP_PARTICLES(i,pa){
+               if(pa->flag & PARS_HIDE) continue;
+               LOOP_KEYS(k,key){
+                       if(key->flag&PEK_SELECT){
+                               sel = 1;
+                               key->flag &= ~PEK_SELECT;
+                               pa->flag |= PARS_EDIT_RECALC;
+                       }
+               }
+       }
+
+       if(sel==0){
+               LOOP_PARTICLES(i,pa){
+                       if(pa->flag & PARS_HIDE) continue;
+                       LOOP_KEYS(k,key){
+                               if(!(key->flag & PEK_SELECT)) {
+                                       key->flag |= PEK_SELECT;
+                                       pa->flag |= PARS_EDIT_RECALC;
+                               }
+                       }
+               }
+       }
+
+       PE_update_selection(scene, ob, 1);
+
+       BIF_undo_push("(De)select all keys");
+}
+
+void PE_mouse_particles(void)
+{
+       struct {Scene *scene;  short *mval; float rad; rcti* rect; int select; } data;
+       Scene *scene= NULL;
+       Object *ob = OBACT;
+       ParticleSystem *psys = PE_get_current(ob);
+       ParticleEdit *edit = 0;
+       ParticleData *pa;
+       ParticleEditKey *key;
+       short mval[2];
+       int i,k,totpart;
+       int shift= 0; // XXX
+       
+       if(!PE_can_edit(psys)) return;
+
+       edit = psys->edit;
+
+       totpart = psys->totpart;
+
+       bglFlush();
+       glReadBuffer(GL_BACK);
+       glDrawBuffer(GL_BACK);
+//     persp(PERSP_VIEW);
+
+       if(shift)
+               LOOP_PARTICLES(i,pa){
+                       if(pa->flag & PARS_HIDE) continue;
+                       LOOP_KEYS(k,key){
+                               if(key->flag & PEK_SELECT) {
+                                       key->flag &= ~PEK_SELECT;
+                                       pa->flag |= PARS_EDIT_RECALC;
+                               }
+                       }
+               }
+
+//     getmouseco_areawin(mval);
+
+       data.scene= scene;
+       data.mval= mval;
+       data.rad= 75.0f;
+       data.rect= 0;
+       data.select= 0;
+
+       for_mouse_hit_keys(1,psys,toggle_key_select,&data);
+
+       PE_update_selection(scene, ob, 1);
+
+}
+
+void PE_select_root(void)
+{
+       Object *ob=NULL; // XXX
+       ParticleSystem *psys = PE_get_current(ob);
+
+       if(!PE_can_edit(psys)) return;
+
+       PE_foreach_element(psys,select_root,NULL);
+       BIF_undo_push("Select first");
+}
+
+void PE_select_tip()
+{
+       Object *ob=NULL; // XXX
+       ParticleSystem *psys = PE_get_current(ob);
+
+       if(!PE_can_edit(psys)) return;
+
+       PE_foreach_element(psys,select_tip,NULL);
+       BIF_undo_push("Select last");
+}
+
+void PE_select_linked(void)
+{
+       struct {Scene *scene;  short *mval; float rad; rcti* rect; int select; } data;
+       Object *ob=NULL; // XXX
+       Scene *scene= NULL;
+       ParticleSystem *psys = PE_get_current(ob);
+       short mval[2];
+       int shift= 0; // XXX
+       
+       if(!PE_can_edit(psys)) return;
+
+//     getmouseco_areawin(mval);
+
+       data.scene= NULL; // XXX
+       data.mval=mval;
+       data.rad=75.0f;
+       data.rect=0;
+       data.select=(shift);
+
+       for_mouse_hit_keys(1,psys,select_keys,&data);
+
+       PE_update_selection(scene, ob, 1);
+
+       BIF_undo_push("Select linked keys");
+
+       return;
+}
+
+void PE_borderselect(ViewContext *vc, rcti *rect, int select)
+{
+       struct {Scene *scene;  short *mval; float rad; rcti* rect; int select; } data;
+       Scene *scene= vc->scene;
+       Object *ob= vc->obact;
+       ParticleSystem *psys = PE_get_current(ob);
+
+       if(!PE_can_edit(psys)) return;
+
+       data.scene= scene;
+       data.mval=0;
+       data.rect= rect;
+       data.select= select;
+
+       for_mouse_hit_keys(0, psys, select_key, &data);
+
+       PE_update_selection(scene, ob, 1);
+
+       BIF_undo_push("Select keys");
+
+       return;
+}
+
+void PE_selectionCB(short selecting, Object *editobj, short *mval, float rad)
+{
+       struct {Scene *scene;  short *mval; float rad; rcti* rect; int select; } data;
+       Scene *scene= NULL;
+       ParticleSystem *psys = PE_get_current(OBACT);
+
+       if(!PE_can_edit(psys)) return;
+
+       data.scene= scene;
+       data.mval=mval;
+       data.rad=rad;
+       data.rect=0;
+       data.select=(selecting==LEFTMOUSE);
+
+       for_mouse_hit_keys(0,psys,select_key,&data);
+
+//     draw_sel_circle(0, 0, 0, 0, 0); /* signal */
+}
+
+void PE_do_lasso_select(ViewContext *vc, short mcords[][2], short moves, short select)
+{
+       Scene *scene= vc->scene;
+       ARegion *ar= vc->ar;
+       Object *ob = OBACT;
+       ParticleSystem *psys = PE_get_current(ob);
+       ParticleSystemModifierData *psmd;
+       ParticleEdit *edit;
+       ParticleData *pa;
+       ParticleEditKey *key;
+       float co[3], mat[4][4];
+       short vertco[2];
+       int i, k, totpart;
+
+       if(!PE_can_edit(psys)) return;
+
+       psmd= psys_get_modifier(ob, psys);
+       edit=psys->edit;
+       totpart=psys->totpart;
+
+       LOOP_PARTICLES(i,pa){
+               if(pa->flag & PARS_HIDE) continue;
+
+               psys_mat_hair_to_global(ob, psmd->dm, psys->part->from, pa, mat);
+
+               if(scene->selectmode==SCE_SELECT_POINT){
+                       LOOP_KEYS(k,key){
+                               VECCOPY(co, key->co);
+                               Mat4MulVecfl(mat, co);
+                               project_short(ar, co, vertco);
+                               if((vertco[0] != IS_CLIPPED) && lasso_inside(mcords,moves,vertco[0],vertco[1])){
+                                       if(select && !(key->flag & PEK_SELECT)) {
+                                               key->flag|=PEK_SELECT;
+                                               pa->flag |= PARS_EDIT_RECALC;
+                                       }
+                                       else if(key->flag & PEK_SELECT) {
+                                               key->flag&=~PEK_SELECT;
+                                               pa->flag |= PARS_EDIT_RECALC;
+                                       }
+                               }
+                       }
+               }
+               else if(scene->selectmode==SCE_SELECT_END){
+                       key = edit->keys[i] + pa->totkey - 1;
+
+                       VECCOPY(co, key->co);
+                       Mat4MulVecfl(mat, co);
+                       project_short(ar, co,vertco);
+                       if((vertco[0] != IS_CLIPPED) && lasso_inside(mcords,moves,vertco[0],vertco[1])){
+                               if(select && !(key->flag & PEK_SELECT)) {
+                                       key->flag|=PEK_SELECT;
+                                       pa->flag |= PARS_EDIT_RECALC;
+                               }
+                               else if(key->flag & PEK_SELECT) {
+                                       key->flag&=~PEK_SELECT;
+                                       pa->flag |= PARS_EDIT_RECALC;
+                               }
+                       }
+               }
+       }
+
+       PE_update_selection(scene, ob, 1);
+
+       BIF_undo_push("Lasso select particles");
+
+}
+
+void PE_hide(int mode)
+{
+       Scene *scene= NULL;
+       Object *ob = OBACT;
+       ParticleSystem *psys = PE_get_current(ob);
+       ParticleEdit *edit;
+       ParticleEditKey *key;
+       ParticleData *pa;
+       int i, k, totpart;
+
+       if(!PE_can_edit(psys)) return;
+
+       edit = psys->edit;
+       totpart = psys->totpart;
+       
+       if(mode == 0){ /* reveal all particles */
+               LOOP_PARTICLES(i, pa){
+                       if(pa->flag & PARS_HIDE) {
+                               pa->flag &= ~PARS_HIDE;
+                               pa->flag |= PARS_EDIT_RECALC;
+
+                               LOOP_KEYS(k, key)
+                                       key->flag |= PEK_SELECT;
+                       }
+               }
+       }
+       else if(mode == 1){ /* hide unselected particles */
+               LOOP_PARTICLES(i, pa) {
+                       if(!particle_is_selected(psys, pa)) {
+                               pa->flag |= PARS_HIDE;
+                               pa->flag |= PARS_EDIT_RECALC;
+
+                               LOOP_KEYS(k, key)
+                                       key->flag &= ~PEK_SELECT;
+                       }
+               }
+       }
+       else{ /* hide selected particles */
+               LOOP_PARTICLES(i, pa) {
+                       if(particle_is_selected(psys, pa)) {
+                               pa->flag |= PARS_HIDE;
+                               pa->flag |= PARS_EDIT_RECALC;
+
+                               LOOP_KEYS(k, key)
+                                       key->flag &= ~PEK_SELECT;
+                       }
+               }
+       }
+
+       PE_update_selection(scene, ob, 1);
+       BIF_undo_push("(Un)hide elements");
+       
+}
+
+void PE_select_less(void)
+{
+       Scene *scene= NULL;
+       ParticleSystem *psys = PE_get_current(OBACT);
+
+       if(!PE_can_edit(psys)) return;
+
+       PE_foreach_element(psys,select_less_keys,NULL);
+       
+       BIF_undo_push("Select less");
+}
+
+void PE_select_more(void)
+{
+       Scene *scene= NULL;
+       ParticleSystem *psys = PE_get_current(OBACT);
+
+       if(!PE_can_edit(psys)) return;
+
+       PE_foreach_element(psys,select_more_keys,NULL);
+       
+       BIF_undo_push("Select more");
+}
+
+/************************************************/
+/*                     Edit Rekey                                                      */
+/************************************************/
+static void rekey_element(ParticleSystem *psys, int index, void *userData)
+{
+       struct {Scene *scene; Object *ob; float dval; } *data = userData;
+       ParticleData *pa = psys->particles + index;
+       ParticleEdit *edit = psys->edit;
+       ParticleEditSettings *pset = PE_settings(data->scene);
+       ParticleKey state;
+       HairKey *key, *new_keys;
+       ParticleEditKey *ekey;
+       float dval, sta, end;
+       int k;
+
+       pa->flag |= PARS_REKEY;
+
+       key = new_keys = MEM_callocN(pset->totrekey * sizeof(HairKey),"Hair re-key keys");
+
+       /* root and tip stay the same */
+       VECCOPY(key->co, pa->hair->co);
+       VECCOPY((key + pset->totrekey - 1)->co, (pa->hair + pa->totkey - 1)->co);
+
+       sta = key->time = pa->hair->time;
+       end = (key + pset->totrekey - 1)->time = (pa->hair + pa->totkey - 1)->time;
+       dval = (end - sta) / (float)(pset->totrekey - 1);
+
+       /* interpolate new keys from old ones */
+       for(k=1,key++; k<pset->totrekey-1; k++,key++) {
+               state.time = (float)k / (float)(pset->totrekey-1);
+               psys_get_particle_on_path(data->scene, data->ob, psys, index, &state, 0);
+               VECCOPY(key->co, state.co);
+               key->time = sta + k * dval;
+       }
+
+       /* replace keys */
+       if(pa->hair)
+               MEM_freeN(pa->hair);
+       pa->hair = new_keys;
+
+       pa->totkey=pset->totrekey;
+
+       if(edit->keys[index])
+               MEM_freeN(edit->keys[index]);
+       ekey = edit->keys[index] = MEM_callocN(pa->totkey * sizeof(ParticleEditKey),"Hair re-key edit keys");
+               
+       for(k=0, key=pa->hair; k<pa->totkey; k++, key++, ekey++) {
+               ekey->co = key->co;
+               ekey->time = &key->time;
+       }
+
+       pa->flag &= ~PARS_REKEY;
+       pa->flag |= PARS_EDIT_RECALC;
+}
+
+void PE_rekey(void)
+{
+       Scene *scene= NULL; // XXX
+       Object *ob=OBACT;
+       ParticleSystem *psys = PE_get_current(ob);
+       ParticleEditSettings *pset = PE_settings(scene);
+       struct {Scene *scene; Object *ob; float dval; } data;
+
+       if(!PE_can_edit(psys)) return;
+
+       data.scene = scene;
+       data.ob = ob;
+       data.dval = 1.0f / (float)(pset->totrekey-1);
+
+       foreach_selected_element(psys, rekey_element, &data);
+       
+       psys->edit->totkeys = psys_count_keys(psys);
+
+       recalc_lengths(psys);
+       
+       PE_update_object(scene, ob, 1);
+
+       BIF_undo_push("Re-key particles");
+}
+
+static void rekey_element_to_time(Object *ob, int index, float path_time)
+{
+       Scene *scene= NULL; // XXX
+       ParticleSystem *psys = PE_get_current(ob);
+       ParticleEdit *edit=0;
+       ParticleData *pa;
+       ParticleKey state;
+       HairKey *new_keys, *key;
+       ParticleEditKey *ekey;
+       int k;
+
+       if(psys==0) return;
+
+       edit = psys->edit;
+
+       pa = psys->particles + index;
+
+       pa->flag |= PARS_REKEY;
+
+       key = new_keys = MEM_dupallocN(pa->hair);
+       
+       /* interpolate new keys from old ones (roots stay the same) */
+       for(k=1, key++; k < pa->totkey; k++, key++) {
+               state.time = path_time * (float)k / (float)(pa->totkey-1);
+               psys_get_particle_on_path(scene, ob, psys, index, &state, 0);
+               VECCOPY(key->co, state.co);
+       }
+
+       /* replace hair keys */
+       if(pa->hair)
+               MEM_freeN(pa->hair);
+       pa->hair = new_keys;
+
+       /* update edit pointers */
+       for(k=0, key=pa->hair, ekey=edit->keys[index]; k<pa->totkey; k++, key++, ekey++) {
+               ekey->co = key->co;
+               ekey->time = &key->time;
+       }
+
+       pa->flag &= ~PARS_REKEY;
+}
+
+static int remove_tagged_elements(Scene *scene, Object *ob, ParticleSystem *psys)
+{
+       ParticleEdit *edit = psys->edit;
+       ParticleEditSettings *pset = PE_settings(scene);
+       ParticleData *pa, *npa=0, *new_pars=0;
+       ParticleEditKey **key, **nkey=0, **new_keys=0;
+       ParticleSystemModifierData *psmd;
+       int i, totpart, new_totpart = psys->totpart, removed = 0;
+
+       if(pset->flag & PE_X_MIRROR) {
+               /* mirror tags */
+               psmd = psys_get_modifier(ob, psys);
+               totpart = psys->totpart;
+
+               LOOP_PARTICLES(i,pa)
+                       if(pa->flag & PARS_TAG)
+                               PE_mirror_particle(ob, psmd->dm, psys, pa, NULL);
+       }
+
+       for(i=0, pa=psys->particles; i<psys->totpart; i++, pa++) {
+               if(pa->flag & PARS_TAG) {
+                       new_totpart--;
+                       removed++;
+               }
+       }
+
+       if(new_totpart != psys->totpart) {
+               if(new_totpart) {
+                       npa = new_pars = MEM_callocN(new_totpart * sizeof(ParticleData), "ParticleData array");
+                       nkey = new_keys = MEM_callocN(new_totpart * sizeof(ParticleEditKey *), "ParticleEditKey array");
+               }
+
+               pa = psys->particles;
+               key = edit->keys;
+               for(i=0; i<psys->totpart; i++, pa++, key++) {
+                       if(pa->flag & PARS_TAG) {
+                               if(*key)
+                                       MEM_freeN(*key);
+                               if(pa->hair)
+                                       MEM_freeN(pa->hair);
+                       }
+                       else {
+                               memcpy(npa, pa, sizeof(ParticleData));
+                               memcpy(nkey, key, sizeof(ParticleEditKey*));
+                               npa++;
+                               nkey++;
+                       }
+               }
+
+               if(psys->particles) MEM_freeN(psys->particles);
+               psys->particles = new_pars;
+
+               if(edit->keys) MEM_freeN(edit->keys);
+               edit->keys = new_keys;
+
+               if(edit->mirror_cache) {
+                       MEM_freeN(edit->mirror_cache);
+                       edit->mirror_cache = NULL;
+               }
+
+               psys->totpart = new_totpart;
+
+               edit->totkeys = psys_count_keys(psys);
+       }
+
+       return removed;
+}
+
+static void remove_tagged_keys(Scene *scene, Object *ob, ParticleSystem *psys)
+{
+       ParticleEdit *edit = psys->edit;
+       ParticleEditSettings *pset = PE_settings(scene);
+       ParticleData *pa;
+       HairKey *key, *nkey, *new_keys=0;
+       ParticleEditKey *ekey;
+       ParticleSystemModifierData *psmd;
+       int i, k, totpart = psys->totpart;
+       short new_totkey;
+
+       if(pset->flag & PE_X_MIRROR) {
+               /* mirror key tags */
+               psmd = psys_get_modifier(ob, psys);
+
+               LOOP_PARTICLES(i,pa) {
+                       LOOP_KEYS(k,ekey) {
+                               if(ekey->flag & PEK_TAG) {
+                                       PE_mirror_particle(ob, psmd->dm, psys, pa, NULL);
+                                       break;
+                               }
+                       }
+               }
+       }
+
+       LOOP_PARTICLES(i,pa) {
+               new_totkey = pa->totkey;
+               LOOP_KEYS(k,ekey) {
+                       if(ekey->flag & PEK_TAG)
+                               new_totkey--;
+               }
+               /* we can't have elements with less than two keys*/
+               if(new_totkey < 2)
+                       pa->flag |= PARS_TAG;
+       }
+       remove_tagged_elements(scene, ob, psys);
+
+       totpart = psys->totpart;
+
+       LOOP_PARTICLES(i,pa) {
+               new_totkey = pa->totkey;
+               LOOP_KEYS(k,ekey) {
+                       if(ekey->flag & PEK_TAG)
+                               new_totkey--;
+               }
+               if(new_totkey != pa->totkey) {
+                       key = pa->hair;
+                       nkey = new_keys = MEM_callocN(new_totkey*sizeof(HairKey), "HairKeys");
+
+                       for(k=0, ekey=edit->keys[i]; k<new_totkey; k++, key++, nkey++, ekey++) {
+                               while(ekey->flag & PEK_TAG && key < pa->hair + pa->totkey) {
+                                       key++;
+                                       ekey++;
+                               }
+
+                               if(key < pa->hair + pa->totkey) {
+                                       VECCOPY(nkey->co, key->co);
+                                       nkey->time = key->time;
+                                       nkey->weight = key->weight;
+                               }
+                       }
+                       if(pa->hair)
+                               MEM_freeN(pa->hair);
+                       
+                       pa->hair = new_keys;
+
+                       pa->totkey=new_totkey;
+
+                       if(edit->keys[i])
+                               MEM_freeN(edit->keys[i]);
+                       ekey = edit->keys[i] = MEM_callocN(new_totkey*sizeof(ParticleEditKey), "particle edit keys");
+
+                       for(k=0, key=pa->hair; k<pa->totkey; k++, key++, ekey++) {
+                               ekey->co = key->co;
+                               ekey->time = &key->time;
+                       }
+               }
+       }
+
+       edit->totkeys = psys_count_keys(psys);
+}
+/* works like normal edit mode subdivide, inserts keys between neighbouring selected keys */
+static void subdivide_element(ParticleSystem *psys, int index, void *userData)
+{
+       struct {Scene *scene; Object *ob; } *data = userData;
+       ParticleEdit *edit = psys->edit;
+       ParticleData *pa = psys->particles + index;
+       
+       ParticleKey state;
+       HairKey *key, *nkey, *new_keys;
+       ParticleEditKey *ekey, *nekey, *new_ekeys;
+
+       int k;
+       short totnewkey=0;
+       float endtime;
+
+       for(k=0, ekey=edit->keys[index]; k<pa->totkey-1; k++,ekey++){
+               if(ekey->flag&PEK_SELECT && (ekey+1)->flag&PEK_SELECT)
+                       totnewkey++;
+       }
+
+       if(totnewkey==0) return;
+
+       pa->flag |= PARS_REKEY;
+
+       nkey = new_keys = MEM_callocN((pa->totkey+totnewkey)*(sizeof(HairKey)),"Hair subdivide keys");
+       nekey = new_ekeys = MEM_callocN((pa->totkey+totnewkey)*(sizeof(ParticleEditKey)),"Hair subdivide edit keys");
+       endtime = pa->hair[pa->totkey-1].time;
+
+       for(k=0, key=pa->hair, ekey=edit->keys[index]; k<pa->totkey-1; k++, key++, ekey++){
+
+               memcpy(nkey,key,sizeof(HairKey));
+               memcpy(nekey,ekey,sizeof(ParticleEditKey));
+
+               nekey->co = nkey->co;
+               nekey->time = &nkey->time;
+
+               nkey++;
+               nekey++;
+
+               if(ekey->flag & PEK_SELECT && (ekey+1)->flag & PEK_SELECT){
+                       nkey->time= (key->time + (key+1)->time)*0.5f;
+                       state.time = (endtime != 0.0f)? nkey->time/endtime: 0.0f;
+                       psys_get_particle_on_path(data->scene, data->ob, psys, index, &state, 0);
+                       VECCOPY(nkey->co, state.co);
+
+                       nekey->co= nkey->co;
+                       nekey->time= &nkey->time;
+                       nekey->flag |= PEK_SELECT;
+
+                       nekey++;
+                       nkey++;
+               }
+       }
+       /*tip still not copied*/
+       memcpy(nkey,key,sizeof(HairKey));
+       memcpy(nekey,ekey,sizeof(ParticleEditKey));
+
+       nekey->co = nkey->co;
+       nekey->time = &nkey->time;
+
+       if(pa->hair)
+               MEM_freeN(pa->hair);
+       pa->hair = new_keys;
+
+       if(edit->keys[index])
+               MEM_freeN(edit->keys[index]);
+
+       edit->keys[index] = new_ekeys;
+
+       pa->totkey += totnewkey;
+       pa->flag |= PARS_EDIT_RECALC;
+       pa->flag &= ~PARS_REKEY;
+}
+
+void PE_subdivide(Object *ob)
+{
+       ParticleSystem *psys = PE_get_current(ob);
+       Scene *scene= NULL;
+       struct {Scene *scene; Object *ob; } data;
+
+       if(!PE_can_edit(psys)) return;
+
+       data.scene= scene;
+       data.ob= ob;
+       PE_foreach_element(psys,subdivide_element,&data);
+       
+       psys->edit->totkeys = psys_count_keys(psys);
+       
+       recalc_lengths(psys);
+       PE_recalc_world_cos(ob, psys);
+
+       PE_update_object(scene, ob, 1);
+       
+       BIF_undo_push("Subdivide hair(s)");
+}
+
+void PE_remove_doubles()
+{
+       Scene *scene= NULL; // XXX
+       Object *ob=OBACT;
+       ParticleSystem *psys=PE_get_current(ob);
+       ParticleEditSettings *pset=PE_settings(scene);
+       ParticleData *pa;
+       ParticleEdit *edit;
+       ParticleSystemModifierData *psmd;
+       KDTree *tree;
+       KDTreeNearest nearest[10];
+       float mat[4][4], co[3];
+       int i, n, totn, removed, totpart, flag, totremoved;
+
+       if(!PE_can_edit(psys)) return;
+
+       edit= psys->edit;
+       psmd= psys_get_modifier(ob, psys);
+       totremoved= 0;
+
+       do {
+               removed= 0;
+
+               totpart= psys->totpart;
+               tree=BLI_kdtree_new(totpart);
+                       
+               /* insert particles into kd tree */
+               LOOP_PARTICLES(i,pa) {
+                       if(particle_is_selected(psys, pa)) {
+                               psys_mat_hair_to_object(ob, psmd->dm, psys->part->from, pa, mat);
+                               VECCOPY(co, pa->hair[0].co);
+                               Mat4MulVecfl(mat, co);
+                               BLI_kdtree_insert(tree, i, co, NULL);
+                       }
+               }
+
+               BLI_kdtree_balance(tree);
+
+               /* tag particles to be removed */
+               LOOP_PARTICLES(i,pa) {
+                       if(particle_is_selected(psys, pa)) {
+                               psys_mat_hair_to_object(ob, psmd->dm, psys->part->from, pa, mat);
+                               VECCOPY(co, pa->hair[0].co);
+                               Mat4MulVecfl(mat, co);
+
+                               totn= BLI_kdtree_find_n_nearest(tree,10,co,NULL,nearest);
+
+                               for(n=0; n<totn; n++) {
+                                       /* this needs a custom threshold still */
+                                       if(nearest[n].index > i && nearest[n].dist < 0.0002f) {
+                                               if(!(pa->flag & PARS_TAG)) {
+                                                       pa->flag |= PARS_TAG;
+                                                       removed++;
+                                               }
+                                       }
+                               }
+                       }
+               }
+
+               BLI_kdtree_free(tree);
+
+               /* remove tagged particles - don't do mirror here! */
+               flag= pset->flag;
+               pset->flag &= ~PE_X_MIRROR;
+               remove_tagged_elements(scene, ob, psys);
+               pset->flag= flag;
+               totremoved += removed;
+       } while(removed);
+
+//     if(totremoved)
+// XXX         notice("Removed: %d", totremoved);
+
+       PE_recalc_world_cos(ob, psys);
+       DAG_object_flush_update(scene, ob, OB_RECALC_DATA);
+       BIF_undo_push("Remove double particles");
+}
+
+/* XXX static */
+void PE_radialcontrol_callback(const int mode, const int val)
+{
+       ParticleEditSettings *pset = NULL; // XXX PE_settings(scene);
+
+       if(pset->brushtype>=0) {
+               ParticleBrushData *brush= &pset->brush[pset->brushtype];
+
+               if(mode == RADIALCONTROL_SIZE)
+                       brush->size = val;
+               else if(mode == RADIALCONTROL_STRENGTH)
+                       brush->strength = val;
+       }
+
+       (*PE_radialcontrol()) = NULL;
+}
+
+struct RadialControl **PE_radialcontrol(void)
+{
+       static struct RadialControl *rc = NULL;
+       return &rc;
+}
+
+void PE_radialcontrol_start(const int mode)
+{
+       ParticleEditSettings *pset = NULL; // XXX PE_settings(scene);
+       int orig= 1;
+
+       if(pset->brushtype>=0) {
+               ParticleBrushData *brush= &pset->brush[pset->brushtype];
+               
+               if(mode == RADIALCONTROL_SIZE)
+                       orig = brush->size;
+               else if(mode == RADIALCONTROL_STRENGTH)
+                       orig = brush->strength;
+               
+//             if(mode != RADIALCONTROL_NONE)
+//                     (*PE_radialcontrol())= radialcontrol_start(mode, PE_radialcontrol_callback, orig, 100, 0);
+       }
+}
+
+/************************************************/
+/*                     Edit Brushes                                            */
+/************************************************/
+static void brush_comb(ParticleSystem *psys, float mat[][4], float imat[][4], int pa_index, int key_index, void *userData)
+{
+       struct {Scene *scene; Object *ob; short *mval; float rad; rcti* rect; float dist; float *dvec; float combfac;} *data = userData;
+       ParticleData *pa= &psys->particles[pa_index];
+       ParticleEditSettings *pset= PE_settings(data->scene);
+       HairKey *key = pa->hair + key_index;
+       float cvec[3], fac;
+
+       if(pset->flag & PE_LOCK_FIRST && key_index == 0) return;
+
+       fac = (float)pow((double)(1.0f - data->dist / data->rad), (double)data->combfac);
+
+       VECCOPY(cvec,data->dvec);
+       Mat4Mul3Vecfl(imat,cvec);
+       VecMulf(cvec, fac);
+       VECADD(key->co, key->co, cvec);
+
+       pa->flag |= PARS_EDIT_RECALC;
+}
+
+static void brush_cut(ParticleSystem *psys, int index, void *userData)
+{
+       struct {Scene *scene; short *mval; float rad; rcti* rect; int selected; float cutfac; bglMats mats;} *data = userData;
+       ARegion *ar= NULL; // XXX
+       Object *ob= NULL; // XXX
+       ParticleData *pa= &psys->particles[index];
+       ParticleCacheKey *key = psys->pathcache[index];
+       float rad2, cut_time = 1.0;
+       float x0, x1, v0, v1, o0, o1, xo0, xo1, d, dv;
+       int k, cut, keys = (int)pow(2.0, (double)psys->part->draw_step);
+       short vertco[2];
+
+       /* blunt scissors */
+       if(BLI_frand() > data->cutfac) return;
+
+       rad2 = data->rad * data->rad;
+
+       cut=0;
+
+       project_short_noclip(ar, key->co, vertco);
+       x0 = (float)vertco[0];
+       x1 = (float)vertco[1];
+
+       o0 = (float)data->mval[0];
+       o1 = (float)data->mval[1];
+       
+       xo0 = x0 - o0;
+       xo1 = x1 - o1;
+
+       /* check if root is inside circle */
+       if(xo0*xo0 + xo1*xo1 < rad2 && test_key_depth(key->co,&(data->mats))) {
+               cut_time = -1.0f;
+               cut = 1;
+       }
+       else {
+               /* calculate path time closest to root that was inside the circle */
+               for(k=1, key++; k<=keys; k++, key++){
+                       project_short_noclip(ar, key->co, vertco);
+
+                       if(test_key_depth(key->co,&(data->mats)) == 0) {
+                               x0 = (float)vertco[0];
+                               x1 = (float)vertco[1];
+
+                               xo0 = x0 - o0;
+                               xo1 = x1 - o1;
+                               continue;
+                       }
+
+                       v0 = (float)vertco[0] - x0;
+                       v1 = (float)vertco[1] - x1;
+
+                       dv = v0*v0 + v1*v1;
+
+                       d = (v0*xo1 - v1*xo0);
+                       
+                       d = dv * rad2 - d*d;
+
+                       if(d > 0.0f) {
+                               d = sqrt(d);
+
+                               cut_time = -(v0*xo0 + v1*xo1 + d);
+
+                               if(cut_time > 0.0f) {
+                                       cut_time /= dv;
+
+                                       if(cut_time < 1.0f) {
+                                               cut_time += (float)(k-1);
+                                               cut_time /= (float)keys;
+                                               cut = 1;
+                                               break;
+                                       }
+                               }
+                       }
+
+                       x0 = (float)vertco[0];
+                       x1 = (float)vertco[1];
+
+                       xo0 = x0 - o0;
+                       xo1 = x1 - o1;
+               }
+       }
+
+       if(cut) {
+               if(cut_time < 0.0f) {
+                       pa->flag |= PARS_TAG;
+               }
+               else {
+                       rekey_element_to_time(ob, index, cut_time);
+                       pa->flag |= PARS_EDIT_RECALC;
+               }
+       }
+}
+
+static void brush_length(ParticleSystem *psys, int index, void *userData)
+{
+       struct {Scene *scene; short *mval; float rad; rcti* rect; float dist; float growfac; } *data = userData;
+       ParticleData *pa = &psys->particles[index];
+       HairKey *key;
+       float dvec[3],pvec[3];
+       int k;
+
+       key = pa->hair;
+       VECCOPY(pvec,key->co);
+
+       for(k=1, key++; k<pa->totkey; k++,key++){
+               VECSUB(dvec,key->co,pvec);
+               VECCOPY(pvec,key->co);
+               VecMulf(dvec,data->growfac);
+               VECADD(key->co,(key-1)->co,dvec);
+       }
+
+       pa->flag |= PARS_EDIT_RECALC;
+}
+
+static void brush_puff(ParticleSystem *psys, int index, void *userData)
+{
+       struct {Scene *scene; short *mval; float rad; rcti* rect; float dist;
+               Object *ob; DerivedMesh *dm; float pufffac; int invert; } *data = userData;
+       ParticleData *pa = &psys->particles[index];
+       ParticleEdit *edit = psys->edit;
+       HairKey *key;
+       float mat[4][4], imat[4][4];
+       float lastco[3], rootco[3], co[3], nor[3], kco[3], dco[3], fac, length;
+       int k;
+
+       psys_mat_hair_to_global(data->ob, data->dm, psys->part->from, pa, mat);
+       Mat4Invert(imat,mat);
+
+       /* find root coordinate and normal on emitter */
+       key = pa->hair;
+       VECCOPY(co, key->co);
+       Mat4MulVecfl(mat, co);
+
+       index= BLI_kdtree_find_nearest(edit->emitter_field, co, NULL, NULL);
+       if(index == -1) return;
+
+       VECCOPY(rootco, co);
+       VecCopyf(nor, &psys->edit->emitter_cosnos[index*6+3]);
+       Normalize(nor);
+       length= 0.0f;
+
+       fac= (float)pow((double)(1.0f - data->dist / data->rad), (double)data->pufffac);
+       fac *= 0.025f;
+       if(data->invert)
+               fac= -fac;
+
+       for(k=1, key++; k<pa->totkey; k++, key++){
+               /* compute position as if hair was standing up straight */
+               VECCOPY(lastco, co);
+               VECCOPY(co, key->co);
+               Mat4MulVecfl(mat, co);
+               length += VecLenf(lastco, co);
+
+               VECADDFAC(kco, rootco, nor, length);
+
+               /* blend between the current and straight position */
+               VECSUB(dco, kco, co);
+               VECADDFAC(co, co, dco, fac);
+
+               VECCOPY(key->co, co);
+               Mat4MulVecfl(imat, key->co);
+       }
+
+       pa->flag |= PARS_EDIT_RECALC;
+}
+
+static void brush_smooth_get(ParticleSystem *psys, float mat[][4], float imat[][4], int pa_index, int key_index, void *userData)
+{
+       struct {Scene *scene; Object *ob; short *mval; float rad; rcti* rect; float dist; float vec[3]; int tot; float smoothfac;} *data = userData;
+       ParticleData *pa= &psys->particles[pa_index];
+       HairKey *key = pa->hair + key_index;
+       
+       if(key_index){
+               float dvec[3];
+
+               VecSubf(dvec,key->co,(key-1)->co);
+               Mat4Mul3Vecfl(mat,dvec);
+               VECADD(data->vec,data->vec,dvec);
+               data->tot++;
+       }
+}
+
+static void brush_smooth_do(ParticleSystem *psys, float mat[][4], float imat[][4], int pa_index, int key_index, void *userData)
+{
+       struct {Scene *scene; Object *ob; short *mval; float rad; rcti* rect; float dist; float vec[3]; int tot; float smoothfac;} *data = userData;
+       ParticleData *pa= &psys->particles[pa_index];
+       HairKey *key = pa->hair + key_index;
+       float vec[3], dvec[3];
+       
+       if(key_index){
+               VECCOPY(vec,data->vec);
+               Mat4Mul3Vecfl(imat,vec);
+
+               VecSubf(dvec,key->co,(key-1)->co);
+
+               VECSUB(dvec,vec,dvec);
+               VecMulf(dvec,data->smoothfac);
+               
+               VECADD(key->co,key->co,dvec);
+       }
+
+       pa->flag |= PARS_EDIT_RECALC;
+}
+
+#define EXPERIMENTAL_DEFORM_ONLY_PAINTING 1
+static void brush_add(Scene *scene, Object *ob, ParticleSystem *psys, short *mval, short number)
+{
+       ParticleData *add_pars = MEM_callocN(number*sizeof(ParticleData),"ParticleData add");
+       ParticleSystemModifierData *psmd = psys_get_modifier(ob,psys);
+       ParticleEditSettings *pset= PE_settings(scene);
+       ARegion *ar= NULL; // XXX
+       View3D *v3d= NULL; // XXX
+       ParticleEdit *edit = psys->edit;
+       int i, k, n = 0, totpart = psys->totpart;
+       short mco[2];
+       short dmx = 0, dmy = 0;
+       float co1[3], co2[3], min_d, imat[4][4];
+       float framestep, timestep = psys_get_timestep(psys->part);
+       short size = pset->brush[PE_BRUSH_ADD].size;
+       short size2 = size*size;
+#if EXPERIMENTAL_DEFORM_ONLY_PAINTING
+       DerivedMesh *dm=0;
+#endif
+       Mat4Invert(imat,ob->obmat);
+
+       BLI_srandom(psys->seed+mval[0]+mval[1]);
+       
+       /* painting onto the deformed mesh, could be an option? */
+#if EXPERIMENTAL_DEFORM_ONLY_PAINTING
+       if (psmd->dm->deformedOnly)
+               dm = psmd->dm;
+       else
+               dm = mesh_get_derived_deform(scene, ob, CD_MASK_BAREMESH);
+#endif
+       for(i=0; i<number; i++){
+               if(number>1){
+                       dmx=dmy=size;
+                       while(dmx*dmx+dmy*dmy>size2){
+                               dmx=(short)((2.0f*BLI_frand()-1.0f)*size);
+                               dmy=(short)((2.0f*BLI_frand()-1.0f)*size);
+                       }
+               }
+
+               mco[0] = mval[0] + dmx;
+               mco[1] = mval[1] + dmy;
+               viewline(ar, v3d, mco, co1, co2);
+
+               Mat4MulVecfl(imat,co1);
+               Mat4MulVecfl(imat,co2);
+               min_d=2.0;
+               
+               /* warning, returns the derived mesh face */
+#if EXPERIMENTAL_DEFORM_ONLY_PAINTING
+               if(psys_intersect_dm(scene, ob,dm,0,co1,co2,&min_d,&add_pars[n].num,add_pars[n].fuv,0,0,0,0)) {
+                       add_pars[n].num_dmcache= psys_particle_dm_face_lookup(ob,psmd->dm,add_pars[n].num,add_pars[n].fuv,NULL);
+                       n++;
+               }
+#else
+#if 0
+               if (psmd->dm->deformedOnly) {
+                       if(psys_intersect_dm(scene, ob,psmd->dm,0,co1,co2,&min_d,&add_pars[n].num,add_pars[n].fuv,0,0,0,0)){
+                               n++;
+                       }
+               } else {
+                       /* we need to test against the cage mesh, because 1) its faster and 2) then we can avoid converting the fuv back which is not simple */
+                       if(psys_intersect_dm(scene, ob,psmd->dm,0,co1,co2,&min_d,&add_pars[n].num,add_pars[n].fuv,0,0,0,0)){
+                               MFace *mface;
+                               float fuv_mod[3] = {0.0, 0.0, 0.0};
+                               OrigSpaceFace *osface;
+                               
+                               mface= psmd->dm->getFaceData(psmd->dm,add_pars[n].num,CD_MFACE);
+                               osface= psmd->dm->getFaceData(psmd->dm, add_pars[n].num, CD_ORIGSPACE);
+                               
+                               add_pars[n].fuv[2]=0.0;
+                               
+                               /* use the original index for num and the derived index for num_dmcache */
+                               add_pars[n].num_dmcache = add_pars[n].num;
+                               add_pars[n].num = *(int *)psmd->dm->getFaceData(psmd->dm, add_pars[n].num, CD_ORIGINDEX);
+                               
+                               /* This is totally unaceptable code (fakeing mesh dara) but changing the target function isnt really nice either, do this temporarily */
+                               if (1) { /* Evilness*/
+                                       MFace mface_fake;
+                                       MVert mvert_fake[4];
+                                       //int test1,test2;
+                                       //test1 = add_pars[n].num_dmcache;
+                                       //test2 = add_pars[n].num;
+                                       
+                                       mvert_fake[0].co[2] = mvert_fake[1].co[2] = mvert_fake[2].co[2] = mvert_fake[3].co[2] = 0.0;
+                                       
+                                       mface_fake.v1 = 0;
+                                       mface_fake.v2 = 1;
+                                       mface_fake.v3 = 2;
+                                       
+                                       if (mface->v4) {
+                                               mface_fake.v4 = 3;
+                                       } else {
+                                               mface_fake.v4 = 0;
+                                       }
+                                       
+                                       Vec2Copyf(mvert_fake[0].co, osface->uv[0]);
+                                       Vec2Copyf(mvert_fake[1].co, osface->uv[1]);
+                                       Vec2Copyf(mvert_fake[2].co, osface->uv[2]);
+                                       Vec2Copyf(mvert_fake[3].co, osface->uv[3]);
+                                       //printf("before %f %f %i %i\n", add_pars[n].fuv[0], add_pars[n].fuv[1], test1, test2);
+                                       psys_interpolate_face(&mvert_fake, &mface_fake, NULL, &add_pars[n].fuv, &fuv_mod, NULL, NULL, NULL);
+                                       
+                                       /* Apply as the UV */
+                                       Vec2Copyf(add_pars[n].fuv, fuv_mod);
+                                       //printf("after %f %f\n", add_pars[n].fuv[0], add_pars[n].fuv[1]);
+                               }
+                               /* Make a fake face, for calculating the derived face's fuv on the original face */
+                               //PointInFace2DUV(mface->v4, osface->uv[0], osface->uv[1], osface->uv[2], osface->uv[3], add_pars[n].fuv, fuv_mod);
+                               //Vec2Copyf(add_pars[n].fuv, fuv_mod);
+                               
+                               n++;
+                       }
+               }
+#endif
+#endif
+       }
+       if(n){
+               int newtotpart=totpart+n;
+               float hairmat[4][4], cur_co[3];
+               KDTree *tree=0;
+               ParticleData *pa, *new_pars = MEM_callocN(newtotpart*sizeof(ParticleData),"ParticleData new");
+               ParticleEditKey *ekey, **key, **new_keys = MEM_callocN(newtotpart*sizeof(ParticleEditKey *),"ParticleEditKey array new");
+               HairKey *hkey;
+
+               /* save existing elements */
+               memcpy(new_pars, psys->particles, totpart * sizeof(ParticleData));
+               memcpy(new_keys, edit->keys, totpart * sizeof(ParticleEditKey*));
+
+               /* change old arrays to new ones */
+               if(psys->particles) MEM_freeN(psys->particles);
+               psys->particles = new_pars;
+
+               if(edit->keys) MEM_freeN(edit->keys);
+               edit->keys = new_keys;
+
+               if(edit->mirror_cache) {
+                       MEM_freeN(edit->mirror_cache);
+                       edit->mirror_cache = NULL;
+               }
+
+               /* create tree for interpolation */
+               if(pset->flag & PE_INTERPOLATE_ADDED && psys->totpart){
+                       tree=BLI_kdtree_new(psys->totpart);
+                       
+                       for(i=0, pa=psys->particles; i<totpart; i++, pa++) {
+                               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);
+                               BLI_kdtree_insert(tree, i, cur_co, NULL);
+                       }
+
+                       BLI_kdtree_balance(tree);
+               }
+
+               psys->totpart = newtotpart;
+
+               /* create new elements */
+               pa = psys->particles + totpart;
+               key = edit->keys + totpart;
+
+               for(i=totpart; i<newtotpart; i++, pa++, key++){
+                       memcpy(pa, add_pars + i - totpart, sizeof(ParticleData));
+                       pa->hair = MEM_callocN(pset->totaddkey * sizeof(HairKey), "BakeKey key add");
+                       ekey = *key = MEM_callocN(pset->totaddkey * sizeof(ParticleEditKey), "ParticleEditKey add");
+                       pa->totkey = pset->totaddkey;
+
+                       for(k=0, hkey=pa->hair; k<pa->totkey; k++, hkey++, ekey++) {
+                               ekey->co = hkey->co;
+                               ekey->time = &hkey->time;
+                       }
+                       
+                       pa->size= 1.0f;
+                       initialize_particle(pa,i,ob,psys,psmd);
+                       reset_particle(scene, pa,psys,psmd,ob,0.0,1.0,0,0,0);
+                       pa->flag |= PARS_EDIT_RECALC;
+                       if(pset->flag & PE_X_MIRROR)
+                               pa->flag |= PARS_TAG; /* signal for duplicate */
+                       
+                       framestep = pa->lifetime/(float)(pset->totaddkey-1);
+
+                       if(tree){
+                               HairKey *hkey;
+                               ParticleKey key[3];
+                               KDTreeNearest ptn[3];
+                               int w, maxw;
+                               float maxd, mind, dd, totw=0.0, weight[3];
+
+                               psys_particle_on_dm(psmd->dm,psys->part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co1,0,0,0,0,0);
+                               maxw = BLI_kdtree_find_n_nearest(tree,3,co1,NULL,ptn);
+
+                               maxd = ptn[maxw-1].dist;
+                               mind = ptn[0].dist;
+                               dd = maxd - mind;
+                               
+                               for(w=0; w<maxw; w++){
+                                       weight[w] = (float)pow(2.0, (double)(-6.0f * ptn[w].dist / maxd));
+                                       totw += weight[w];
+                               }
+                               for(;w<3; w++){
+                                       weight[w] = 0.0f;
+                               }
+
+                               for(w=0; w<maxw; w++)
+                                       weight[w] /= totw;
+
+                               for(k=0; k<pset->totaddkey; k++) {
+                                       hkey = pa->hair + k;
+                                       hkey->time = pa->time + k * framestep;
+
+                                       key[0].time = hkey->time/ 100.0f;
+                                       psys_get_particle_on_path(scene, ob, psys, ptn[0].index, key, 0);
+                                       VecMulf(key[0].co, weight[0]);
+                                       
+                                       if(maxw>1) {
+                                               key[1].time = key[0].time;
+                                               psys_get_particle_on_path(scene, ob, psys, ptn[1].index, key + 1, 0);
+                                               VecMulf(key[1].co, weight[1]);
+                                               VECADD(key[0].co, key[0].co, key[1].co);
+
+                                               if(maxw>2) {                                            
+                                                       key[2].time = key[0].time;
+                                                       psys_get_particle_on_path(scene, ob, psys, ptn[2].index, key + 2, 0);
+                                                       VecMulf(key[2].co, weight[2]);
+                                                       VECADD(key[0].co, key[0].co, key[2].co);
+                                               }
+                                       }
+
+                                       if(k==0)
+                                               VECSUB(co1, pa->state.co, key[0].co);
+
+                                       VECADD(pa->hair[k].co, key[0].co, co1);
+
+                                       pa->hair[k].time = key[0].time;
+                               }
+                       }
+                       else{
+                               for(k=0, hkey=pa->hair; k<pset->totaddkey; k++, hkey++) {
+                                       VECADDFAC(hkey->co, pa->state.co, pa->state.vel, k * framestep * timestep);
+                                       pa->hair[k].time += k * framestep;
+                               }
+                       }
+                       for(k=0, hkey=pa->hair; k<pset->totaddkey; k++, hkey++) {
+                               psys_mat_hair_to_global(ob, psmd->dm, psys->part->from, pa, hairmat);
+                               Mat4Invert(imat,hairmat);
+                               Mat4MulVecfl(imat, hkey->co);
+                       }
+               }
+               edit->totkeys = psys_count_keys(psys);
+
+               if(tree)
+                       BLI_kdtree_free(tree);
+       }
+       if(add_pars)
+               MEM_freeN(add_pars);
+       
+/* painting onto the deformed mesh, could be an option? */
+#if EXPERIMENTAL_DEFORM_ONLY_PAINTING
+       if (!psmd->dm->deformedOnly)
+               dm->release(dm);
+#endif
+}
+static void brush_weight(ParticleSystem *psys, float mat[][4], float imat[][4], int pa_index, int key_index, void *userData)
+{
+       struct {Scene *scene; Object *ob; short *mval; float rad; rcti* rect; float dist; float weightfac;} *data = userData;
+       ParticleData *pa;
+
+       /* roots have full weight allways */
+       if(key_index) {
+               pa= &psys->particles[pa_index];
+               pa->hair[key_index].weight = data->weightfac;
+               pa->flag |= PARS_EDIT_RECALC;
+       }
+}
+
+/* returns 0 if no brush was used */
+int PE_brush_particles(void)
+{
+       Scene *scene= NULL; // XXX
+       ARegion *ar= NULL; // XXX
+       Object *ob = OBACT;
+       ParticleSystem *psys = PE_get_current(ob);
+       ParticleEdit *edit;
+       ParticleEditSettings *pset = PE_settings(scene);
+       ParticleSystemModifierData *psmd;
+       ParticleBrushData *brush;
+       float vec1[3], vec2[3];
+       short mval[2], mvalo[2], firsttime = 1, dx, dy;
+       int selected = 0, flip, removed = 0;
+
+       if(!PE_can_edit(psys)) return 0;
+
+       edit = psys->edit;
+       psmd= psys_get_modifier(ob, psys);
+
+// XXX flip= (get_qual() == LR_SHIFTKEY);
+
+       if(pset->brushtype<0) return 0;
+       brush= &pset->brush[pset->brushtype];
+
+       initgrabz(ar->regiondata, ob->obmat[3][0], ob->obmat[3][1], ob->obmat[3][2]);
+
+//     getmouseco_areawin(mvalo);
+
+       mval[0] = mvalo[0]; mval[1] = mvalo[1];
+
+       while(0){ // XXX get_mbut
+               bglFlush();
+               glReadBuffer(GL_BACK);
+               glDrawBuffer(GL_BACK);
+//             persp(PERSP_VIEW);
+
+               dx=mval[0]-mvalo[0];
+               dy=mval[1]-mvalo[1];
+               if(((pset->brushtype == PE_BRUSH_ADD) ?
+                       (sqrt(dx * dx + dy * dy) > pset->brush[PE_BRUSH_ADD].step) : (dx != 0 || dy != 0))
+                       || firsttime){
+                       firsttime = 0;
+
+                       selected = (short)count_selected_keys(scene, psys);
+
+                       switch(pset->brushtype){
+                               case PE_BRUSH_COMB:
+                               {
+                                       struct {Scene *scene; Object *ob; short *mval; float rad; rcti* rect; float dist; float *dvec; float combfac;} data;
+
+                                       data.scene = scene;
+                                       data.ob = ob;
+                                       data.mval = mval;
+                                       data.rad = (float)brush->size;
+
+                                       data.combfac = (float)(brush->strength - 50) / 50.0f;
+                                       if(data.combfac < 0.0f)
+                                               data.combfac = 1.0f - 9.0f * data.combfac;
+                                       else
+                                               data.combfac = 1.0f - data.combfac;
+
+                                       Mat4Invert(ob->imat, ob->obmat);
+
+                                       window_to_3d(ar, vec1, mvalo[0], mvalo[1]);
+                                       window_to_3d(ar, vec2, mval[0], mval[1]);
+                                       VECSUB(vec1, vec2, vec1);
+                                       data.dvec = vec1;
+
+                                       foreach_mouse_hit_key(selected, psys,brush_comb, &data);
+                                       break;
+                               }
+                               case PE_BRUSH_CUT:
+                               {
+                                       struct {Scene *scene; short *mval; float rad; rcti* rect; int selected; float cutfac; bglMats mats;} data;
+
+                                       data.scene = scene;
+                                       data.mval = mval;
+                                       data.rad = (float)brush->size;
+
+                                       data.selected = selected;
+
+                                       data.cutfac = (float)(brush->strength / 100.0f);
+
+                                       bgl_get_mats(&(data.mats));
+
+                                       if(selected)
+                                               foreach_selected_element(psys, brush_cut, &data);
+                                       else
+                                               PE_foreach_element(psys, brush_cut, &data);
+
+                                       removed= remove_tagged_elements(scene, ob, psys);
+                                       if(pset->flag & PE_KEEP_LENGTHS)
+                                               recalc_lengths(psys);
+                                       break;
+                               }
+                               case PE_BRUSH_LENGTH:
+                               {
+                                       struct {Scene *scene; short *mval; float rad; rcti* rect; float dist; float growfac; } data;
+                                       
+                                       data.scene= scene;
+                                       data.mval = mval;
+                                       
+                                       data.rad = (float)brush->size;
+                                       data.growfac = (float)brush->strength / 5000.0f;
+
+                                       if(brush->invert ^ flip)
+                                               data.growfac = 1.0f - data.growfac;
+                                       else
+                                               data.growfac = 1.0f + data.growfac;
+
+                                       foreach_mouse_hit_element(selected, psys, brush_length, &data);
+
+                                       if(pset->flag & PE_KEEP_LENGTHS)
+                                               recalc_lengths(psys);
+                                       break;
+                               }
+                               case PE_BRUSH_PUFF:
+                               {
+                                       struct {Scene *scene; short *mval; float rad; rcti* rect; float dist;
+                                               Object *ob; DerivedMesh *dm; float pufffac; int invert; } data;
+
+                                       data.scene= scene;
+                                       data.ob = ob;
+                                       data.dm = psmd->dm;
+                                       data.mval = mval;
+                                       data.rad = (float)brush->size;
+
+                                       data.pufffac = (float)(brush->strength - 50) / 50.0f;
+                                       if(data.pufffac < 0.0f)
+                                               data.pufffac = 1.0f - 9.0f * data.pufffac;
+                                       else
+                                               data.pufffac = 1.0f - data.pufffac;
+
+                                       data.invert= (brush->invert ^ flip);
+                                       Mat4Invert(ob->imat, ob->obmat);
+
+                                       foreach_mouse_hit_element(selected, psys, brush_puff, &data);
+                                       break;
+                               }
+                               case PE_BRUSH_ADD:
+                                       if(psys->part->from==PART_FROM_FACE){
+                                               brush_add(scene, ob, psys, mval, brush->strength);
+                                               if(pset->flag & PE_KEEP_LENGTHS)
+                                                       recalc_lengths(psys);
+                                       }
+                                       break;
+                               case PE_BRUSH_WEIGHT:
+                               {
+                                       struct {Scene *scene; Object *ob; short *mval; float rad; rcti* rect; float dist; float weightfac;} data;
+
+                                       data.scene = scene;
+                                       data.ob = ob;
+                                       data.mval = mval;
+                                       data.rad = (float)brush->size;
+
+                                       data.weightfac = (float)(brush->strength / 100.0f);
+
+                                       foreach_mouse_hit_key(selected, psys, brush_weight, &data);
+                                       break;
+                               }
+                               case PE_BRUSH_SMOOTH:
+                               {
+                                       struct {Scene *scene; Object *ob; short *mval; float rad; rcti* rect; float dist; float vec[3]; int tot; float smoothfac;} data;
+
+                                       data.scene = scene;
+                                       data.ob = ob;
+                                       data.mval = mval;
+                                       data.rad = (float)brush->size;
+
+                                       data.vec[0] = data.vec[1] = data.vec[2] = 0.0f;
+                                       data.tot = 0;
+
+                                       data.smoothfac = (float)(brush->strength / 100.0f);
+
+                                       Mat4Invert(ob->imat, ob->obmat);
+
+                                       foreach_mouse_hit_key(selected, psys, brush_smooth_get, &data);
+
+                                       if(data.tot){
+                                               VecMulf(data.vec, 1.0f / (float)data.tot);
+                                               foreach_mouse_hit_key(selected, psys, brush_smooth_do, &data);
+                                       }
+
+                                       break;
+                               }
+                       }
+                       if((pset->flag & PE_KEEP_LENGTHS)==0)
+                               recalc_lengths(psys);
+
+                       if(pset->brushtype == PE_BRUSH_ADD || removed) {
+                               if(pset->brushtype == PE_BRUSH_ADD && (pset->flag & PE_X_MIRROR))
+                                       PE_mirror_x(scene, 1);
+                               PE_recalc_world_cos(ob,psys);
+                               psys_free_path_cache(psys);
+                               DAG_object_flush_update(scene, ob, OB_RECALC_DATA);
+                       }
+                       else
+                               PE_update_object(scene, ob, 1);
+                       
+                       mvalo[0] = mval[0];
+                       mvalo[1] = mval[1];
+               }
+
+               PIL_sleep_ms(10);
+               
+//             getmouseco_areawin(mval);
+       }
+
+       BIF_undo_push("Brush edit particles");
+
+       return 1;
+}
+
+static void set_delete_particle(ParticleSystem *psys, int index, void *userData)
+{
+       psys->particles[index].flag |= PARS_TAG;
+}
+
+static void set_delete_particle_key(ParticleSystem *psys, int pa_index, int key_index, void *userData)
+{
+       psys->edit->keys[pa_index][key_index].flag |= PEK_TAG;
+}
+
+void PE_delete_particle(void)
+{
+       Scene *scene= NULL; // XXX
+       Object *ob=OBACT;
+       ParticleSystem *psys = PE_get_current(ob);
+       short event=0;
+
+       if(!PE_can_edit(psys)) return;
+
+       event= pupmenu("Erase %t|Particle%x2|Key%x1");
+
+       if(event<1) return;
+
+       if(event==1){
+               foreach_selected_key(psys, set_delete_particle_key, 0);
+               remove_tagged_keys(scene, ob, psys);
+               recalc_lengths(psys);
+       }
+       else if(event==2){
+               foreach_selected_element(psys, set_delete_particle, 0);
+               remove_tagged_elements(scene, ob, psys);
+               recalc_lengths(psys);
+       }
+
+       DAG_object_flush_update(scene, ob, OB_RECALC_DATA);
+       BIF_undo_push("Delete particles/keys");
+}
+
+void PE_mirror_x(Scene *scene, int tagged)
+{
+       Object *ob=OBACT;
+       Mesh *me= (Mesh*)(ob->data);
+       ParticleSystemModifierData *psmd;
+       ParticleSystem *psys = PE_get_current(ob);
+       ParticleEdit *edit;
+       ParticleData *pa, *newpa, *new_pars;
+       ParticleEditKey *ekey, **newkey, **key, **new_keys;
+       HairKey *hkey;
+       int *mirrorfaces;
+       int i, k, rotation, totpart, newtotpart;
+
+       if(!PE_can_edit(psys)) return;
+
+       edit= psys->edit;
+       psmd= psys_get_modifier(ob, psys);
+
+       mirrorfaces= mesh_get_x_mirror_faces(ob);
+
+       if(!edit->mirror_cache)
+               PE_update_mirror_cache(ob, psys);
+
+       totpart= psys->totpart;
+       newtotpart= psys->totpart;
+       LOOP_PARTICLES(i,pa) {
+               if(pa->flag&PARS_HIDE) continue;
+
+               if(!tagged) {
+                       if(particle_is_selected(psys, pa)) {
+                               if(edit->mirror_cache[i] != -1) {
+                                       /* already has a mirror, don't need to duplicate */
+                                       PE_mirror_particle(ob, psmd->dm, psys, pa, NULL);
+                                       continue;
+                               }
+                               else
+                                       pa->flag |= PARS_TAG;
+                       }
+               }
+
+               if((pa->flag & PARS_TAG) && mirrorfaces[pa->num*2] != -1)
+                       newtotpart++;
+       }
+
+       if(newtotpart != psys->totpart) {
+               /* allocate new arrays and copy existing */
+               new_pars= MEM_callocN(newtotpart*sizeof(ParticleData), "ParticleData new");
+               new_keys= MEM_callocN(newtotpart*sizeof(ParticleEditKey*), "ParticleEditKey new");
+
+               memcpy(new_pars, psys->particles, totpart*sizeof(ParticleData));
+               memcpy(new_keys, edit->keys, totpart*sizeof(ParticleEditKey*));
+
+               if(psys->particles) MEM_freeN(psys->particles);
+               psys->particles= new_pars;
+
+               if(edit->keys) MEM_freeN(edit->keys);
+               edit->keys= new_keys;
+
+               if(edit->mirror_cache) {
+                       MEM_freeN(edit->mirror_cache);
+                       edit->mirror_cache= NULL;
+               }
+
+               psys->totpart= newtotpart;
+                       
+               /* create new elements */
+               pa= psys->particles;
+               newpa= psys->particles + totpart;
+               key= edit->keys;
+               newkey= edit->keys + totpart;
+
+               for(i=0; i<totpart; i++, pa++, key++) {
+                       if(pa->flag&PARS_HIDE) continue;
+
+                       if(!(pa->flag & PARS_TAG) || mirrorfaces[pa->num*2] == -1)
+                               continue;
+
+                       /* duplicate */
+                       *newpa= *pa;
+                       if(pa->hair) newpa->hair= MEM_dupallocN(pa->hair);
+                       if(pa->keys) newpa->keys= MEM_dupallocN(pa->keys);
+                       if(*key) *newkey= MEM_dupallocN(*key);
+
+                       /* rotate weights according to vertex index rotation */
+                       rotation= mirrorfaces[pa->num*2+1];
+                       newpa->fuv[0]= pa->fuv[2];
+                       newpa->fuv[1]= pa->fuv[1];
+                       newpa->fuv[2]= pa->fuv[0];
+                       newpa->fuv[3]= pa->fuv[3];
+                       while(rotation-- > 0)
+                               if(me->mface[pa->num].v4)
+                                       SHIFT4(float, newpa->fuv[0], newpa->fuv[1], newpa->fuv[2], newpa->fuv[3])
+                               else
+                                       SHIFT3(float, newpa->fuv[0], newpa->fuv[1], newpa->fuv[2])
+
+                       /* assign face inddex */
+                       newpa->num= mirrorfaces[pa->num*2];
+                       newpa->num_dmcache= psys_particle_dm_face_lookup(ob,psmd->dm,newpa->num,newpa->fuv, NULL);
+
+                       /* update edit key pointers */
+                       ekey= *newkey;
+                       for(k=0, hkey=newpa->hair; k<newpa->totkey; k++, hkey++, ekey++) {
+                               ekey->co= hkey->co;
+                               ekey->time= &hkey->time;
+                       }
+
+                       /* map key positions as mirror over x axis */
+                       PE_mirror_particle(ob, psmd->dm, psys, pa, newpa);
+
+                       newpa++;
+                       newkey++;
+               }
+
+               edit->totkeys = psys_count_keys(psys);
+       }
+
+       for(pa=psys->particles, i=0; i<psys->totpart; i++, pa++)
+               pa->flag &= ~PARS_TAG;
+
+       MEM_freeN(mirrorfaces);
+
+       if(!tagged) {
+               PE_recalc_world_cos(ob,psys);
+               DAG_object_flush_update(scene, ob, OB_RECALC_DATA);
+               BIF_undo_push("Mirror particles");
+       }
+}
+
+void PE_selectbrush_menu(Scene *scene)
+{
+       ParticleEditSettings *pset= PE_settings(scene);
+       int val;
+       
+       // XXX pupmenu_set_active(pset->brushtype);
+       
+       val= pupmenu("Select Brush%t|None %x0|Comb %x1|Smooth %x7|Weight %x6|Add %x5|Length %x3|Puff %x4|Cut %x2");
+
+       if(val>=0) {
+               pset->brushtype= val-1;
+       }
+}
+
+/************************************************/
+/*                     Particle Edit Undo                                      */
+/************************************************/
+static void free_ParticleUndo(ParticleUndo *undo)
+{
+       ParticleData *pa;
+       int i;
+
+       for(i=0, pa=undo->particles; i<undo->totpart; i++, pa++) {
+               if(pa->hair)
+                       MEM_freeN(pa->hair);
+               if(undo->keys[i])
+                       MEM_freeN(undo->keys[i]);
+       }
+       if(undo->keys)
+               MEM_freeN(undo->keys);
+
+       if(undo->particles)
+               MEM_freeN(undo->particles);
+
+       //if(undo->emitter_cosnos)
+       //      MEM_freeN(undo->emitter_cosnos);
+}
+static void make_ParticleUndo(ParticleSystem *psys, ParticleUndo *undo)
+{
+       ParticleData *pa,*upa;
+       int i;
+
+       undo->totpart = psys->totpart;
+       undo->totkeys = psys->edit->totkeys;
+
+       upa = undo->particles = MEM_dupallocN(psys->particles);
+       undo->keys = MEM_dupallocN(psys->edit->keys);
+       
+       for(i=0, pa=psys->particles; i<undo->totpart; i++, pa++, upa++) {
+               upa->hair = MEM_dupallocN(pa->hair);
+               undo->keys[i] = MEM_dupallocN(psys->edit->keys[i]);
+               /* no need to update edit key->co & key->time pointers here */
+       }
+}
+static void get_ParticleUndo(ParticleSystem *psys, ParticleUndo *undo)
+{
+       ParticleData *pa, *upa;
+       ParticleEditKey *key;
+       HairKey *hkey;
+       int i, k, totpart = psys->totpart;
+
+       LOOP_PARTICLES(i,pa) {
+               if(pa->hair)
+                       MEM_freeN(pa->hair);
+
+               if(psys->edit->keys[i])
+                       MEM_freeN(psys->edit->keys[i]);
+       }
+       if(psys->particles)
+               MEM_freeN(psys->particles);
+       if(psys->edit->keys)
+               MEM_freeN(psys->edit->keys);
+       if(psys->edit->mirror_cache) {
+               MEM_freeN(psys->edit->mirror_cache);
+               psys->edit->mirror_cache= NULL;
+       }
+
+       pa = psys->particles = MEM_dupallocN(undo->particles);
+       psys->edit->keys = MEM_dupallocN(undo->keys);
+
+       for(i=0,upa=undo->particles; i<undo->totpart; i++, upa++, pa++){
+               hkey = pa->hair = MEM_dupallocN(upa->hair);
+               key = psys->edit->keys[i] = MEM_dupallocN(undo->keys[i]);
+               for(k=0; k<pa->totkey; k++, hkey++, key++) {
+                       key->co = hkey->co;
+                       key->time = &hkey->time;
+               }
+       }
+
+       psys->totpart = undo->totpart;
+       psys->edit->totkeys = undo->totkeys;
+}
+
+void PE_undo_push(Scene *scene, char *str)
+{
+       ParticleSystem *psys = PE_get_current(OBACT);
+       ParticleEdit *edit = 0;
+       ParticleUndo *undo;
+       int nr;
+
+       if(!PE_can_edit(psys)) return;
+       edit = psys->edit;
+
+       /* remove all undos after (also when curundo==NULL) */
+       while(edit->undo.last != edit->curundo) {
+               undo= edit->undo.last;
+               BLI_remlink(&edit->undo, undo);
+               free_ParticleUndo(undo);
+               MEM_freeN(undo);
+       }
+
+       /* make new */
+       edit->curundo= undo= MEM_callocN(sizeof(ParticleUndo), "particle undo file");
+       strncpy(undo->name, str, 64-1);
+       BLI_addtail(&edit->undo, undo);
+       
+       /* and limit amount to the maximum */
+       nr= 0;
+       undo= edit->undo.last;
+       while(undo) {
+               nr++;
+               if(nr==U.undosteps) break;
+               undo= undo->prev;
+       }
+       if(undo) {
+               while(edit->undo.first!=undo) {
+                       ParticleUndo *first= edit->undo.first;
+                       BLI_remlink(&edit->undo, first);
+                       free_ParticleUndo(first);
+                       MEM_freeN(first);
+               }
+       }
+
+       /* copy  */
+       make_ParticleUndo(psys,edit->curundo);
+}
+void PE_undo_step(Scene *scene, int step)
+{      
+       ParticleSystem *psys = PE_get_current(OBACT);
+       ParticleEdit *edit = 0;
+
+       if(!PE_can_edit(psys)) return;
+       edit=psys->edit;
+
+       if(step==0) {
+               get_ParticleUndo(psys,edit->curundo);
+       }
+       else if(step==1) {
+               
+               if(edit->curundo==NULL || edit->curundo->prev==NULL) error("No more steps to undo");
+               else {
+                       if(G.f & G_DEBUG) printf("undo %s\n", edit->curundo->name);
+                       edit->curundo= edit->curundo->prev;
+                       get_ParticleUndo(psys, edit->curundo);
+               }
+       }
+       else {
+               /* curundo has to remain current situation! */
+               
+               if(edit->curundo==NULL || edit->curundo->next==NULL) error("No more steps to redo");
+               else {
+                       get_ParticleUndo(psys, edit->curundo->next);
+                       edit->curundo= edit->curundo->next;
+                       if(G.f & G_DEBUG) printf("redo %s\n", edit->curundo->name);
+               }
+       }
+
+       DAG_object_flush_update(scene, OBACT, OB_RECALC_DATA);
+}
+
+static void ParticleUndo_number(Scene *scene, ParticleEdit *edit, int nr)
+{
+       ParticleUndo *undo;
+       int a=1;
+       
+       for(undo= edit->undo.first; undo; undo= undo->next, a++) {
+               if(a==nr) break;
+       }
+       edit->curundo= undo;
+       PE_undo_step(scene, 0);
+}
+
+static void ParticleUndo_clear(ParticleSystem *psys)
+{
+       ParticleUndo *undo;
+       ParticleEdit *edit;
+
+       if(psys==0) return;
+
+       edit = psys->edit;
+
+       if(edit==0) return;
+       
+       undo= edit->undo.first;
+       while(undo) {
+               free_ParticleUndo(undo);
+               undo= undo->next;
+       }
+       BLI_freelistN(&edit->undo);
+       edit->curundo= NULL;
+}
+void PE_undo(Scene *scene)
+{
+       PE_undo_step(scene, 1);
+}
+void PE_redo(Scene *scene)
+{
+       PE_undo_step(scene, -1);
+}
+void PE_undo_menu(Scene *scene)
+{
+       ParticleSystem *psys = PE_get_current(OBACT);
+       ParticleEdit *edit = 0;
+       ParticleUndo *undo;
+       DynStr *ds;
+       short event;
+       char *menu;
+
+       if(!PE_can_edit(psys)) return;
+       edit = psys->edit;
+       
+       ds= BLI_dynstr_new();
+
+       BLI_dynstr_append(ds, "Particlemode Undo History %t");
+       
+       for(undo= edit->undo.first; undo; undo= undo->next) {
+               BLI_dynstr_append(ds, "|");
+               BLI_dynstr_append(ds, undo->name);
+       }
+       
+       menu= BLI_dynstr_get_cstring(ds);
+       BLI_dynstr_free(ds);
+       
+// XXX event= pupmenu_col(menu, 20);
+       MEM_freeN(menu);
+       
+       if(event>0) ParticleUndo_number(scene, edit,event);
+}
+
+void PE_get_colors(char sel[4], char nosel[4])
+{
+       UI_GetThemeColor3ubv(TH_EDGE_SELECT, sel);
+       UI_GetThemeColor3ubv(TH_WIRE, nosel);
+}
+
+int PE_minmax(Scene *scene, float *min, float *max)
+{
+       Object *ob = OBACT;
+       ParticleSystem *psys = PE_get_current(ob);
+       ParticleSystemModifierData *psmd;
+       ParticleData *pa;
+       ParticleEditKey *key;
+       float co[3], mat[4][4];
+       int i, k, totpart, ok = 0;
+
+       if(!PE_can_edit(psys)) return ok;
+       
+       psmd= psys_get_modifier(ob, psys);
+       totpart= psys->totpart;
+
+       LOOP_PARTICLES(i,pa){
+               if(pa->flag&PARS_HIDE) continue;
+
+               psys_mat_hair_to_global(ob, psmd->dm, psys->part->from, pa, mat);
+
+               LOOP_KEYS(k,key){
+                       if(key->flag&PEK_SELECT) {
+                               VECCOPY(co, key->co);
+                               Mat4MulVecfl(mat, co);
+                               DO_MINMAX(co, min, max);                
+                               ok= 1;
+                       }
+               }
+       }
+
+       if(!ok) {
+               minmax_object(ob, min, max);
+               ok= 1;
+       }
+  
+       return ok;
+}
+
diff --git a/source/blender/editors/physics/fluidsim.c b/source/blender/editors/physics/fluidsim.c
new file mode 100644 (file)
index 0000000..902979e
--- /dev/null
@@ -0,0 +1,1149 @@
+/**
+ * fluidsim.c
+ * 
+ * $Id$
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) Blender Foundation
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+
+
+#include <math.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+
+#ifdef WIN32   /* Windos */
+#ifndef snprintf
+#define snprintf _snprintf
+#endif
+#endif
+
+#include "MEM_guardedalloc.h"
+
+/* types */
+#include "DNA_curve_types.h"
+#include "DNA_object_types.h"
+#include "DNA_object_fluidsim.h"       
+#include "DNA_key_types.h"
+#include "DNA_mesh_types.h"
+#include "DNA_meshdata_types.h"
+#include "DNA_lattice_types.h"
+#include "DNA_scene_types.h"
+#include "DNA_camera_types.h"
+#include "DNA_screen_types.h"
+#include "DNA_space_types.h"
+#include "DNA_userdef_types.h"
+#include "DNA_ipo_types.h"
+#include "DNA_key_types.h" 
+
+#include "BLI_blenlib.h"
+#include "BLI_threads.h"
+#include "BLI_arithb.h"
+
+#include "BKE_blender.h"
+#include "BKE_context.h"
+#include "BKE_customdata.h"
+#include "BKE_displist.h"
+#include "BKE_effect.h"
+#include "BKE_fluidsim.h"
+#include "BKE_global.h"
+#include "BKE_modifier.h"
+#include "BKE_main.h"
+#include "BKE_key.h"
+#include "BKE_scene.h"
+#include "BKE_object.h"
+#include "BKE_softbody.h"
+#include "BKE_DerivedMesh.h"
+#include "BKE_ipo.h"
+
+#include "PIL_time.h"
+
+#include "LBM_fluidsim.h"
+
+#include "BIF_gl.h"
+
+#include "ED_anim_api.h"
+#include "ED_fluidsim.h"
+
+/* XXX */
+/* from header info.c */
+static int start_progress_bar(void) {return 0;};
+static void end_progress_bar(void) {};
+static void waitcursor() {};
+static int progress_bar(float done, char *busy_info) {return 0;}
+static int pupmenu() {return 0;}
+/* XXX */
+
+
+double fluidsimViscosityPreset[6] = {
+       -1.0,   /* unused */
+       -1.0,   /* manual */
+       1.0e-6, /* water */
+       5.0e-5, /* some (thick) oil */
+       2.0e-3, /* ca. honey */
+       -1.0    /* end */
+};
+
+char* fluidsimViscosityPresetString[6] = {
+       "UNUSED",       /* unused */
+       "UNUSED",       /* manual */
+       "  = 1.0 * 10^-6", /* water */
+       "  = 5.0 * 10^-5", /* some (thick) oil */
+       "  = 2.0 * 10^-3", /* ca. honey */
+       "INVALID"       /* end */
+};
+
+/* enable/disable overall compilation */
+#ifndef DISABLE_ELBEEM
+
+
+/* ********************** fluid sim settings struct functions ********************** */
+
+/* helper function */
+void fluidsimGetGeometryObjFilename(struct Object *ob, char *dst) { //, char *srcname) {
+       //snprintf(dst,FILE_MAXFILE, "%s_cfgdata_%s.bobj.gz", srcname, ob->id.name);
+       snprintf(dst,FILE_MAXFILE, "fluidcfgdata_%s.bobj.gz", ob->id.name);
+}
+
+
+
+
+/* ******************************************************************************** */
+/* ********************** fluid sim channel helper functions ********************** */
+/* ******************************************************************************** */
+
+// no. of entries for the two channel sizes
+#define CHANNEL_FLOAT 1
+#define CHANNEL_VEC   3
+
+#define FS_FREE_ONECHANNEL(c,str) { \
+       if(c){ MEM_freeN(c); c=NULL; } \
+} // end ONE CHANN, debug: fprintf(stderr,"freeing " str " \n"); 
+
+#define FS_FREE_CHANNELS { \
+       FS_FREE_ONECHANNEL(timeAtIndex,"timeAtIndex");\
+       FS_FREE_ONECHANNEL(timeAtFrame,"timeAtFrame");\
+       FS_FREE_ONECHANNEL(channelDomainTime,"channelDomainTime"); \
+       FS_FREE_ONECHANNEL(channelDomainGravity,"channelDomainGravity");\
+       FS_FREE_ONECHANNEL(channelDomainViscosity,"channelDomainViscosity");\
+       for(i=0;i<256;i++) { \
+               FS_FREE_ONECHANNEL(channelObjMove[i][0],"channelObjMove0"); \
+               FS_FREE_ONECHANNEL(channelObjMove[i][1],"channelObjMove1"); \
+               FS_FREE_ONECHANNEL(channelObjMove[i][2],"channelObjMove2"); \
+               FS_FREE_ONECHANNEL(channelObjInivel[i],"channelObjInivel"); \
+               FS_FREE_ONECHANNEL(channelObjActive[i],"channelObjActive"); \
+               FS_FREE_ONECHANNEL(channelAttractforceStrength[i],"channelAttractforceStrength"); \
+               FS_FREE_ONECHANNEL(channelAttractforceRadius[i],"channelAttractforceRadius"); \
+               FS_FREE_ONECHANNEL(channelVelocityforceStrength[i],"channelVelocityforceStrength"); \
+               FS_FREE_ONECHANNEL(channelVelocityforceRadius[i],"channelVelocityforceRadius"); \
+       }  \
+} // end FS FREE CHANNELS
+
+
+// simplify channels before printing
+// for API this is done anyway upon init
+#if 0
+static void fluidsimPrintChannel(FILE *file, float *channel, int paramsize, char *str, int entries) 
+{ 
+       int i,j; 
+       int channelSize = paramsize; 
+
+       if(entries==3) {
+               elbeemSimplifyChannelVec3( channel, &channelSize); 
+       } else if(entries==1) {
+               elbeemSimplifyChannelFloat( channel, &channelSize); 
+       } else {
+               // invalid, cant happen?
+       }
+
+       fprintf(file, "      CHANNEL %s = \n", str); 
+       for(i=0; i<channelSize;i++) { 
+               fprintf(file,"        ");  
+               for(j=0;j<=entries;j++) {  // also print time value
+                       fprintf(file," %f ", channel[i*(entries+1)+j] ); 
+                       if(j==entries-1){ fprintf(file,"  "); }
+               } 
+               fprintf(file," \n");  
+       } 
+
+       fprintf(file,  "      ; \n" ); 
+}
+#endif
+
+static void fluidsimInitChannel(Scene *scene, float **setchannel, int size, float *time, 
+               int *icuIds, float *defaults, Ipo* ipo, int entries) 
+{
+#if 0
+       /* goes away completely */
+       int i,j;
+       IpoCurve* icus[3];
+       char *cstr = NULL;
+       float *channel = NULL;
+       float aniFrlen = scene->r.framelen;
+       int current_frame = scene->r.cfra;
+       if((entries<1) || (entries>3)) {
+               printf("fluidsimInitChannel::Error - invalid no. of entries: %d\n",entries);
+               entries = 1;
+       }
+
+       cstr = "fluidsiminit_channelfloat";
+       if(entries>1) cstr = "fluidsiminit_channelvec";
+       channel = MEM_callocN( size* (entries+1)* sizeof(float), cstr );
+       
+       if(ipo) {
+               for(j=0; j<entries; j++) icus[j]  = find_ipocurve(ipo, icuIds[j] );
+       } else {
+               for(j=0; j<entries; j++) icus[j]  = NULL; 
+       }
+       
+       for(j=0; j<entries; j++) {
+               if(icus[j]) { 
+                       for(i=1; i<=size; i++) {
+                               /* Bugfix to make python drivers working
+                               // which uses Blender.get("curframe") 
+                               */
+                               scene->r.cfra = floor(aniFrlen*((float)i));
+                               
+                               // XXX calc_icu(icus[j], aniFrlen*((float)i) );
+                               channel[(i-1)*(entries+1) + j] = icus[j]->curval;
+                       }
+               }  else {
+                       for(i=1; i<=size; i++) { channel[(i-1)*(entries+1) + j] = defaults[j]; }
+               }
+               //printf("fluidsimInitChannel entry:%d , ",j); for(i=1; i<=size; i++) { printf(" val%d:%f ",i, channel[(i-1)*(entries+1) + j] ); } printf(" \n"); // DEBUG
+       }
+       // set time values
+       for(i=1; i<=size; i++) {
+               channel[(i-1)*(entries+1) + entries] = time[i];
+       }
+       scene->r.cfra = current_frame;
+       *setchannel = channel;
+#endif
+}
+
+static void fluidsimInitMeshChannel(bContext *C, float **setchannel, int size, Object *obm, int vertices, 
+                                                                       float *time, int modifierIndex) 
+{
+       Scene *scene= CTX_data_scene(C);
+       float *channel = NULL;
+       int mallsize = size* (3*vertices+1);
+       int frame,i;
+       int numVerts=0, numTris=0;
+       int setsize = 3*vertices+1;
+
+       channel = MEM_callocN( mallsize* sizeof(float), "fluidsim_meshchannel" );
+
+       //fprintf(stderr,"\n\nfluidsimInitMeshChannel size%d verts%d mallsize%d \n\n\n",size,vertices,mallsize);
+       for(frame=1; frame<=size; frame++) {
+               float *verts=NULL;
+               int *tris=NULL;
+               scene->r.cfra = frame;
+               ED_update_for_newframe(C, 0);
+
+               initElbeemMesh(scene, obm, &numVerts, &verts, &numTris, &tris, 1, modifierIndex);
+               //fprintf(stderr,"\nfluidsimInitMeshChannel frame%d verts%d/%d \n\n",frame,vertices,numVerts);
+               for(i=0; i<3*vertices;i++) {
+                       channel[(frame-1)*setsize + i] = verts[i];
+                       //fprintf(stdout," frame%d vert%d=%f \n",frame,i,verts[i]);
+                       //if(i%3==2) fprintf(stdout,"\n");
+               }
+               channel[(frame-1)*setsize + setsize-1] = time[frame];
+
+               MEM_freeN(verts);
+               MEM_freeN(tris);
+       }
+       *setchannel = channel;
+}
+
+
+/* ******************************************************************************** */
+/* ********************** simulation thread             ************************* */
+/* ******************************************************************************** */
+
+static volatile int    globalBakeState = 0; // 0 everything ok, -1 abort simulation, -2 sim error, 1 sim done
+static volatile int    globalBakeFrame = 0;
+static volatile int g_break= 0;
+
+// run simulation in seperate thread
+static void *fluidsimSimulateThread(void *unused) { // *ptr) {
+       //char* fnameCfgPath = (char*)(ptr);
+       int ret=0;
+       
+       ret = elbeemSimulate();
+       BLI_lock_thread(LOCK_CUSTOM1);
+       if(globalBakeState==0) {
+               if(ret==0) {
+                       // if no error, set to normal exit
+                       globalBakeState = 1;
+               } else {
+                       // simulation failed, display error
+                       globalBakeState = -2;
+               }
+       }
+       BLI_unlock_thread(LOCK_CUSTOM1);
+       return NULL;
+}
+
+
+int runSimulationCallback(void *data, int status, int frame) {
+       //elbeemSimulationSettings *settings = (elbeemSimulationSettings*)data;
+       //printf("elbeem blender cb s%d, f%d, domainid:%d \n", status,frame, settings->domainId ); // DEBUG
+       int state = 0;
+       if(status==FLUIDSIM_CBSTATUS_NEWFRAME) {
+               BLI_lock_thread(LOCK_CUSTOM1);
+               globalBakeFrame = frame-1;
+               BLI_unlock_thread(LOCK_CUSTOM1);
+       }
+       
+       //if((frameCounter==3) && (!frameStop)) { frameStop=1; return 1; }
+               
+       BLI_lock_thread(LOCK_CUSTOM1);
+       state = globalBakeState;
+       BLI_unlock_thread(LOCK_CUSTOM1);
+       
+       if(state!=0) {
+               return FLUIDSIM_CBRET_ABORT;
+       }
+       
+       return FLUIDSIM_CBRET_CONTINUE;
+}
+
+
+/* ******************************************************************************** */
+/* ********************** write fluidsim config to file ************************* */
+/* ******************************************************************************** */
+
+void fluidsimBake(bContext *C, struct Object *ob)
+{
+       Scene *scene= CTX_data_scene(C);
+       FILE *fileCfg;
+       int i;
+       struct Object *fsDomain = NULL;
+       FluidsimSettings *domainSettings;
+       struct Object *obit = NULL; /* object iterator */
+       Base *base;
+       int origFrame = scene->r.cfra;
+       char debugStrBuffer[256];
+       int dirExist = 0;
+       int gridlevels = 0;
+       int simAborted = 0; // was the simulation aborted by user?
+       int  doExportOnly = 0;
+       char *exportEnvStr = "BLENDER_ELBEEMEXPORTONLY";
+       const char *strEnvName = "BLENDER_ELBEEMDEBUG"; // from blendercall.cpp
+       //char *channelNames[3] = { "translation","rotation","scale" };
+
+       char *suffixConfig = "fluidsim.cfg";
+       char *suffixSurface = "fluidsurface";
+       char newSurfdataPath[FILE_MAXDIR+FILE_MAXFILE]; // modified output settings
+       char targetDir[FILE_MAXDIR+FILE_MAXFILE];  // store & modify output settings
+       char targetFile[FILE_MAXDIR+FILE_MAXFILE]; // temp. store filename from targetDir for access
+       int  outStringsChanged = 0;             // modified? copy back before baking
+       int  haveSomeFluid = 0;                 // check if any fluid objects are set
+
+       // config vars, inited before either export or run...
+       double calcViscosity = 0.0;
+       int noFrames;
+       double aniFrameTime;
+       float aniFrlen;
+       int   channelObjCount;
+       float *bbStart = NULL;
+       float *bbSize = NULL;
+       float domainMat[4][4];
+       float invDomMat[4][4];
+       // channel data
+       int   allchannelSize; // fixed by no. of frames
+       int   startFrame = 1;  // dont use scene->r.sfra here, always start with frame 1
+       // easy frame -> sim time calc
+       float *timeAtFrame=NULL, *timeAtIndex=NULL;
+       // domain
+       float *channelDomainTime = NULL;
+       float *channelDomainViscosity = NULL; 
+       float *channelDomainGravity = NULL;
+       // objects (currently max. 256 objs)
+       float *channelObjMove[256][3]; // object movments , 0=trans, 1=rot, 2=scale
+       float *channelObjInivel[256];    // initial velocities
+       float *channelObjActive[256];    // obj active channel
+       
+       /* fluid control channels */
+       float *channelAttractforceStrength[256];
+       float *channelAttractforceRadius[256];
+       float *channelVelocityforceStrength[256];
+       float *channelVelocityforceRadius[256];
+       FluidsimModifierData *fluidmd = NULL;
+       Mesh *mesh = NULL;
+       
+       if(getenv(strEnvName)) {
+               int dlevel = atoi(getenv(strEnvName));
+               elbeemSetDebugLevel(dlevel);
+               snprintf(debugStrBuffer,256,"fluidsimBake::msg: Debug messages activated due to envvar '%s'\n",strEnvName); 
+               elbeemDebugOut(debugStrBuffer);
+       }
+       if(getenv(exportEnvStr)) {
+               doExportOnly = atoi(getenv(exportEnvStr));
+               snprintf(debugStrBuffer,256,"fluidsimBake::msg: Exporting mode set to '%d' due to envvar '%s'\n",doExportOnly, exportEnvStr); 
+               elbeemDebugOut(debugStrBuffer);
+       }
+
+       // make sure it corresponds to startFrame setting
+       // old: noFrames = scene->r.efra - scene->r.sfra +1;
+       noFrames = scene->r.efra - 0;
+       if(noFrames<=0) {
+               pupmenu("Fluidsim Bake Error%t|No frames to export - check your animation range settings. Aborted%x0");
+               return;
+       }
+
+       /* no object pointer, find in selected ones.. */
+       if(!ob) {
+               for(base=scene->base.first; base; base= base->next) {
+                       if ((base)->flag & SELECT) 
+                       {
+                               FluidsimModifierData *fluidmdtmp = (FluidsimModifierData *)modifiers_findByType(base->object, eModifierType_Fluidsim);
+                               
+                               if(fluidmdtmp && (base->object->type==OB_MESH)) 
+                               {
+                                       if(fluidmdtmp->fss->type == OB_FLUIDSIM_DOMAIN) 
+                                       {
+                                               ob = base->object;
+                                               break;
+                                       }
+                               }
+                       }
+               }
+               // no domains found?
+               if(!ob) return;
+       }
+       
+       channelObjCount = 0;
+       for(base=scene->base.first; base; base= base->next) 
+       {
+               FluidsimModifierData *fluidmdtmp = (FluidsimModifierData *)modifiers_findByType(base->object, eModifierType_Fluidsim);
+               obit = base->object;
+               if( fluidmdtmp && 
+                       (obit->type==OB_MESH) &&
+                       (fluidmdtmp->fss->type != OB_FLUIDSIM_DOMAIN) &&  // if has to match 3 places! // CHECKMATCH
+                       (fluidmdtmp->fss->type != OB_FLUIDSIM_PARTICLE) ) 
+               {
+                       channelObjCount++;
+               }
+       }
+       
+       if (channelObjCount>=255) {
+               pupmenu("Fluidsim Bake Error%t|Cannot bake with more then 256 objects");
+               return;
+       }
+
+       /* check if there's another domain... */
+       for(base=scene->base.first; base; base= base->next) 
+       {
+               FluidsimModifierData *fluidmdtmp = (FluidsimModifierData *)modifiers_findByType(base->object, eModifierType_Fluidsim);
+               obit = base->object;
+               if( fluidmdtmp &&(obit->type==OB_MESH)) 
+               {
+                       if(fluidmdtmp->fss->type == OB_FLUIDSIM_DOMAIN) 
+                       {
+                               if(obit != ob) 
+                               {
+                                       pupmenu("Fluidsim Bake Error%t|There should be only one domain object! Aborted%x0");
+                                       return;
+                               }
+                       }
+               }
+       }
+       
+       // check if theres any fluid
+       // abort baking if not...
+       for(base=scene->base.first; base; base= base->next) 
+       {
+               FluidsimModifierData *fluidmdtmp = (FluidsimModifierData *)modifiers_findByType(base->object, eModifierType_Fluidsim);
+               obit = base->object;
+               if( fluidmdtmp && 
+                       (obit->type==OB_MESH) && 
+                       ((fluidmdtmp->fss->type == OB_FLUIDSIM_FLUID) ||
+                       (fluidmdtmp->fss->type == OB_FLUIDSIM_INFLOW) ))
+               {
+                       haveSomeFluid = 1;
+                       break;
+               }
+       }
+       if(!haveSomeFluid) {
+               pupmenu("Fluidsim Bake Error%t|No fluid objects in scene... Aborted%x0");
+               return;
+       }
+       
+       /* these both have to be valid, otherwise we wouldnt be here */
+       /* dont use ob here after...*/
+       fsDomain = ob;
+       fluidmd = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim);
+       domainSettings = fluidmd->fss;
+       ob = NULL;
+       mesh = fsDomain->data;
+       
+       // calculate bounding box
+       fluid_get_bb(mesh->mvert, mesh->totvert, fsDomain->obmat, domainSettings->bbStart, domainSettings->bbSize);
+       
+       // reset last valid frame
+       domainSettings->lastgoodframe = -1;
+       
+       /* rough check of settings... */
+       if(domainSettings->previewresxyz > domainSettings->resolutionxyz) {
+               snprintf(debugStrBuffer,256,"fluidsimBake::warning - Preview (%d) >= Resolution (%d)... setting equal.\n", domainSettings->previewresxyz ,  domainSettings->resolutionxyz); 
+               elbeemDebugOut(debugStrBuffer);
+               domainSettings->previewresxyz = domainSettings->resolutionxyz;
+       }
+       // set adaptive coarsening according to resolutionxyz
+       // this should do as an approximation, with in/outflow
+       // doing this more accurate would be overkill
+       // perhaps add manual setting?
+       if(domainSettings->maxRefine <0) {
+               if(domainSettings->resolutionxyz>128) {
+                       gridlevels = 2;
+               } else
+               if(domainSettings->resolutionxyz>64) {
+                       gridlevels = 1;
+               } else {
+                       gridlevels = 0;
+               }
+       } else {
+               gridlevels = domainSettings->maxRefine;
+       }
+       snprintf(debugStrBuffer,256,"fluidsimBake::msg: Baking %s, refine: %d\n", fsDomain->id.name , gridlevels ); 
+       elbeemDebugOut(debugStrBuffer);
+
+       // prepare names...
+       strncpy(targetDir, domainSettings->surfdataPath, FILE_MAXDIR);
+       strncpy(newSurfdataPath, domainSettings->surfdataPath, FILE_MAXDIR);
+       BLI_convertstringcode(targetDir, G.sce); // fixed #frame-no 
+
+       strcpy(targetFile, targetDir);
+       strcat(targetFile, suffixConfig);
+       if(!doExportOnly) { strcat(targetFile,".tmp"); }  // dont overwrite/delete original file
+       // make sure all directories exist
+       // as the bobjs use the same dir, this only needs to be checked
+       // for the cfg output
+       BLI_make_existing_file(targetFile);
+
+       // check selected directory
+       // simply try to open cfg file for writing to test validity of settings
+       fileCfg = fopen(targetFile, "w");
+       if(fileCfg) { 
+               dirExist = 1; fclose(fileCfg); 
+               // remove cfg dummy from  directory test
+               if(!doExportOnly) { BLI_delete(targetFile, 0,0); }
+       }
+
+       if((strlen(targetDir)<1) || (!dirExist)) {
+               char blendDir[FILE_MAXDIR+FILE_MAXFILE], blendFile[FILE_MAXDIR+FILE_MAXFILE];
+               // invalid dir, reset to current/previous
+               strcpy(blendDir, G.sce);
+               BLI_splitdirstring(blendDir, blendFile);
+               if(strlen(blendFile)>6){
+                       int len = strlen(blendFile);
+                       if( (blendFile[len-6]=='.')&& (blendFile[len-5]=='b')&& (blendFile[len-4]=='l')&&
+                                       (blendFile[len-3]=='e')&& (blendFile[len-2]=='n')&& (blendFile[len-1]=='d') ){
+                               blendFile[len-6] = '\0';
+                       }
+               }
+               // todo... strip .blend ?
+               snprintf(newSurfdataPath,FILE_MAXFILE+FILE_MAXDIR,"//fluidsimdata/%s_%s_", blendFile, fsDomain->id.name);
+
+               snprintf(debugStrBuffer,256,"fluidsimBake::error - warning resetting output dir to '%s'\n", newSurfdataPath);
+               elbeemDebugOut(debugStrBuffer);
+               outStringsChanged=1;
+       }
+
+       // check if modified output dir is ok
+       if(outStringsChanged) {
+               char dispmsg[FILE_MAXDIR+FILE_MAXFILE+256];
+               int  selection=0;
+               strcpy(dispmsg,"Output settings set to: '");
+               strcat(dispmsg, newSurfdataPath);
+               strcat(dispmsg, "'%t|Continue with changed settings%x1|Discard and abort%x0");
+
+               // ask user if thats what he/she wants...
+               selection = pupmenu(dispmsg);
+               if(selection<1) return; // 0 from menu, or -1 aborted
+               strcpy(targetDir, newSurfdataPath);
+               strncpy(domainSettings->surfdataPath, newSurfdataPath, FILE_MAXDIR);
+               BLI_convertstringcode(targetDir, G.sce); // fixed #frame-no 
+       }
+       
+       // --------------------------------------------------------------------------------------------
+       // dump data for start frame 
+       // CHECK more reasonable to number frames according to blender?
+       // dump data for frame 0
+       scene->r.cfra = startFrame;
+       ED_update_for_newframe(C, 0);
+       
+       // init common export vars for both file export and run
+       for(i=0; i<256; i++) {
+               channelObjMove[i][0] = channelObjMove[i][1] = channelObjMove[i][2] = NULL;
+               channelObjInivel[i] = NULL;
+               channelObjActive[i] = NULL;
+               channelAttractforceStrength[i] = NULL;
+               channelAttractforceRadius[i] = NULL;
+               channelVelocityforceStrength[i] = NULL;
+               channelVelocityforceRadius[i] = NULL;
+       }
+       allchannelSize = scene->r.efra; // always use till last frame
+       aniFrameTime = (domainSettings->animEnd - domainSettings->animStart)/(double)noFrames;
+       // blender specific - scale according to map old/new settings in anim panel:
+       aniFrlen = scene->r.framelen;
+       if(domainSettings->viscosityMode==1) {
+               /* manual mode, visc=value/(10^-vexp) */
+               calcViscosity = (1.0/pow(10.0,domainSettings->viscosityExponent)) * domainSettings->viscosityValue;
+       } else {
+               calcViscosity = fluidsimViscosityPreset[ domainSettings->viscosityMode ];
+       }
+
+       bbStart = domainSettings->bbStart;
+       bbSize = domainSettings->bbSize;
+
+       // always init
+       { int timeIcu[1] = { FLUIDSIM_TIME };
+               float timeDef[1] = { 1. };
+               int gravIcu[3] = { FLUIDSIM_GRAV_X, FLUIDSIM_GRAV_Y, FLUIDSIM_GRAV_Z };
+               float gravDef[3];
+               int viscIcu[1] = { FLUIDSIM_VISC };
+               float viscDef[1] = { 1. };
+
+               gravDef[0] = domainSettings->gravx;
+               gravDef[1] = domainSettings->gravy;
+               gravDef[2] = domainSettings->gravz;
+
+               // time channel is a bit special, init by hand...
+               timeAtIndex = MEM_callocN( (allchannelSize+1)*1*sizeof(float), "fluidsiminit_timeatindex");
+               for(i=0; i<=scene->r.efra; i++) {
+                       timeAtIndex[i] = (float)(i-startFrame);
+               }
+               fluidsimInitChannel(scene, &channelDomainTime, allchannelSize, timeAtIndex, timeIcu,timeDef, domainSettings->ipo, CHANNEL_FLOAT ); // NDEB
+               // time channel is a multiplicator for aniFrameTime
+               if(channelDomainTime) {
+                       for(i=0; i<allchannelSize; i++) { 
+                               channelDomainTime[i*2+0] = aniFrameTime * channelDomainTime[i*2+0]; 
+                               if(channelDomainTime[i*2+0]<0.) channelDomainTime[i*2+0] = 0.;
+                       }
+               }
+               timeAtFrame = MEM_callocN( (allchannelSize+1)*1*sizeof(float), "fluidsiminit_timeatframe");
+               timeAtFrame[0] = timeAtFrame[1] = domainSettings->animStart; // start at index 1
+               if(channelDomainTime) {
+                       for(i=2; i<=allchannelSize; i++) {
+                               timeAtFrame[i] = timeAtFrame[i-1]+channelDomainTime[(i-1)*2+0];
+                       }
+               } else {
+                       for(i=2; i<=allchannelSize; i++) { timeAtFrame[i] = timeAtFrame[i-1]+aniFrameTime; }
+               }
+
+               fluidsimInitChannel(scene, &channelDomainViscosity, allchannelSize, timeAtFrame, viscIcu,viscDef, domainSettings->ipo, CHANNEL_FLOAT ); // NDEB
+               if(channelDomainViscosity) {
+                       for(i=0; i<allchannelSize; i++) { channelDomainViscosity[i*2+0] = calcViscosity * channelDomainViscosity[i*2+0]; }
+               }
+               fluidsimInitChannel(scene, &channelDomainGravity, allchannelSize, timeAtFrame, gravIcu,gravDef, domainSettings->ipo, CHANNEL_VEC );
+       } // domain channel init
+       
+       // init obj movement channels
+       channelObjCount=0;
+       for(base=scene->base.first; base; base= base->next) 
+       {
+               FluidsimModifierData *fluidmdtmp = (FluidsimModifierData *)modifiers_findByType(base->object, eModifierType_Fluidsim);
+               obit = base->object;
+               
+               if( fluidmdtmp && 
+                       (obit->type==OB_MESH) &&
+                       (fluidmdtmp->fss->type != OB_FLUIDSIM_DOMAIN) &&  // if has to match 3 places! // CHECKMATCH
+                       (fluidmdtmp->fss->type != OB_FLUIDSIM_PARTICLE) ) {
+
+                       //  cant use fluidsimInitChannel for obj channels right now, due
+                       //  to the special DXXX channels, and the rotation specialities
+                       IpoCurve *icuex[3][3];
+                       //IpoCurve *par_icuex[3][3];
+#if 0
+                       int icuIds[3][3] = { 
+                               {OB_LOC_X,  OB_LOC_Y,  OB_LOC_Z},
+                               {OB_ROT_X,  OB_ROT_Y,  OB_ROT_Z},
+                               {OB_SIZE_X, OB_SIZE_Y, OB_SIZE_Z} 
+                       };
+                       int icudIds[3][3] = { 
+                               {OB_DLOC_X,  OB_DLOC_Y,  OB_DLOC_Z},
+                               {OB_DROT_X,  OB_DROT_Y,  OB_DROT_Z},
+                               {OB_DSIZE_X, OB_DSIZE_Y, OB_DSIZE_Z} 
+                       };
+#endif
+                       // relative ipos
+                       IpoCurve *icudex[3][3];
+                       //IpoCurve *par_icudex[3][3];
+                       int j,k;
+                       float vals[3] = {0.0,0.0,0.0}; 
+                       int o = channelObjCount;
+                       int   inivelIcu[3] =  { FLUIDSIM_VEL_X, FLUIDSIM_VEL_Y, FLUIDSIM_VEL_Z };
+                       float inivelDefs[3];
+                       int   activeIcu[1] =  { FLUIDSIM_ACTIVE };
+                       float activeDefs[1] = { 1 }; // default to on
+
+                       inivelDefs[0] = fluidmdtmp->fss->iniVelx;
+                       inivelDefs[1] = fluidmdtmp->fss->iniVely;
+                       inivelDefs[2] = fluidmdtmp->fss->iniVelz;
+
+                       // check & init loc,rot,size
+                       for(j=0; j<3; j++) {
+                               for(k=0; k<3; k++) {
+                                       // XXX icuex[j][k]  = find_ipocurve(obit->ipo, icuIds[j][k] );
+                                       // XXX icudex[j][k] = find_ipocurve(obit->ipo, icudIds[j][k] );
+                                       // XXX lines below were already disabled!
+                                       //if(obit->parent) {
+                                               //par_icuex[j][k]  = find_ipocurve(obit->parent->ipo, icuIds[j][k] );
+                                               //par_icudex[j][k] = find_ipocurve(obit->parent->ipo, icudIds[j][k] );
+                                       //}
+                               }
+                       }
+
+                       for(j=0; j<3; j++) {
+                               channelObjMove[o][j] = MEM_callocN( allchannelSize*4*sizeof(float), "fluidsiminit_objmovchannel");
+                               for(i=1; i<=allchannelSize; i++) {
+
+                                       for(k=0; k<3; k++) {
+                                               if(icuex[j][k]) { 
+                                                       // IPO exists, use it ...
+                                                       // XXX calc_icu(icuex[j][k], aniFrlen*((float)i) );
+                                                       vals[k] = icuex[j][k]->curval; 
+                                                       if(obit->parent) {
+                                                               // add parent transform, multiply scaling, add trafo&rot
+                                                               //calc_icu(par_icuex[j][k], aniFrlen*((float)i) );
+                                                               //if(j==2) { vals[k] *= par_icuex[j][k]->curval; }
+                                                               //else { vals[k] += par_icuex[j][k]->curval; }
+                                                       }
+                                               } else {
+                                                       // use defaults from static values
+                                                       float setval=0.0;
+                                                       if(j==0) { 
+                                                               setval = obit->loc[k];
+                                                               if(obit->parent){ setval += obit->parent->loc[k]; }
+                                                       } else if(j==1) { 
+                                                               setval = ( 180.0*obit->rot[k] )/( 10.0*M_PI );
+                                                               if(obit->parent){ setval = ( 180.0*(obit->rot[k]+obit->parent->rot[k]) )/( 10.0*M_PI ); }
+                                                       } else { 
+                                                               setval = obit->size[k]; 
+                                                               if(obit->parent){ setval *= obit->parent->size[k]; }
+                                                       }
+                                                       vals[k] = setval;
+                                               }
+                                               if(icudex[j][k]) { 
+                                                       // XXX calc_icu(icudex[j][k], aniFrlen*((float)i) );
+                                                       //vals[k] += icudex[j][k]->curval; 
+                                                       // add transform, multiply scaling, add trafo&rot
+                                                       if(j==2) { vals[k] *= icudex[j][k]->curval; }
+                                                       else { vals[k] += icudex[j][k]->curval; }
+                                                       if(obit->parent) {
+                                                               // add parent transform, multiply scaling, add trafo&rot
+                                                               //calc_icu(par_icuex[j][k], aniFrlen*((float)i) );
+                                                               //if(j==2) { vals[k] *= par_icudex[j][k]->curval; }
+                                                               //else { vals[k] += par_icudex[j][k]->curval; }
+                                                       }
+                                               } 
+                                       } // k
+
+                                       for(k=0; k<3; k++) {
+                                               float set = vals[k];
+                                               if(j==1) { // rot is downscaled by 10 for ipo !?
+                                                       set = 360.0 - (10.0*set);
+                                               }
+                                               channelObjMove[o][j][(i-1)*4 + k] = set;
+                                       } // k
+                                       channelObjMove[o][j][(i-1)*4 + 3] = timeAtFrame[i];
+                               }
+                       }
+                       
+                       {
+                               int   attrFSIcu[1] =  { FLUIDSIM_ATTR_FORCE_STR };
+                               int   attrFRIcu[1] =  { FLUIDSIM_ATTR_FORCE_RADIUS };
+                               int   velFSIcu[1] =  { FLUIDSIM_VEL_FORCE_STR };
+                               int   velFRIcu[1] =  { FLUIDSIM_VEL_FORCE_RADIUS };
+
+                               float attrFSDefs[1];
+                               float attrFRDefs[1];
+                               float velFSDefs[1];
+                               float velFRDefs[1];
+                               
+                               attrFSDefs[0] = fluidmdtmp->fss->attractforceStrength;
+                               attrFRDefs[0] = fluidmdtmp->fss->attractforceRadius;
+                               velFSDefs[0] = fluidmdtmp->fss->velocityforceStrength;
+                               velFRDefs[0] = fluidmdtmp->fss->velocityforceRadius;
+                               
+                               fluidsimInitChannel(scene, &channelAttractforceStrength[o], allchannelSize, timeAtFrame, attrFSIcu,attrFSDefs, fluidmdtmp->fss->ipo, CHANNEL_FLOAT );
+                               fluidsimInitChannel(scene, &channelAttractforceRadius[o], allchannelSize, timeAtFrame, attrFRIcu,attrFRDefs, fluidmdtmp->fss->ipo, CHANNEL_FLOAT );
+                               fluidsimInitChannel(scene, &channelVelocityforceStrength[o], allchannelSize, timeAtFrame, velFSIcu,velFSDefs, fluidmdtmp->fss->ipo, CHANNEL_FLOAT );
+                               fluidsimInitChannel(scene, &channelVelocityforceRadius[o], allchannelSize, timeAtFrame, velFRIcu,velFRDefs, fluidmdtmp->fss->ipo, CHANNEL_FLOAT );
+                       }
+                       
+                       fluidsimInitChannel(scene, &channelObjInivel[o], allchannelSize, timeAtFrame, inivelIcu,inivelDefs, fluidmdtmp->fss->ipo, CHANNEL_VEC );
+                       fluidsimInitChannel(scene, &channelObjActive[o], allchannelSize, timeAtFrame, activeIcu,activeDefs, fluidmdtmp->fss->ipo, CHANNEL_FLOAT );
+               
+
+                       channelObjCount++;
+
+               }
+       }
+
+       // init trafo matrix
+       Mat4CpyMat4(domainMat, fsDomain->obmat);
+       if(!Mat4Invert(invDomMat, domainMat)) {
+               snprintf(debugStrBuffer,256,"fluidsimBake::error - Invalid obj matrix?\n"); 
+               elbeemDebugOut(debugStrBuffer);
+               // FIXME add fatal msg
+               FS_FREE_CHANNELS;
+               return;
+       }
+
+
+       // --------------------------------------------------------------------------------------------
+       // start writing / exporting
+       strcpy(targetFile, targetDir);
+       strcat(targetFile, suffixConfig);
+       if(!doExportOnly) { strcat(targetFile,".tmp"); }  // dont overwrite/delete original file
+       // make sure these directories exist as well
+       if(outStringsChanged) {
+               BLI_make_existing_file(targetFile);
+       }
+
+       if(!doExportOnly) {
+               ListBase threads;
+
+               // perform simulation with El'Beem api and threads
+               elbeemSimulationSettings fsset;
+               elbeemResetSettings(&fsset);
+               fsset.version = 1;
+
+               // setup global settings
+               for(i=0 ; i<3; i++) fsset.geoStart[i] = bbStart[i];
+               for(i=0 ; i<3; i++) fsset.geoSize[i] = bbSize[i];
+               
+               // simulate with 50^3
+               fsset.resolutionxyz = (int)domainSettings->resolutionxyz;
+               fsset.previewresxyz = (int)domainSettings->previewresxyz;
+               // 10cm water domain
+               fsset.realsize = domainSettings->realsize;
+               fsset.viscosity = calcViscosity;
+               // earth gravity
+               fsset.gravity[0] = domainSettings->gravx;
+               fsset.gravity[1] = domainSettings->gravy;
+               fsset.gravity[2] = domainSettings->gravz;
+               // simulate 5 frames, each 0.03 seconds, output to ./apitest_XXX.bobj.gz
+               fsset.animStart = domainSettings->animStart;
+               fsset.aniFrameTime = aniFrameTime;
+               fsset.noOfFrames = noFrames; // is otherwise subtracted in parser
+               strcpy(targetFile, targetDir);
+               strcat(targetFile, suffixSurface);
+               // defaults for compressibility and adaptive grids
+               fsset.gstar = domainSettings->gstar;
+               fsset.maxRefine = domainSettings->maxRefine; // check <-> gridlevels
+               fsset.generateParticles = domainSettings->generateParticles; 
+               fsset.numTracerParticles = domainSettings->generateTracers; 
+               fsset.surfaceSmoothing = domainSettings->surfaceSmoothing; 
+               fsset.surfaceSubdivs = domainSettings->surfaceSubdivs; 
+               fsset.farFieldSize = domainSettings->farFieldSize; 
+               strcpy( fsset.outputPath, targetFile);
+
+               // domain channels
+               fsset.channelSizeFrameTime = 
+               fsset.channelSizeViscosity = 
+               fsset.channelSizeGravity =  allchannelSize;
+               fsset.channelFrameTime = channelDomainTime;
+               fsset.channelViscosity = channelDomainViscosity;
+               fsset.channelGravity = channelDomainGravity;
+
+               fsset.runsimCallback = &runSimulationCallback;
+               fsset.runsimUserData = &fsset;
+
+               if(     (domainSettings->typeFlags&OB_FSBND_NOSLIP))   fsset.domainobsType = FLUIDSIM_OBSTACLE_NOSLIP;
+               else if((domainSettings->typeFlags&OB_FSBND_PARTSLIP)) fsset.domainobsType = FLUIDSIM_OBSTACLE_PARTSLIP;
+               else if((domainSettings->typeFlags&OB_FSBND_FREESLIP)) fsset.domainobsType = FLUIDSIM_OBSTACLE_FREESLIP;
+               fsset.domainobsPartslip = domainSettings->partSlipValue;
+               fsset.generateVertexVectors = (domainSettings->domainNovecgen==0);
+
+               // init blender trafo matrix
+               // fprintf(stderr,"elbeemInit - mpTrafo:\n");
+               { int j; 
+               for(i=0; i<4; i++) {
+                       for(j=0; j<4; j++) {
+                               fsset.surfaceTrafo[i*4+j] = invDomMat[j][i];
+                               // fprintf(stderr,"elbeemInit - mpTrafo %d %d = %f (%d) \n", i,j, fsset.surfaceTrafo[i*4+j] , (i*4+j) );
+                       }
+               } }
+
+         // init solver with settings
+               elbeemInit();
+               elbeemAddDomain(&fsset);
+               
+               // init objects
+               channelObjCount = 0;
+               for(base=scene->base.first; base; base= base->next) {
+                       FluidsimModifierData *fluidmdtmp = (FluidsimModifierData *)modifiers_findByType(base->object, eModifierType_Fluidsim);
+                       obit = base->object;
+                       //{ snprintf(debugStrBuffer,256,"DEBUG object name=%s, type=%d ...\n", obit->id.name, obit->type); elbeemDebugOut(debugStrBuffer); } // DEBUG
+                       if( fluidmdtmp &&  // if has to match 3 places! // CHECKMATCH
+                               (obit->type==OB_MESH) &&
+                               (fluidmdtmp->fss->type != OB_FLUIDSIM_DOMAIN) &&
+                               (fluidmdtmp->fss->type != OB_FLUIDSIM_PARTICLE)) 
+                       {
+                               float *verts=NULL;
+                               int *tris=NULL;
+                               int numVerts=0, numTris=0;
+                               int o = channelObjCount;
+                               int     deform = (fluidmdtmp->fss->domainNovecgen); // misused value
+                               // todo - use blenderInitElbeemMesh
+                               int modifierIndex = modifiers_indexInObject(obit, (ModifierData *)fluidmdtmp);
+                               
+                               elbeemMesh fsmesh;
+                               elbeemResetMesh( &fsmesh );
+                               fsmesh.type = fluidmdtmp->fss->type;
+                               // get name of object for debugging solver
+                               fsmesh.name = obit->id.name; 
+
+                               initElbeemMesh(scene, obit, &numVerts, &verts, &numTris, &tris, 0, modifierIndex);
+                               fsmesh.numVertices   = numVerts;
+                               fsmesh.numTriangles  = numTris;
+                               fsmesh.vertices      = verts;
+                               fsmesh.triangles     = tris;
+
+                               fsmesh.channelSizeTranslation  = 
+                               fsmesh.channelSizeRotation     = 
+                               fsmesh.channelSizeScale        = 
+                               fsmesh.channelSizeInitialVel   = 
+                               fsmesh.channelSizeActive       = allchannelSize;
+
+                               fsmesh.channelTranslation      = channelObjMove[o][0];
+                               fsmesh.channelRotation         = channelObjMove[o][1];
+                               fsmesh.channelScale            = channelObjMove[o][2];
+                               fsmesh.channelActive           = channelObjActive[o];
+                               if( (fsmesh.type == OB_FLUIDSIM_FLUID) ||
+                               (fsmesh.type == OB_FLUIDSIM_INFLOW)) {
+                                       fsmesh.channelInitialVel       = channelObjInivel[o];
+                                       fsmesh.localInivelCoords = ((fluidmdtmp->fss->typeFlags&OB_FSINFLOW_LOCALCOORD)?1:0);
+                               } 
+
+                               if(     (fluidmdtmp->fss->typeFlags&OB_FSBND_NOSLIP))   fsmesh.obstacleType = FLUIDSIM_OBSTACLE_NOSLIP;
+                               else if((fluidmdtmp->fss->typeFlags&OB_FSBND_PARTSLIP)) fsmesh.obstacleType = FLUIDSIM_OBSTACLE_PARTSLIP;
+                               else if((fluidmdtmp->fss->typeFlags&OB_FSBND_FREESLIP)) fsmesh.obstacleType = FLUIDSIM_OBSTACLE_FREESLIP;
+                               fsmesh.obstaclePartslip = fluidmdtmp->fss->partSlipValue;
+                               fsmesh.volumeInitType = fluidmdtmp->fss->volumeInitType;
+                               fsmesh.obstacleImpactFactor = fluidmdtmp->fss->surfaceSmoothing; // misused value
+                               
+                               if(fsmesh.type == OB_FLUIDSIM_CONTROL)
+                               {
+                                       // control fluids will get exported as whole
+                                       deform = 1;
+                                       
+                                       fsmesh.cpsTimeStart = fluidmdtmp->fss->cpsTimeStart;
+                                       fsmesh.cpsTimeEnd = fluidmdtmp->fss->cpsTimeEnd;
+                                       fsmesh.cpsQuality = fluidmdtmp->fss->cpsQuality;
+                                       fsmesh.obstacleType = (fluidmdtmp->fss->flag & OB_FLUIDSIM_REVERSE);
+                                       
+                                       fsmesh.channelSizeAttractforceRadius = 
+                                       fsmesh.channelSizeVelocityforceStrength = 
+                                       fsmesh.channelSizeVelocityforceRadius = 
+                                       fsmesh.channelSizeAttractforceStrength = allchannelSize;
+                                       
+                                       fsmesh.channelAttractforceStrength = channelAttractforceStrength[o];
+                                       fsmesh.channelAttractforceRadius = channelAttractforceRadius[o];
+                                       fsmesh.channelVelocityforceStrength = channelVelocityforceStrength[o];
+                                       fsmesh.channelVelocityforceRadius = channelVelocityforceRadius[o];
+                               }
+                               else 
+                               {
+                                       // set channels to 0
+                                       fsmesh.channelAttractforceStrength =
+                                       fsmesh.channelAttractforceRadius = 
+                                       fsmesh.channelVelocityforceStrength = 
+                                       fsmesh.channelVelocityforceRadius = NULL; 
+                               }
+
+                               // animated meshes
+                               if(deform) {
+                                       fsmesh.channelSizeVertices = allchannelSize;
+                                       fluidsimInitMeshChannel(C, &fsmesh.channelVertices, allchannelSize, obit, numVerts, timeAtFrame, modifierIndex);
+                                       scene->r.cfra = startFrame;
+                                       ED_update_for_newframe(C, 0);
+                                       // remove channels
+                                       fsmesh.channelTranslation      = 
+                                       fsmesh.channelRotation         = 
+                                       fsmesh.channelScale            = NULL; 
+                               } 
+
+                               elbeemAddMesh(&fsmesh);
+
+                               if(verts) MEM_freeN(verts);
+                               if(tris) MEM_freeN(tris);
+                               if(fsmesh.channelVertices) MEM_freeN(fsmesh.channelVertices);
+                               channelObjCount++;
+                       } // valid mesh
+               } // objects
+               //domainSettings->type = OB_FLUIDSIM_DOMAIN; // enable for bake display again
+               //fsDomain->fluidsimFlag = OB_FLUIDSIM_ENABLE; // disable during bake
+               
+               // set to neutral, -1 means user abort, -2 means init error
+               globalBakeState = 0;
+               globalBakeFrame = 0;
+               BLI_init_threads(&threads, fluidsimSimulateThread, 1);
+               BLI_insert_thread(&threads, targetFile);
+               
+               {
+                       int done = 0;
+                       float noFramesf = (float)noFrames;
+                       float percentdone = 0.0;
+                       int lastRedraw = -1;
+                       
+                       g_break= 0;
+                       G.afbreek= 0;   /* blender_test_break uses this global */
+                       
+                       start_progress_bar();
+
+                       while(done==0) {
+                               char busy_mess[80];
+                               
+                               waitcursor(1);
+                               
+                               // lukep we add progress bar as an interim mesure
+                               percentdone = globalBakeFrame / noFramesf;
+                               sprintf(busy_mess, "baking fluids %d / %d       |||", globalBakeFrame, (int) noFramesf);
+                               progress_bar(percentdone, busy_mess );
+                               
+                               // longer delay to prevent frequent redrawing
+                               PIL_sleep_ms(2000);
+                               
+                               BLI_lock_thread(LOCK_CUSTOM1);
+                               if(globalBakeState != 0) done = 1; // 1=ok, <0=error/abort
+                               BLI_unlock_thread(LOCK_CUSTOM1);
+
+                               if (!G.background) {
+                                       g_break= blender_test_break();
+                                       
+                                       if(g_break)
+                                       {
+                                               // abort...
+                                               BLI_lock_thread(LOCK_CUSTOM1);
+                                               
+                                               if(domainSettings)
+                                                       domainSettings->lastgoodframe = startFrame+globalBakeFrame;
+                                               
+                                               done = -1;
+                                               globalBakeFrame = 0;
+                                               globalBakeState = -1;
+                                               simAborted = 1;
+                                               BLI_unlock_thread(LOCK_CUSTOM1);
+                                               break;
+                                       }
+                               } 
+
+                               // redraw the 3D for showing progress once in a while...
+                               if(lastRedraw!=globalBakeFrame) {
+#if 0                                  
+                                       ScrArea *sa;
+                                       scene->r.cfra = startFrame+globalBakeFrame;
+                                       lastRedraw = globalBakeFrame;
+                                       ED_update_for_newframe(C, 0);
+                                       sa= G.curscreen->areabase.first;
+                                       while(sa) {
+                                               if(sa->spacetype == SPACE_VIEW3D) { scrarea_do_windraw(sa); }
+                                               sa= sa->next;   
+                                       } 
+                                       screen_swapbuffers();
+#endif
+                               } // redraw
+                       }
+                       end_progress_bar();
+               }
+               BLI_end_threads(&threads);
+       } // El'Beem API init, thread creation 
+       // --------------------------------------------------------------------------------------------
+       else
+       { // write config file to be run with command line simulator
+               pupmenu("Fluidsim Bake Message%t|Config file export not supported.%x0");
+       } // config file export done!
+
+       // --------------------------------------------------------------------------------------------
+       FS_FREE_CHANNELS;
+
+       // go back to "current" blender time
+       waitcursor(0);
+       
+       if(globalBakeState >= 0)
+       {
+               if(domainSettings)
+                       domainSettings->lastgoodframe = startFrame+globalBakeFrame;
+       }
+       
+       scene->r.cfra = origFrame;
+       ED_update_for_newframe(C, 0);
+
+       if(!simAborted) {
+               char fsmessage[512];
+               char elbeemerr[256];
+               strcpy(fsmessage,"Fluidsim Bake Error: ");
+               // check if some error occurred
+               if(globalBakeState==-2) {
+                       strcat(fsmessage,"Failed to initialize [Msg: ");
+
+                       elbeemGetErrorString(elbeemerr);
+                       strcat(fsmessage,elbeemerr);
+
+                       strcat(fsmessage,"] |OK%x0");
+                       pupmenu(fsmessage);
+               } // init error
+       }
+       
+       // elbeemFree();
+}
+
+void fluidsimFreeBake(struct Object *ob)
+{
+       /* not implemented yet */
+}
+
+
+#else /* DISABLE_ELBEEM */
+
+/* compile dummy functions for disabled fluid sim */
+
+FluidsimSettings *fluidsimSettingsNew(struct Object *srcob) {
+       return NULL;
+}
+
+void fluidsimSettingsFree(FluidsimSettings *fss) {
+}
+
+FluidsimSettings* fluidsimSettingsCopy(FluidsimSettings *fss) {
+       return NULL;
+}
+
+/* only compile dummy functions */
+void fluidsimBake(bContext *C, struct Object *ob)
+}
+
+void fluidsimFreeBake(struct Object *ob) {
+}
+
+#endif /* DISABLE_ELBEEM */
+
diff --git a/source/blender/editors/physics/physics_intern.h b/source/blender/editors/physics/physics_intern.h
new file mode 100644 (file)
index 0000000..9ca4f86
--- /dev/null
@@ -0,0 +1,40 @@
+/* BIF_editparticle.h
+ *
+ *
+ * $Id: BIF_editparticle.h $
+ *
+ * ***** BEGIN GPL LICENSE BLOCK *****
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version. The Blender
+ * Foundation also sells licenses for use in proprietary software under
+ * the Blender License.  See http://www.blender.org/BL/ for information
+ * about this.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ *
+ * The Original Code is Copyright (C) 2007 by Janne Karhu.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef ED_PHYSICS_INTERN_H
+#define ED_PHYSICS_INTERN_H
+
+
+#endif /* ED_PHYSICS_INTERN_H */
+
index fee766ee3ffcd7ddad936e98af6b566dcc1a80a6..8430e4b874bb93eedd5b06666b5870e343b2bd06 100644 (file)
@@ -55,6 +55,7 @@
 #include "DNA_modifier_types.h"
 #include "DNA_object_types.h"
 #include "DNA_object_force.h"
+#include "DNA_object_fluidsim.h"
 #include "DNA_particle_types.h"
 #include "DNA_space_types.h"
 #include "DNA_scene_types.h"
@@ -62,8 +63,6 @@
 #include "DNA_userdef_types.h"
 #include "DNA_view3d_types.h"
 #include "DNA_world_types.h"
-// FSPARTICLE
-#include "DNA_object_fluidsim.h"
 
 #include "BLI_blenlib.h"
 #include "BLI_arithb.h"
@@ -99,6 +98,7 @@
 #include "GPU_material.h"
 #include "GPU_extensions.h"
 
+#include "ED_editparticle.h"
 #include "ED_mesh.h"
 #include "ED_types.h"
 #include "ED_util.h"
@@ -1114,14 +1114,12 @@ static void drawlattice__point(Lattice *lt, DispList *dl, int u, int v, int w, i
        int index = ((w*lt->pntsv + v)*lt->pntsu) + u;
 
        if(use_wcol) {
-#if 0
-               XXX
                float col[3];
                MDeformWeight *mdw= get_defweight (lt->dvert+index, use_wcol-1);
                
                weight_to_rgb(mdw?mdw->weight:0.0f, col, col+1, col+2);
                glColor3fv(col);
-#endif
+
        }
        
        if (dl) {
@@ -2364,7 +2362,7 @@ static void draw_mesh_fancy(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base
 static int draw_mesh_object(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base *base, int dt, int flag)
 {
        Object *ob= base->object;
-       Object *obedit= scene->obedit; // XXX hrumf, see below
+       Object *obedit= scene->obedit;
        Mesh *me= ob->data;
        EditMesh *em= me->edit_mesh;
        int do_alpha_pass= 0, drawlinked= 0, retval= 0, glsl, check_alpha;
@@ -3508,7 +3506,7 @@ static void draw_particle_edit(Scene *scene, View3D *v3d, RegionView3D *rv3d, Ob
        ParticleData *pa;
        ParticleCacheKey **path;
        ParticleEditKey *key;
-       ParticleEditSettings *pset = NULL; // XXX PE_settings();
+       ParticleEditSettings *pset = PE_settings(scene);
        int i, k, totpart = psys->totpart, totchild=0, timed = pset->draw_timed;
        char nosel[4], sel[4];
        float sel_col[3];
@@ -3517,7 +3515,7 @@ static void draw_particle_edit(Scene *scene, View3D *v3d, RegionView3D *rv3d, Ob
 
        /* create path and child path cache if it doesn't exist already */
        if(psys->pathcache==0){
-// XXX         PE_hide_keys_time(psys,CFRA);
+               PE_hide_keys_time(scene, psys,CFRA);
                psys_cache_paths(scene, ob, psys, CFRA,0);
        }
        if(psys->pathcache==0)
@@ -4594,7 +4592,6 @@ static void drawSolidSelect(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base
 
 static void drawWireExtra(Scene *scene, RegionView3D *rv3d, Object *ob) 
 {
-       // XXX scene->obedit warning
        if(ob!=scene->obedit && (ob->flag & SELECT)) {
                if(ob==OBACT) {
                        if(ob->flag & OB_FROMGROUP) UI_ThemeColor(TH_GROUP_ACTIVE);
@@ -4726,7 +4723,6 @@ void draw_object(Scene *scene, ARegion *ar, View3D *v3d, Base *base, int flag)
 
        ob= base->object;
 
-       /* XXX ermfh... */
        if (ob!=scene->obedit) {
                if (ob->restrictflag & OB_RESTRICT_VIEW) 
                        return;
@@ -5087,7 +5083,7 @@ void draw_object(Scene *scene, ARegion *ar, View3D *v3d, Base *base, int flag)
                        draw_new_particle_system(scene, v3d, rv3d, base, psys, dt);
                
                if(G.f & G_PARTICLEEDIT && ob==OBACT) {
-                       psys= NULL; // XXX PE_get_current(ob);
+                       psys= PE_get_current(ob);
                        if(psys && !scene->obedit && psys_in_edit_mode(scene, psys))
                                draw_particle_edit(scene, v3d, rv3d, ob, psys, dt);
                }
index 3bece21acf14aa1b6c770b30a0b7b3ba4d5a96b1..1e1f235298da75fb1828827546043aac19d051b5 100644 (file)
@@ -70,6 +70,7 @@
 #include "RNA_access.h"
 #include "RNA_define.h"
 
+#include "ED_editparticle.h"
 #include "ED_space_api.h"
 #include "ED_screen.h"
 #include "ED_types.h"
@@ -966,7 +967,7 @@ static int viewcenter_exec(bContext *C, wmOperator *op) /* like a localview with
 // XXX         ok= minmax_tface(min, max);
        }
        else if (G.f & G_PARTICLEEDIT) {
-// XXX         ok= PE_minmax(min, max);
+               ok= PE_minmax(scene, min, max);
        }
        else {
                Base *base= FIRSTBASE;
index 95dd74893924199ac9a12e116dbf1dff4a3ee370..df477ac7736edb1da9db91b123cd5f037141539e 100644 (file)
@@ -63,6 +63,7 @@
 #include "BKE_utildefines.h" /* for VECCOPY */
 
 #include "ED_armature.h"
+#include "ED_editparticle.h"
 #include "ED_object.h"
 #include "ED_mesh.h"
 #include "ED_util.h"
@@ -144,7 +145,7 @@ void ED_view3d_exit_paint_modes(bContext *C)
 
 //     if(G.f & G_TEXTUREPAINT) set_texturepaint();
 //     if(G.f & G_SCULPTMODE) set_sculptmode();
-//     if(G.f & G_PARTICLEEDIT) PE_set_particle_edit();
+       if(G.f & G_PARTICLEEDIT) PE_set_particle_edit(CTX_data_scene(C));
        
        G.f &= ~(G_VERTEXPAINT+G_TEXTUREPAINT+G_WEIGHTPAINT+G_SCULPTMODE+G_PARTICLEEDIT);
 }
@@ -4969,14 +4970,14 @@ static uiBlock *view3d_faceselmenu(bContext *C, uiMenuBlockHandle *handle, void
 
 void do_view3d_select_particlemenu(bContext *C, void *arg, int event)
 {
-#if 0
+
        /* events >= 6 are registered bpython scripts */
 #ifndef DISABLE_PYTHON
-       if (event >= 6) BPY_menu_do_python(PYMENU_FACESELECT, event - 6);
+// XXX if (event >= 6) BPY_menu_do_python(PYMENU_FACESELECT, event - 6);
 #endif
        switch(event) {
                case 0:
-                       PE_borderselect();
+                       // XXX PE_borderselect();
                        break;
                case 1:
                        PE_deselectall();
@@ -4997,8 +4998,6 @@ void do_view3d_select_particlemenu(bContext *C, void *arg, int event)
                        PE_select_linked();
                        break;
        }
-       allqueue(REDRAWVIEW3D, 0);
-#endif
 }
 
 static uiBlock *view3d_select_particlemenu(bContext *C, uiMenuBlockHandle *handle, void *arg_unused)
@@ -5047,7 +5046,7 @@ static uiBlock *view3d_select_particlemenu(bContext *C, uiMenuBlockHandle *handl
 
 void do_view3d_particle_showhidemenu(bContext *C, void *arg, int event)
 {
-#if 0
+
        switch(event) {
        case 1: /* show hidden */
                PE_hide(0);
@@ -5059,8 +5058,6 @@ void do_view3d_particle_showhidemenu(bContext *C, void *arg, int event)
                PE_hide(1);
                break;
        }
-       allqueue(REDRAWVIEW3D, 0);
-#endif
 }
 
 static uiBlock *view3d_particle_showhidemenu(bContext *C, uiMenuBlockHandle *handle, void *arg_unused)
@@ -5124,7 +5121,7 @@ uiBlock *view3d_particlemenu(bContext *C, uiMenuBlockHandle *handle, void *arg_u
 {
        Scene *scene= CTX_data_scene(C);
        uiBlock *block;
-// XXX ParticleEditSettings *pset= PE_settings();
+       ParticleEditSettings *pset= PE_settings(scene);
        short yco= 0, menuwidth= 120;
        
        block= uiBeginBlock(C, handle->region, "view3d_particlemenu", UI_EMBOSSP, UI_HELV);
@@ -5133,7 +5130,7 @@ uiBlock *view3d_particlemenu(bContext *C, uiMenuBlockHandle *handle, void *arg_u
        uiDefIconTextBut(block, BUTM, 1, ICON_MENU_PANEL, "Particle Edit Properties|N", 0, yco-=20, menuwidth, 19, NULL, 0.0, 0.0, 0, 1, "");
        uiDefBut(block, SEPR, 0, "", 0, yco-=6, menuwidth, 6, NULL, 0.0, 0.0, 0, 0, "");
 
-//     uiDefIconTextBut(block, BUTM, 1, (pset->flag & PE_X_MIRROR)? ICON_CHECKBOX_HLT: ICON_CHECKBOX_DEHLT, "X-Axis Mirror Editing", 0, yco-=20, menuwidth, 19, NULL, 0.0, 0.0, 1, 6, "");
+       uiDefIconTextBut(block, BUTM, 1, (pset->flag & PE_X_MIRROR)? ICON_CHECKBOX_HLT: ICON_CHECKBOX_DEHLT, "X-Axis Mirror Editing", 0, yco-=20, menuwidth, 19, NULL, 0.0, 0.0, 1, 6, "");
        
        uiDefIconTextBut(block, BUTM, 1, ICON_BLANK1, "Mirror|Ctrl M", 0, yco-=20, menuwidth, 19, NULL, 0.0, 0.0, 1, 5, "");
        uiDefBut(block, SEPR, 0, "", 0, yco-=6, menuwidth, 6, NULL, 0.0, 0.0, 0, 0, "");
@@ -5406,7 +5403,7 @@ static void do_view3d_buttons(bContext *C, void *arg, int event)
                                ED_view3d_exit_paint_modes(C);
                                if(obedit) ED_object_exit_editmode(C, EM_FREEDATA|EM_FREEUNDO|EM_WAITCURSOR);   /* exit editmode and undo */
 
-// XXX                         PE_set_particle_edit();
+                               PE_set_particle_edit(scene);
                        }
                }
                allqueue(REDRAWVIEW3D, 1);
index 05f83d51af724daae2a99e7cc77f8563d2cf9ee4..e5233349ac0513f088e162e04016f590ab7c8a3b 100644 (file)
@@ -43,14 +43,6 @@ struct wmWindowManager;
 struct EditMesh;
 struct ViewContext;
 
-typedef struct ViewDepths {
-       unsigned short w, h;
-       float *depths;
-       double depth_range[2];
-       
-       char damaged;
-} ViewDepths;
-
 /* drawing flags: */
 #define DRAW_PICKING   1
 #define DRAW_CONSTCOLOR        2
@@ -61,9 +53,6 @@ typedef struct ViewDepths {
 
 #define V3D_SELECT_MOUSE       1
 
-/* project short */
-#define IS_CLIPPED        12000
-
 /* view3d_header.c */
 void view3d_header_buttons(const struct bContext *C, struct ARegion *ar);
 
index ef29e21d047d528e34b8fe19bba3452e55c33f85..49d941f3d362010396c66fbd4e0bc6aa83c8408f 100644 (file)
@@ -76,6 +76,7 @@
 
 #include "ED_armature.h"
 #include "ED_curve.h"
+#include "ED_editparticle.h"
 #include "ED_mesh.h"
 #include "ED_object.h"
 #include "ED_screen.h"
@@ -596,7 +597,6 @@ static void do_lasso_select_armature(ViewContext *vc, short mcords[][2], short m
                        else ebone->flag &= ~(BONE_ACTIVE|BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
                }
        }
-       // XXX countall();      /* abused for flushing selection!!!! */
 }
 
 static void do_lasso_select_facemode(ViewContext *vc, short mcords[][2], short moves, short select)
@@ -658,8 +658,8 @@ void view3d_lasso_select(ViewContext *vc, short mcords[][2], short moves, short
                        do_lasso_select_facemode(vc, mcords, moves, select);
                else if(G.f & (G_VERTEXPAINT|G_TEXTUREPAINT|G_WEIGHTPAINT))
                        ;
-// XX          else if(G.f & G_PARTICLEEDIT)
-//                     PE_do_lasso_select(mcords, moves, select);
+               else if(G.f & G_PARTICLEEDIT)
+                       PE_do_lasso_select(vc, mcords, moves, select);
                else  
                        do_lasso_select_objects(vc, mcords, moves, select);
        }
@@ -1306,7 +1306,7 @@ static int view3d_borderselect_exec(bContext *C, wmOperator *op)
                return OPERATOR_FINISHED;
        }
        else if(obedit==NULL && (G.f & G_PARTICLEEDIT)) {
-// XXX         PE_borderselect();
+               PE_borderselect(&vc, &rect, (val==LEFTMOUSE));
                return OPERATOR_FINISHED;
        }
        
@@ -1321,7 +1321,6 @@ static int view3d_borderselect_exec(bContext *C, wmOperator *op)
                }
                else if(ELEM(obedit->type, OB_CURVE, OB_SURF)) {
                        do_nurbs_box_select(&vc, &rect, val==LEFTMOUSE);
-//                     allqueue(REDRAWVIEW3D, 0);
                }
                else if(obedit->type==OB_MBALL) {
                        hits= view3d_opengl_select(&vc, buffer, MAXPICKBUF, &rect);
@@ -1568,7 +1567,7 @@ void VIEW3D_OT_select(wmOperatorType *ot)
 
 static void mesh_circle_doSelectVert(void *userData, EditVert *eve, int x, int y, int index)
 {
-       struct { short select, mval[2]; float radius; } *data = userData;
+       struct {ViewContext *vc; short select, mval[2]; float radius; } *data = userData;
        int mx = x - data->mval[0], my = y - data->mval[1];
        float r = sqrt(mx*mx + my*my);
 
@@ -1578,7 +1577,7 @@ static void mesh_circle_doSelectVert(void *userData, EditVert *eve, int x, int y
 }
 static void mesh_circle_doSelectEdge(void *userData, EditEdge *eed, int x0, int y0, int x1, int y1, int index)
 {
-       struct { short select, mval[2]; float radius; } *data = userData;
+       struct {ViewContext *vc; short select, mval[2]; float radius; } *data = userData;
 
        if (edge_inside_circle(data->mval[0], data->mval[1], (short) data->radius, x0, y0, x1, y1)) {
                EM_select_edge(eed, data->select);
@@ -1586,13 +1585,12 @@ static void mesh_circle_doSelectEdge(void *userData, EditEdge *eed, int x0, int
 }
 static void mesh_circle_doSelectFace(void *userData, EditFace *efa, int x, int y, int index)
 {
-       struct { short select, mval[2]; float radius; } *data = userData;
+       struct {ViewContext *vc; short select, mval[2]; float radius; } *data = userData;
        int mx = x - data->mval[0], my = y - data->mval[1];
        float r = sqrt(mx*mx + my*my);
-       EditMesh *em= NULL; // XXX
        
        if (r<=data->radius) {
-               EM_select_face_fgon(em, efa, data->select);
+               EM_select_face_fgon(data->vc->em, efa, data->select);
        }
 }
 
@@ -1615,7 +1613,7 @@ static void mesh_circle_select(ViewContext *vc, int selecting, short *mval, floa
                }
        }
        else {
-               struct { short select, mval[2]; float radius; } data;
+               struct {ViewContext *vc; short select, mval[2]; float radius; } data;
                
                bbsel= EM_init_backbuf_circle(vc, mval[0], mval[1], (short)(rad+1.0));
                vc->em= ((Mesh *)vc->obedit->data)->edit_mesh;
@@ -1657,7 +1655,7 @@ static void mesh_circle_select(ViewContext *vc, int selecting, short *mval, floa
 
 static void nurbscurve_circle_doSelect(void *userData, Nurb *nu, BPoint *bp, BezTriple *bezt, int beztindex, int x, int y)
 {
-       struct { short select, mval[2]; float radius; } *data = userData;
+       struct {ViewContext *vc; short select, mval[2]; float radius; } *data = userData;
        int mx = x - data->mval[0], my = y - data->mval[1];
        float r = sqrt(mx*mx + my*my);
 
@@ -1677,7 +1675,7 @@ static void nurbscurve_circle_doSelect(void *userData, Nurb *nu, BPoint *bp, Bez
 }
 static void nurbscurve_circle_select(ViewContext *vc, int selecting, short *mval, float rad)
 {
-       struct { short select, mval[2]; float radius; } data;
+       struct {ViewContext *vc; short select, mval[2]; float radius; } data;
 
        /* set vc-> edit data */
        
@@ -1692,7 +1690,7 @@ static void nurbscurve_circle_select(ViewContext *vc, int selecting, short *mval
 
 static void latticecurve_circle_doSelect(void *userData, BPoint *bp, int x, int y)
 {
-       struct { short select, mval[2]; float radius; } *data = userData;
+       struct {ViewContext *vc; short select, mval[2]; float radius; } *data = userData;
        int mx = x - data->mval[0], my = y - data->mval[1];
        float r = sqrt(mx*mx + my*my);
 
@@ -1702,7 +1700,7 @@ static void latticecurve_circle_doSelect(void *userData, BPoint *bp, int x, int
 }
 static void lattice_circle_select(ViewContext *vc, int selecting, short *mval, float rad)
 {
-       struct { short select, mval[2]; float radius; } data;
+       struct {ViewContext *vc; short select, mval[2]; float radius; } data;
 
        /* set vc-> edit data */
        
index 29245ab5ce4c8749f6f1bb53ddfae0bca5f1c26b..4b2a8769f03c8b433f3efa4f985b4a00d09aa453 100644 (file)
 //#include "BIF_space.h"
 //#include "BIF_toolbox.h"
 
-#include "ED_armature.h"
-#include "ED_types.h"
 #include "ED_anim_api.h"
+#include "ED_armature.h"
+#include "ED_editparticle.h"
 #include "ED_keyframing.h"
 #include "ED_keyframes_edit.h"
-#include "ED_view3d.h"
 #include "ED_mesh.h"
+#include "ED_types.h"
+#include "ED_view3d.h"
 
 #include "UI_view2d.h"
 
@@ -1617,7 +1618,7 @@ static void createTransParticleVerts(bContext *C, TransInfo *t)
        Object *ob = OBACT;
        ParticleSystem *psys = PE_get_current(ob);
        ParticleSystemModifierData *psmd = NULL;
-       ParticleEditSettings *pset = PE_settings();
+       ParticleEditSettings *pset = PE_settings(t->scene);
        ParticleData *pa = NULL;
        ParticleEdit *edit;
        ParticleEditKey *key;
@@ -1762,7 +1763,7 @@ void flushTransParticles(TransInfo *t)
                }
        }
 
-       PE_update_object(OBACT, 1);
+       PE_update_object(scene, OBACT, 1);
 #endif
 }
 
@@ -3535,7 +3536,6 @@ static void createTransSeqData(bContext *C, TransInfo *t)
        Sequence *seq;
 
        int count=0;
-       float cfra;
 
 
 
@@ -4133,10 +4133,10 @@ void special_aftertrans_update(TransInfo *t)
                        }
                }
                else if (ac.datatype == ANIMCONT_SHAPEKEY) {
+#if 0 // XXX old animation system
                        /* fix up the Ipocurves and redraw stuff */
                        Key *key= (Key *)ac.data;
                        
-#if 0 // XXX old animation system
                        if (key->ipo) {
                                if ( (saction->flag & SACTION_NOTRANSKEYCULL)==0 && 
                                     ((cancelled == 0) || (duplicate)) )
@@ -4314,9 +4314,6 @@ void special_aftertrans_update(TransInfo *t)
 
 static void createTransObject(bContext *C, TransInfo *t)
 {
-       Scene *sce = CTX_data_scene(C);
-       View3D *v3d = t->view;
-       
        TransData *td = NULL;
        TransDataExtension *tx;
 //     IpoKey *ik;
index 138050d6b9c27e7a25f82ec9dc25d3b1cef95ff1..0d36d63a1d0128f1ef76c54d76c3530654c9b755 100644 (file)
 
 #include "BKE_utildefines.h"
 
+#include "ED_armature.h"
+#include "ED_editparticle.h"
+#include "ED_curve.h"
 #include "ED_mesh.h"
+#include "ED_object.h"
 #include "ED_screen.h"
 #include "ED_util.h"
 
 /* ***************** generic undo system ********************* */
 
 /* ********* XXX **************** */
-static void undo_push_curve() {}
-static void undo_push_font() {}
 static void undo_push_mball() {}
-static void undo_push_lattice() {}
-static void undo_push_armature() {}
-static void PE_undo_push() {}
-static void PE_undo() {}
-static void PE_redo() {}
-static void PE_undo_menu() {}
 static void undo_imagepaint_step() {}
 static void sound_initialize_sounds() {}
 /* ********* XXX **************** */
@@ -90,20 +86,20 @@ void ED_undo_push(bContext *C, char *str)
                if(obedit->type==OB_MESH)
                        undo_push_mesh(C, str);
                else if ELEM(obedit->type, OB_CURVE, OB_SURF)
-                       undo_push_curve(str);
+                       undo_push_curve(C, str);
                else if (obedit->type==OB_FONT)
-                       undo_push_font(str);
+                       undo_push_font(C, str);
                else if (obedit->type==OB_MBALL)
                        undo_push_mball(str);
                else if (obedit->type==OB_LATTICE)
-                       undo_push_lattice(str);
+                       undo_push_lattice(C, str);
                else if (obedit->type==OB_ARMATURE)
-                       undo_push_armature(str);
+                       undo_push_armature(C, str);
        }
        else if(G.f & G_PARTICLEEDIT) {
                if (U.undosteps == 0) return;
                
-               PE_undo_push(str);
+               PE_undo_push(CTX_data_scene(C), str);
        }
        else {
                if(U.uiflag & USER_GLOBALUNDO) 
@@ -134,9 +130,9 @@ static int ed_undo_step(bContext *C, wmOperator *op, int step)
                }
                else if(G.f & G_PARTICLEEDIT) {
                        if(step==1)
-                               PE_undo();
+                               PE_undo(CTX_data_scene(C));
                        else
-                               PE_redo();
+                               PE_redo(CTX_data_scene(C));
                }
                else {
                        do_glob_undo= 1;
@@ -178,7 +174,7 @@ void ED_undo_menu(bContext *C)
        }
        else {
                if(G.f & G_PARTICLEEDIT)
-                       PE_undo_menu();
+                       PE_undo_menu(CTX_data_scene(C));
                else if(U.uiflag & USER_GLOBALUNDO) {
                        char *menu= BKE_undo_menu_string();
                        if(menu) {
index b9b7f83636f30ec7fad17460acf5a0beb962ba7a..12903f131befd2a9cbe534b3d96cf94ca1f40689 100644 (file)
@@ -594,7 +594,7 @@ int WM_gesture_circle_invoke(bContext *C, wmOperator *op, wmEvent *event)
        return OPERATOR_RUNNING_MODAL;
 }
 
-static void gesture_circle_apply(bContext *C, wmOperator *op, int event_type)
+static void gesture_circle_apply(bContext *C, wmOperator *op)
 {
        wmGesture *gesture= op->customdata;
        rcti *rect= gesture->customdata;
@@ -603,8 +603,6 @@ static void gesture_circle_apply(bContext *C, wmOperator *op, int event_type)
        RNA_int_set(op->ptr, "x", rect->xmin);
        RNA_int_set(op->ptr, "y", rect->ymin);
        RNA_int_set(op->ptr, "radius", rect->xmax);
-       if( RNA_struct_find_property(op->ptr, "event_type") )
-               RNA_int_set(op->ptr, "event_type", event_type);
        
        if(op->type->exec)
                op->type->exec(C, op);
@@ -627,7 +625,7 @@ int WM_gesture_circle_modal(bContext *C, wmOperator *op, wmEvent *event)
                        wm_gesture_tag_redraw(C);
                        
                        if(gesture->mode)
-                               gesture_circle_apply(C, op, event->type);
+                               gesture_circle_apply(C, op);
 
                        break;
                case WHEELUPMOUSE:
@@ -646,9 +644,14 @@ int WM_gesture_circle_modal(bContext *C, wmOperator *op, wmEvent *event)
                                wm_gesture_end(C, op);
                                return OPERATOR_FINISHED;
                        }
-                       else
+                       else {
+                               if( RNA_struct_find_property(op->ptr, "event_type") )
+                                       RNA_int_set(op->ptr, "event_type", event->type);
+                               
+                               /* apply first click */
+                               gesture_circle_apply(C, op);
                                gesture->mode= 1;
-
+                       }
                        break;
                case ESCKEY:
                        wm_gesture_end(C, op);