merge with trunk at r31523
[blender.git] / source / blender / blenkernel / intern / boids.c
1 /* boids.c
2  *
3  *
4  * $Id$
5  *
6  * ***** BEGIN GPL LICENSE BLOCK *****
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21  *
22  * The Original Code is Copyright (C) 2009 by Janne Karhu.
23  * All rights reserved.
24  *
25  * The Original Code is: all of this file.
26  *
27  * Contributor(s): none yet.
28  *
29  * ***** END GPL LICENSE BLOCK *****
30  */
31
32 #include <string.h>
33 #include <math.h>
34
35 #include "MEM_guardedalloc.h"
36
37 #include "DNA_object_force.h"
38 #include "DNA_scene_types.h"
39
40 #include "BLI_rand.h"
41 #include "BLI_math.h"
42 #include "BLI_blenlib.h"
43 #include "BLI_kdtree.h"
44 #include "BKE_collision.h"
45 #include "BKE_effect.h"
46 #include "BKE_boids.h"
47 #include "BKE_particle.h"
48 #include "BKE_utildefines.h"
49 #include "BKE_modifier.h"
50
51 #include "RNA_enum_types.h"
52
53 typedef struct BoidValues {
54         float max_speed, max_acc;
55         float max_ave, min_speed;
56         float personal_space, jump_speed;
57 } BoidValues;
58
59 static int apply_boid_rule(BoidBrainData *bbd, BoidRule *rule, BoidValues *val, ParticleData *pa, float fuzziness);
60
61 static int rule_none(BoidRule *rule, BoidBrainData *data, BoidValues *val, ParticleData *pa)
62 {
63         return 0;
64 }
65
66 static int rule_goal_avoid(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, ParticleData *pa)
67 {
68         BoidRuleGoalAvoid *gabr = (BoidRuleGoalAvoid*) rule;
69         BoidSettings *boids = bbd->part->boids;
70         BoidParticle *bpa = pa->boid;
71         EffectedPoint epoint;
72         ListBase *effectors = bbd->sim->psys->effectors;
73         EffectorCache *cur, *eff = NULL;
74         EffectorCache temp_eff;
75         EffectorData efd, cur_efd;
76         float mul = (rule->type == eBoidRuleType_Avoid ? 1.0 : -1.0);
77         float priority = 0.0f, len = 0.0f;
78         int ret = 0;
79
80         pd_point_from_particle(bbd->sim, pa, &pa->state, &epoint);
81
82         /* first find out goal/predator with highest priority */
83         if(effectors) for(cur = effectors->first; cur; cur=cur->next) {
84                 Object *eob = cur->ob;
85                 PartDeflect *pd = cur->pd;
86
87                 if(gabr->ob && (rule->type != eBoidRuleType_Goal || gabr->ob != bpa->ground)) {
88                         if(gabr->ob == eob) {
89                                 /* TODO: effectors with multiple points */
90                                 if(get_effector_data(cur, &efd, &epoint, 0)) {
91                                         if(cur->pd && cur->pd->forcefield == PFIELD_BOID)
92                                                 priority = mul * pd->f_strength * effector_falloff(cur, &efd, &epoint, bbd->part->effector_weights);
93                                         else
94                                                 priority = 1.0;
95
96                                         eff = cur;
97                                 }
98                                 break;
99                         }
100                 }
101                 else if(rule->type == eBoidRuleType_Goal && eob == bpa->ground)
102                         ; /* skip current object */
103                 else if(pd->forcefield == PFIELD_BOID && mul * pd->f_strength > 0.0f && get_effector_data(cur, &cur_efd, &epoint, 0)) {
104                         float temp = mul * pd->f_strength * effector_falloff(cur, &cur_efd, &epoint, bbd->part->effector_weights);
105
106                         if(temp == 0.0f)
107                                 ; /* do nothing */
108                         else if(temp > priority) {
109                                 priority = temp;
110                                 eff = cur;
111                                 efd = cur_efd;
112                                 len = efd.distance;
113                         }
114                         /* choose closest object with same priority */
115                         else if(temp == priority && efd.distance < len) {
116                                 eff = cur;
117                                 efd = cur_efd;
118                                 len = efd.distance;
119                         }
120                 }
121         }
122
123         /* if the object doesn't have effector data we have to fake it */
124         if(eff == NULL && gabr->ob) {
125                 memset(&temp_eff, 0, sizeof(EffectorCache));
126                 temp_eff.ob = gabr->ob;
127                 temp_eff.scene = bbd->sim->scene;
128                 eff = &temp_eff;
129                 get_effector_data(eff, &efd, &epoint, 0);
130                 priority = 1.0f;
131         }
132
133         /* then use that effector */
134         if(priority > (rule->type==eBoidRuleType_Avoid ? gabr->fear_factor : 0.0f)) { /* with avoid, factor is "fear factor" */
135                 Object *eob = eff->ob;
136                 PartDeflect *pd = eff->pd;
137                 float surface = (pd && pd->shape == PFIELD_SHAPE_SURFACE) ? 1.0f : 0.0f;
138
139                 if(gabr->options & BRULE_GOAL_AVOID_PREDICT) {
140                         /* estimate future location of target */
141                         get_effector_data(eff, &efd, &epoint, 1);
142
143                         mul_v3_fl(efd.vel, efd.distance / (val->max_speed * bbd->timestep));
144                         add_v3_v3(efd.loc, efd.vel);
145                         sub_v3_v3v3(efd.vec_to_point, pa->prev_state.co, efd.loc);
146                         efd.distance = len_v3(efd.vec_to_point);
147                 }
148
149                 if(rule->type == eBoidRuleType_Goal && boids->options & BOID_ALLOW_CLIMB && surface!=0.0f) {
150                         if(!bbd->goal_ob || bbd->goal_priority < priority) {
151                                 bbd->goal_ob = eob;
152                                 VECCOPY(bbd->goal_co, efd.loc);
153                                 VECCOPY(bbd->goal_nor, efd.nor);
154                         }
155                 }
156                 else if(rule->type == eBoidRuleType_Avoid && bpa->data.mode == eBoidMode_Climbing &&
157                         priority > 2.0f * gabr->fear_factor) {
158                         /* detach from surface and try to fly away from danger */
159                         negate_v3_v3(efd.vec_to_point, bpa->gravity);
160                 }
161
162                 VECCOPY(bbd->wanted_co, efd.vec_to_point);
163                 mul_v3_fl(bbd->wanted_co, mul);
164
165                 bbd->wanted_speed = val->max_speed * priority;
166
167                 /* with goals factor is approach velocity factor */
168                 if(rule->type == eBoidRuleType_Goal && boids->landing_smoothness > 0.0f) {
169                         float len2 = 2.0f*len_v3(pa->prev_state.vel);
170
171                         surface *= pa->size * boids->height;
172
173                         if(len2 > 0.0f && efd.distance - surface < len2) {
174                                 len2 = (efd.distance - surface)/len2;
175                                 bbd->wanted_speed *= pow(len2, boids->landing_smoothness);
176                         }
177                 }
178
179                 ret = 1;
180         }
181
182         return ret;
183 }
184
185 static int rule_avoid_collision(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, ParticleData *pa)
186 {
187         BoidRuleAvoidCollision *acbr = (BoidRuleAvoidCollision*) rule;
188         KDTreeNearest *ptn = NULL;
189         ParticleTarget *pt;
190         BoidParticle *bpa = pa->boid;
191         ColliderCache *coll;
192         float vec[3] = {0.0f, 0.0f, 0.0f}, loc[3] = {0.0f, 0.0f, 0.0f};
193         float co1[3], vel1[3], co2[3], vel2[3];
194         float  len, t, inp, t_min = 2.0f;
195         int n, neighbors = 0, nearest = 0;
196         int ret = 0;
197
198         //check deflector objects first
199         if(acbr->options & BRULE_ACOLL_WITH_DEFLECTORS && bbd->sim->colliders) {
200                 ParticleCollision col;
201                 BVHTreeRayHit hit;
202                 float radius = val->personal_space * pa->size, ray_dir[3];
203
204                 VECCOPY(col.co1, pa->prev_state.co);
205                 add_v3_v3v3(col.co2, pa->prev_state.co, pa->prev_state.vel);
206                 sub_v3_v3v3(ray_dir, col.co2, col.co1);
207                 mul_v3_fl(ray_dir, acbr->look_ahead);
208                 col.t = 0.0f;
209                 hit.index = -1;
210                 hit.dist = col.ray_len = len_v3(ray_dir);
211
212                 /* find out closest deflector object */
213                 for(coll = bbd->sim->colliders->first; coll; coll=coll->next) {
214                         /* don't check with current ground object */
215                         if(coll->ob == bpa->ground)
216                                 continue;
217
218                         col.ob = coll->ob;
219                         col.md = coll->collmd;
220
221                         if(col.md && col.md->bvhtree)
222                                 BLI_bvhtree_ray_cast(col.md->bvhtree, col.co1, ray_dir, radius, &hit, particle_intersect_face, &col);
223                 }
224                 /* then avoid that object */
225                 if(hit.index>=0) {
226                         t = hit.dist/col.ray_len;
227
228                         /* avoid head-on collision */
229                         if(dot_v3v3(col.nor, pa->prev_state.ave) < -0.99) {
230                                 /* don't know why, but uneven range [0.0,1.0] */
231                                 /* works much better than even [-1.0,1.0] */
232                                 bbd->wanted_co[0] = BLI_frand();
233                                 bbd->wanted_co[1] = BLI_frand();
234                                 bbd->wanted_co[2] = BLI_frand();
235                         }
236                         else {
237                                 VECCOPY(bbd->wanted_co, col.nor);
238                         }
239
240                         mul_v3_fl(bbd->wanted_co, (1.0f - t) * val->personal_space * pa->size);
241
242                         bbd->wanted_speed = sqrt(t) * len_v3(pa->prev_state.vel);
243
244                         return 1;
245                 }
246         }
247
248         //check boids in own system
249         if(acbr->options & BRULE_ACOLL_WITH_BOIDS)
250         {
251                 neighbors = BLI_kdtree_range_search(bbd->sim->psys->tree, acbr->look_ahead * len_v3(pa->prev_state.vel), pa->prev_state.co, pa->prev_state.ave, &ptn);
252                 if(neighbors > 1) for(n=1; n<neighbors; n++) {
253                         VECCOPY(co1, pa->prev_state.co);
254                         VECCOPY(vel1, pa->prev_state.vel);
255                         VECCOPY(co2, (bbd->sim->psys->particles + ptn[n].index)->prev_state.co);
256                         VECCOPY(vel2, (bbd->sim->psys->particles + ptn[n].index)->prev_state.vel);
257
258                         sub_v3_v3v3(loc, co1, co2);
259
260                         sub_v3_v3v3(vec, vel1, vel2);
261                         
262                         inp = dot_v3v3(vec,vec);
263
264                         /* velocities not parallel */
265                         if(inp != 0.0f) {
266                                 t = -dot_v3v3(loc, vec)/inp;
267                                 /* cpa is not too far in the future so investigate further */
268                                 if(t > 0.0f && t < t_min) {
269                                         VECADDFAC(co1, co1, vel1, t);
270                                         VECADDFAC(co2, co2, vel2, t);
271                                         
272                                         sub_v3_v3v3(vec, co2, co1);
273
274                                         len = normalize_v3(vec);
275
276                                         /* distance of cpa is close enough */
277                                         if(len < 2.0f * val->personal_space * pa->size) {
278                                                 t_min = t;
279
280                                                 mul_v3_fl(vec, len_v3(vel1));
281                                                 mul_v3_fl(vec, (2.0f - t)/2.0f);
282                                                 sub_v3_v3v3(bbd->wanted_co, vel1, vec);
283                                                 bbd->wanted_speed = len_v3(bbd->wanted_co);
284                                                 ret = 1;
285                                         }
286                                 }
287                         }
288                 }
289         }
290         if(ptn){ MEM_freeN(ptn); ptn=NULL; }
291
292         /* check boids in other systems */
293         for(pt=bbd->sim->psys->targets.first; pt; pt=pt->next) {
294                 ParticleSystem *epsys = psys_get_target_system(bbd->sim->ob, pt);
295
296                 if(epsys) {
297                         neighbors = BLI_kdtree_range_search(epsys->tree, acbr->look_ahead * len_v3(pa->prev_state.vel), pa->prev_state.co, pa->prev_state.ave, &ptn);
298                         if(neighbors > 0) for(n=0; n<neighbors; n++) {
299                                 VECCOPY(co1, pa->prev_state.co);
300                                 VECCOPY(vel1, pa->prev_state.vel);
301                                 VECCOPY(co2, (epsys->particles + ptn[n].index)->prev_state.co);
302                                 VECCOPY(vel2, (epsys->particles + ptn[n].index)->prev_state.vel);
303
304                                 sub_v3_v3v3(loc, co1, co2);
305
306                                 sub_v3_v3v3(vec, vel1, vel2);
307                                 
308                                 inp = dot_v3v3(vec,vec);
309
310                                 /* velocities not parallel */
311                                 if(inp != 0.0f) {
312                                         t = -dot_v3v3(loc, vec)/inp;
313                                         /* cpa is not too far in the future so investigate further */
314                                         if(t > 0.0f && t < t_min) {
315                                                 VECADDFAC(co1, co1, vel1, t);
316                                                 VECADDFAC(co2, co2, vel2, t);
317                                                 
318                                                 sub_v3_v3v3(vec, co2, co1);
319
320                                                 len = normalize_v3(vec);
321
322                                                 /* distance of cpa is close enough */
323                                                 if(len < 2.0f * val->personal_space * pa->size) {
324                                                         t_min = t;
325
326                                                         mul_v3_fl(vec, len_v3(vel1));
327                                                         mul_v3_fl(vec, (2.0f - t)/2.0f);
328                                                         sub_v3_v3v3(bbd->wanted_co, vel1, vec);
329                                                         bbd->wanted_speed = len_v3(bbd->wanted_co);
330                                                         ret = 1;
331                                                 }
332                                         }
333                                 }
334                         }
335
336                         if(ptn){ MEM_freeN(ptn); ptn=NULL; }
337                 }
338         }
339
340
341         if(ptn && nearest==0)
342                 MEM_freeN(ptn);
343
344         return ret;
345 }
346 static int rule_separate(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, ParticleData *pa)
347 {
348         KDTreeNearest *ptn = NULL;
349         ParticleTarget *pt;
350         float len = 2.0f * val->personal_space * pa->size + 1.0f;
351         float vec[3] = {0.0f, 0.0f, 0.0f};
352         int neighbors = BLI_kdtree_range_search(bbd->sim->psys->tree, 2.0f * val->personal_space * pa->size, pa->prev_state.co, NULL, &ptn);
353         int ret = 0;
354
355         if(neighbors > 1 && ptn[1].dist!=0.0f) {
356                 sub_v3_v3v3(vec, pa->prev_state.co, bbd->sim->psys->particles[ptn[1].index].state.co);
357                 mul_v3_fl(vec, (2.0f * val->personal_space * pa->size - ptn[1].dist) / ptn[1].dist);
358                 add_v3_v3(bbd->wanted_co, vec);
359                 bbd->wanted_speed = val->max_speed;
360                 len = ptn[1].dist;
361                 ret = 1;
362         }
363         if(ptn){ MEM_freeN(ptn); ptn=NULL; }
364
365         /* check other boid systems */
366         for(pt=bbd->sim->psys->targets.first; pt; pt=pt->next) {
367                 ParticleSystem *epsys = psys_get_target_system(bbd->sim->ob, pt);
368
369                 if(epsys) {
370                         neighbors = BLI_kdtree_range_search(epsys->tree, 2.0f * val->personal_space * pa->size, pa->prev_state.co, NULL, &ptn);
371                         
372                         if(neighbors > 0 && ptn[0].dist < len) {
373                                 sub_v3_v3v3(vec, pa->prev_state.co, ptn[0].co);
374                                 mul_v3_fl(vec, (2.0f * val->personal_space * pa->size - ptn[0].dist) / ptn[1].dist);
375                                 add_v3_v3(bbd->wanted_co, vec);
376                                 bbd->wanted_speed = val->max_speed;
377                                 len = ptn[0].dist;
378                                 ret = 1;
379                         }
380
381                         if(ptn){ MEM_freeN(ptn); ptn=NULL; }
382                 }
383         }
384         return ret;
385 }
386 static int rule_flock(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, ParticleData *pa)
387 {
388         KDTreeNearest ptn[11];
389         float vec[3] = {0.0f, 0.0f, 0.0f}, loc[3] = {0.0f, 0.0f, 0.0f};
390         int neighbors = BLI_kdtree_find_n_nearest(bbd->sim->psys->tree, 11, pa->state.co, pa->prev_state.ave, ptn);
391         int n;
392         int ret = 0;
393
394         if(neighbors > 1) {
395                 for(n=1; n<neighbors; n++) {
396                         add_v3_v3(loc, bbd->sim->psys->particles[ptn[n].index].prev_state.co);
397                         add_v3_v3(vec, bbd->sim->psys->particles[ptn[n].index].prev_state.vel);
398                 }
399
400                 mul_v3_fl(loc, 1.0f/((float)neighbors - 1.0f));
401                 mul_v3_fl(vec, 1.0f/((float)neighbors - 1.0f));
402
403                 sub_v3_v3(loc, pa->prev_state.co);
404                 sub_v3_v3(vec, pa->prev_state.vel);
405
406                 add_v3_v3(bbd->wanted_co, vec);
407                 add_v3_v3(bbd->wanted_co, loc);
408                 bbd->wanted_speed = len_v3(bbd->wanted_co);
409
410                 ret = 1;
411         }
412         return ret;
413 }
414 static int rule_follow_leader(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, ParticleData *pa)
415 {
416         BoidRuleFollowLeader *flbr = (BoidRuleFollowLeader*) rule;
417         float vec[3] = {0.0f, 0.0f, 0.0f}, loc[3] = {0.0f, 0.0f, 0.0f};
418         float mul, len;
419         int n = (flbr->queue_size <= 1) ? bbd->sim->psys->totpart : flbr->queue_size;
420         int i, ret = 0, p = pa - bbd->sim->psys->particles;
421
422         if(flbr->ob) {
423                 float vec2[3], t;
424
425                 /* first check we're not blocking the leader*/
426                 sub_v3_v3v3(vec, flbr->loc, flbr->oloc);
427                 mul_v3_fl(vec, 1.0f/bbd->timestep);
428
429                 sub_v3_v3v3(loc, pa->prev_state.co, flbr->oloc);
430
431                 mul = dot_v3v3(vec, vec);
432
433                 /* leader is not moving */
434                 if(mul < 0.01) {
435                         len = len_v3(loc);
436                         /* too close to leader */
437                         if(len < 2.0f * val->personal_space * pa->size) {
438                                 VECCOPY(bbd->wanted_co, loc);
439                                 bbd->wanted_speed = val->max_speed;
440                                 return 1;
441                         }
442                 }
443                 else {
444                         t = dot_v3v3(loc, vec)/mul;
445
446                         /* possible blocking of leader in near future */
447                         if(t > 0.0f && t < 3.0f) {
448                                 VECCOPY(vec2, vec);
449                                 mul_v3_fl(vec2, t);
450
451                                 sub_v3_v3v3(vec2, loc, vec2);
452
453                                 len = len_v3(vec2);
454
455                                 if(len < 2.0f * val->personal_space * pa->size) {
456                                         VECCOPY(bbd->wanted_co, vec2);
457                                         bbd->wanted_speed = val->max_speed * (3.0f - t)/3.0f;
458                                         return 1;
459                                 }
460                         }
461                 }
462
463                 /* not blocking so try to follow leader */
464                 if(p && flbr->options & BRULE_LEADER_IN_LINE) {
465                         VECCOPY(vec, bbd->sim->psys->particles[p-1].prev_state.vel);
466                         VECCOPY(loc, bbd->sim->psys->particles[p-1].prev_state.co);
467                 }
468                 else {
469                         VECCOPY(loc, flbr->oloc);
470                         sub_v3_v3v3(vec, flbr->loc, flbr->oloc);
471                         mul_v3_fl(vec, 1.0/bbd->timestep);
472                 }
473                 
474                 /* fac is seconds behind leader */
475                 VECADDFAC(loc, loc, vec, -flbr->distance);
476
477                 sub_v3_v3v3(bbd->wanted_co, loc, pa->prev_state.co);
478                 bbd->wanted_speed = len_v3(bbd->wanted_co);
479                         
480                 ret = 1;
481         }
482         else if(p % n) {
483                 float vec2[3], t, t_min = 3.0f;
484
485                 /* first check we're not blocking any leaders */
486                 for(i = 0; i< bbd->sim->psys->totpart; i+=n){
487                         VECCOPY(vec, bbd->sim->psys->particles[i].prev_state.vel);
488
489                         sub_v3_v3v3(loc, pa->prev_state.co, bbd->sim->psys->particles[i].prev_state.co);
490
491                         mul = dot_v3v3(vec, vec);
492
493                         /* leader is not moving */
494                         if(mul < 0.01) {
495                                 len = len_v3(loc);
496                                 /* too close to leader */
497                                 if(len < 2.0f * val->personal_space * pa->size) {
498                                         VECCOPY(bbd->wanted_co, loc);
499                                         bbd->wanted_speed = val->max_speed;
500                                         return 1;
501                                 }
502                         }
503                         else {
504                                 t = dot_v3v3(loc, vec)/mul;
505
506                                 /* possible blocking of leader in near future */
507                                 if(t > 0.0f && t < t_min) {
508                                         VECCOPY(vec2, vec);
509                                         mul_v3_fl(vec2, t);
510
511                                         sub_v3_v3v3(vec2, loc, vec2);
512
513                                         len = len_v3(vec2);
514
515                                         if(len < 2.0f * val->personal_space * pa->size) {
516                                                 t_min = t;
517                                                 VECCOPY(bbd->wanted_co, loc);
518                                                 bbd->wanted_speed = val->max_speed * (3.0f - t)/3.0f;
519                                                 ret = 1;
520                                         }
521                                 }
522                         }
523                 }
524
525                 if(ret) return 1;
526
527                 /* not blocking so try to follow leader */
528                 if(flbr->options & BRULE_LEADER_IN_LINE) {
529                         VECCOPY(vec, bbd->sim->psys->particles[p-1].prev_state.vel);
530                         VECCOPY(loc, bbd->sim->psys->particles[p-1].prev_state.co);
531                 }
532                 else {
533                         VECCOPY(vec, bbd->sim->psys->particles[p - p%n].prev_state.vel);
534                         VECCOPY(loc, bbd->sim->psys->particles[p - p%n].prev_state.co);
535                 }
536                 
537                 /* fac is seconds behind leader */
538                 VECADDFAC(loc, loc, vec, -flbr->distance);
539
540                 sub_v3_v3v3(bbd->wanted_co, loc, pa->prev_state.co);
541                 bbd->wanted_speed = len_v3(bbd->wanted_co);
542                 
543                 ret = 1;
544         }
545
546         return ret;
547 }
548 static int rule_average_speed(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, ParticleData *pa)
549 {
550         BoidParticle *bpa = pa->boid;
551         BoidRuleAverageSpeed *asbr = (BoidRuleAverageSpeed*)rule;
552         float vec[3] = {0.0f, 0.0f, 0.0f};
553
554         if(asbr->wander > 0.0f) {
555                 /* abuse pa->r_ave for wandering */
556                 bpa->wander[0] += asbr->wander * (-1.0f + 2.0f * BLI_frand());
557                 bpa->wander[1] += asbr->wander * (-1.0f + 2.0f * BLI_frand());
558                 bpa->wander[2] += asbr->wander * (-1.0f + 2.0f * BLI_frand());
559
560                 normalize_v3(bpa->wander);
561
562                 VECCOPY(vec, bpa->wander);
563
564                 mul_qt_v3(pa->prev_state.rot, vec);
565
566                 VECCOPY(bbd->wanted_co, pa->prev_state.ave);
567
568                 mul_v3_fl(bbd->wanted_co, 1.1f);
569
570                 add_v3_v3(bbd->wanted_co, vec);
571
572                 /* leveling */
573                 if(asbr->level > 0.0f && psys_uses_gravity(bbd->sim)) {
574                         project_v3_v3v3(vec, bbd->wanted_co, bbd->sim->scene->physics_settings.gravity);
575                         mul_v3_fl(vec, asbr->level);
576                         sub_v3_v3(bbd->wanted_co, vec);
577                 }
578         }
579         else {
580                 VECCOPY(bbd->wanted_co, pa->prev_state.ave);
581
582                 /* may happen at birth */
583                 if(dot_v2v2(bbd->wanted_co,bbd->wanted_co)==0.0f) {
584                         bbd->wanted_co[0] = 2.0f*(0.5f - BLI_frand());
585                         bbd->wanted_co[1] = 2.0f*(0.5f - BLI_frand());
586                         bbd->wanted_co[2] = 2.0f*(0.5f - BLI_frand());
587                 }
588                 
589                 /* leveling */
590                 if(asbr->level > 0.0f && psys_uses_gravity(bbd->sim)) {
591                         project_v3_v3v3(vec, bbd->wanted_co, bbd->sim->scene->physics_settings.gravity);
592                         mul_v3_fl(vec, asbr->level);
593                         sub_v3_v3(bbd->wanted_co, vec);
594                 }
595
596         }
597         bbd->wanted_speed = asbr->speed * val->max_speed;
598         
599         return 1;
600 }
601 static int rule_fight(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, ParticleData *pa)
602 {
603         BoidRuleFight *fbr = (BoidRuleFight*)rule;
604         KDTreeNearest *ptn = NULL;
605         ParticleTarget *pt;
606         ParticleData *epars;
607         ParticleData *enemy_pa = NULL;
608         BoidParticle *bpa;
609         /* friends & enemies */
610         float closest_enemy[3] = {0.0f,0.0f,0.0f};
611         float closest_dist = fbr->distance + 1.0f;
612         float f_strength = 0.0f, e_strength = 0.0f;
613         float health = 0.0f;
614         int n, ret = 0;
615
616         /* calculate own group strength */
617         int neighbors = BLI_kdtree_range_search(bbd->sim->psys->tree, fbr->distance, pa->prev_state.co, NULL, &ptn);
618         for(n=0; n<neighbors; n++) {
619                 bpa = bbd->sim->psys->particles[ptn[n].index].boid;
620                 health += bpa->data.health;
621         }
622
623         f_strength += bbd->part->boids->strength * health;
624
625         if(ptn){ MEM_freeN(ptn); ptn=NULL; }
626
627         /* add other friendlies and calculate enemy strength and find closest enemy */
628         for(pt=bbd->sim->psys->targets.first; pt; pt=pt->next) {
629                 ParticleSystem *epsys = psys_get_target_system(bbd->sim->ob, pt);
630                 if(epsys) {
631                         epars = epsys->particles;
632
633                         neighbors = BLI_kdtree_range_search(epsys->tree, fbr->distance, pa->prev_state.co, NULL, &ptn);
634                         
635                         health = 0.0f;
636
637                         for(n=0; n<neighbors; n++) {
638                                 bpa = epars[ptn[n].index].boid;
639                                 health += bpa->data.health;
640
641                                 if(n==0 && pt->mode==PTARGET_MODE_ENEMY && ptn[n].dist < closest_dist) {
642                                         VECCOPY(closest_enemy, ptn[n].co);
643                                         closest_dist = ptn[n].dist;
644                                         enemy_pa = epars + ptn[n].index;
645                                 }
646                         }
647                         if(pt->mode==PTARGET_MODE_ENEMY)
648                                 e_strength += epsys->part->boids->strength * health;
649                         else if(pt->mode==PTARGET_MODE_FRIEND)
650                                 f_strength += epsys->part->boids->strength * health;
651
652                         if(ptn){ MEM_freeN(ptn); ptn=NULL; }
653                 }
654         }
655         /* decide action if enemy presence found */
656         if(e_strength > 0.0f) {
657                 sub_v3_v3v3(bbd->wanted_co, closest_enemy, pa->prev_state.co);
658
659                 /* attack if in range */
660                 if(closest_dist <= bbd->part->boids->range + pa->size + enemy_pa->size) {
661                         float damage = BLI_frand();
662                         float enemy_dir[3];
663
664                         normalize_v3_v3(enemy_dir, bbd->wanted_co);
665
666                         /* fight mode */
667                         bbd->wanted_speed = 0.0f;
668
669                         /* must face enemy to fight */
670                         if(dot_v3v3(pa->prev_state.ave, enemy_dir)>0.5f) {
671                                 bpa = enemy_pa->boid;
672                                 bpa->data.health -= bbd->part->boids->strength * bbd->timestep * ((1.0f-bbd->part->boids->accuracy)*damage + bbd->part->boids->accuracy);
673                         }
674                 }
675                 else {
676                         /* approach mode */
677                         bbd->wanted_speed = val->max_speed;
678                 }
679
680                 /* check if boid doesn't want to fight */
681                 bpa = pa->boid;
682                 if(bpa->data.health/bbd->part->boids->health * bbd->part->boids->aggression < e_strength / f_strength) {
683                         /* decide to flee */
684                         if(closest_dist < fbr->flee_distance * fbr->distance) {
685                                 negate_v3(bbd->wanted_co);
686                                 bbd->wanted_speed = val->max_speed;
687                         }
688                         else { /* wait for better odds */
689                                 bbd->wanted_speed = 0.0f;
690                         }
691                 }
692
693                 ret = 1;
694         }
695
696         return ret;
697 }
698
699 typedef int (*boid_rule_cb)(BoidRule *rule, BoidBrainData *data, BoidValues *val, ParticleData *pa);
700
701 static boid_rule_cb boid_rules[] = {
702         rule_none,
703         rule_goal_avoid,
704         rule_goal_avoid,
705         rule_avoid_collision,
706         rule_separate,
707         rule_flock,
708         rule_follow_leader,
709         rule_average_speed,
710         rule_fight,
711         //rule_help,
712         //rule_protect,
713         //rule_hide,
714         //rule_follow_path,
715         //rule_follow_wall
716 };
717
718 static void set_boid_values(BoidValues *val, BoidSettings *boids, ParticleData *pa)
719 {
720         BoidParticle *bpa = pa->boid;
721
722         if(ELEM(bpa->data.mode, eBoidMode_OnLand, eBoidMode_Climbing)) {
723                 val->max_speed = boids->land_max_speed * bpa->data.health/boids->health;
724                 val->max_acc = boids->land_max_acc * val->max_speed;
725                 val->max_ave = boids->land_max_ave * M_PI * bpa->data.health/boids->health;
726                 val->min_speed = 0.0f; /* no minimum speed on land */
727                 val->personal_space = boids->land_personal_space;
728                 val->jump_speed = boids->land_jump_speed * bpa->data.health/boids->health;
729         }
730         else {
731                 val->max_speed = boids->air_max_speed * bpa->data.health/boids->health;
732                 val->max_acc = boids->air_max_acc * val->max_speed;
733                 val->max_ave = boids->air_max_ave * M_PI * bpa->data.health/boids->health;
734                 val->min_speed = boids->air_min_speed * boids->air_max_speed;
735                 val->personal_space = boids->air_personal_space;
736                 val->jump_speed = 0.0f; /* no jumping in air */
737         }
738 }
739 static Object *boid_find_ground(BoidBrainData *bbd, ParticleData *pa, float *ground_co, float *ground_nor)
740 {
741         BoidParticle *bpa = pa->boid;
742
743         if(bpa->data.mode == eBoidMode_Climbing) {
744                 SurfaceModifierData *surmd = NULL;
745                 float x[3], v[3];
746                 
747                 surmd = (SurfaceModifierData *)modifiers_findByType ( bpa->ground, eModifierType_Surface );
748
749                 /* take surface velocity into account */
750                 closest_point_on_surface(surmd, pa->state.co, x, NULL, v);
751                 add_v3_v3(x, v);
752
753                 /* get actual position on surface */
754                 closest_point_on_surface(surmd, x, ground_co, ground_nor, NULL);
755
756                 return bpa->ground;
757         }
758         else {
759                 float zvec[3] = {0.0f, 0.0f, 2000.0f};
760                 ParticleCollision col;
761                 ColliderCache *coll;
762                 BVHTreeRayHit hit;
763                 float radius = 0.0f, t, ray_dir[3];
764
765                 if(!bbd->sim->colliders)
766                         return NULL;
767
768                 copy_v3_v3(col.co1, pa->state.co);
769                 copy_v3_v3(col.co2, pa->state.co);
770                 add_v3_v3(col.co1, zvec);
771                 sub_v3_v3(col.co2, zvec);
772                 sub_v3_v3v3(ray_dir, col.co2, col.co1);
773                 col.t = 0.0f;
774                 hit.index = -1;
775                 hit.dist = col.ray_len = len_v3(ray_dir);
776
777                 /* find out upmost deflector object */
778                 for(coll = bbd->sim->colliders->first; coll; coll = coll->next){
779                         col.ob = coll->ob;
780                         col.md = coll->collmd;
781
782                         if(col.md && col.md->bvhtree)
783                                 BLI_bvhtree_ray_cast(col.md->bvhtree, col.co1, ray_dir, radius, &hit, particle_intersect_face, &col);
784                 }
785                 /* then use that object */
786                 if(hit.index>=0) {
787                         t = hit.dist/col.ray_len;
788                         interp_v3_v3v3(ground_co, col.co1, col.co2, t);
789                         normalize_v3_v3(ground_nor, col.nor);
790                         return col.hit_ob;
791                 }
792                 else {
793                         /* default to z=0 */
794                         VECCOPY(ground_co, pa->state.co);
795                         ground_co[2] = 0;
796                         ground_nor[0] = ground_nor[1] = 0.0f;
797                         ground_nor[2] = 1.0f;
798                         return NULL;
799                 }
800         }
801 }
802 static int boid_rule_applies(ParticleData *pa, BoidSettings *boids, BoidRule *rule)
803 {
804         BoidParticle *bpa = pa->boid;
805
806         if(rule==NULL)
807                 return 0;
808         
809         if(ELEM(bpa->data.mode, eBoidMode_OnLand, eBoidMode_Climbing) && rule->flag & BOIDRULE_ON_LAND)
810                 return 1;
811         
812         if(bpa->data.mode==eBoidMode_InAir && rule->flag & BOIDRULE_IN_AIR)
813                 return 1;
814
815         return 0;
816 }
817 void boids_precalc_rules(ParticleSettings *part, float cfra)
818 {
819         BoidState *state = part->boids->states.first;
820         BoidRule *rule;
821         for(; state; state=state->next) {
822                 for(rule = state->rules.first; rule; rule=rule->next) {
823                         if(rule->type==eBoidRuleType_FollowLeader) {
824                                 BoidRuleFollowLeader *flbr = (BoidRuleFollowLeader*) rule;
825
826                                 if(flbr->ob && flbr->cfra != cfra) {
827                                         /* save object locations for velocity calculations */
828                                         VECCOPY(flbr->oloc, flbr->loc);
829                                         VECCOPY(flbr->loc, flbr->ob->obmat[3]);
830                                         flbr->cfra = cfra;
831                                 }
832                         }
833                 }
834         }
835 }
836 static void boid_climb(BoidSettings *boids, ParticleData *pa, float *surface_co, float *surface_nor)
837 {
838         BoidParticle *bpa = pa->boid;
839         float nor[3], vel[3];
840         VECCOPY(nor, surface_nor);
841
842         /* gather apparent gravity */
843         VECADDFAC(bpa->gravity, bpa->gravity, surface_nor, -1.0);
844         normalize_v3(bpa->gravity);
845
846         /* raise boid it's size from surface */
847         mul_v3_fl(nor, pa->size * boids->height);
848         add_v3_v3v3(pa->state.co, surface_co, nor);
849
850         /* remove normal component from velocity */
851         project_v3_v3v3(vel, pa->state.vel, surface_nor);
852         sub_v3_v3v3(pa->state.vel, pa->state.vel, vel);
853 }
854 static float boid_goal_signed_dist(float *boid_co, float *goal_co, float *goal_nor)
855 {
856         float vec[3];
857
858         sub_v3_v3v3(vec, boid_co, goal_co);
859
860         return dot_v3v3(vec, goal_nor);
861 }
862 /* wanted_co is relative to boid location */
863 static int apply_boid_rule(BoidBrainData *bbd, BoidRule *rule, BoidValues *val, ParticleData *pa, float fuzziness)
864 {
865         if(rule==NULL)
866                 return 0;
867
868         if(boid_rule_applies(pa, bbd->part->boids, rule)==0)
869                 return 0;
870
871         if(boid_rules[rule->type](rule, bbd, val, pa)==0)
872                 return 0;
873
874         if(fuzziness < 0.0f || compare_len_v3v3(bbd->wanted_co, pa->prev_state.vel, fuzziness * len_v3(pa->prev_state.vel))==0)
875                 return 1;
876         else
877                 return 0;
878 }
879 static BoidState *get_boid_state(BoidSettings *boids, ParticleData *pa) {
880         BoidState *state = boids->states.first;
881         BoidParticle *bpa = pa->boid;
882
883         for(; state; state=state->next) {
884                 if(state->id==bpa->data.state_id)
885                         return state;
886         }
887
888         /* for some reason particle isn't at a valid state */
889         state = boids->states.first;
890         if(state)
891                 bpa->data.state_id = state->id;
892
893         return state;
894 }
895 //static int boid_condition_is_true(BoidCondition *cond) {
896 //      /* TODO */
897 //      return 0;
898 //}
899
900 /* determines the velocity the boid wants to have */
901 void boid_brain(BoidBrainData *bbd, int p, ParticleData *pa)
902 {
903         BoidRule *rule;
904         BoidSettings *boids = bbd->part->boids;
905         BoidValues val;
906         BoidState *state = get_boid_state(boids, pa);
907         BoidParticle *bpa = pa->boid;
908         int rand;
909         //BoidCondition *cond;
910
911         if(bpa->data.health <= 0.0f) {
912                 pa->alive = PARS_DYING;
913                 return;
914         }
915
916         //planned for near future
917         //cond = state->conditions.first;
918         //for(; cond; cond=cond->next) {
919         //      if(boid_condition_is_true(cond)) {
920         //              pa->boid->state_id = cond->state_id;
921         //              state = get_boid_state(boids, pa);
922         //              break; /* only first true condition is used */
923         //      }
924         //}
925
926         bbd->wanted_co[0]=bbd->wanted_co[1]=bbd->wanted_co[2]=bbd->wanted_speed=0.0f;
927
928         /* create random seed for every particle & frame */
929         BLI_srandom(bbd->sim->psys->seed + p);
930         rand = BLI_rand();
931         BLI_srandom((int)bbd->cfra + rand);
932
933         set_boid_values(&val, bbd->part->boids, pa);
934
935         /* go through rules */
936         switch(state->ruleset_type) {
937                 case eBoidRulesetType_Fuzzy:
938                 {
939                         for(rule = state->rules.first; rule; rule = rule->next) {
940                                 if(apply_boid_rule(bbd, rule, &val, pa, state->rule_fuzziness))
941                                         break; /* only first nonzero rule that comes through fuzzy rule is applied */
942                         }
943                         break;
944                 }
945                 case eBoidRulesetType_Random:
946                 {
947                         /* use random rule for each particle (allways same for same particle though) */
948                         rule = BLI_findlink(&state->rules, rand % BLI_countlist(&state->rules));
949
950                         apply_boid_rule(bbd, rule, &val, pa, -1.0);
951                 }
952                 case eBoidRulesetType_Average:
953                 {
954                         float wanted_co[3] = {0.0f, 0.0f, 0.0f}, wanted_speed = 0.0f;
955                         int n = 0;
956                         for(rule = state->rules.first; rule; rule=rule->next) {
957                                 if(apply_boid_rule(bbd, rule, &val, pa, -1.0f)) {
958                                         add_v3_v3(wanted_co, bbd->wanted_co);
959                                         wanted_speed += bbd->wanted_speed;
960                                         n++;
961                                         bbd->wanted_co[0]=bbd->wanted_co[1]=bbd->wanted_co[2]=bbd->wanted_speed=0.0f;
962                                 }
963                         }
964
965                         if(n > 1) {
966                                 mul_v3_fl(wanted_co, 1.0f/(float)n);
967                                 wanted_speed /= (float)n;
968                         }
969
970                         VECCOPY(bbd->wanted_co, wanted_co);
971                         bbd->wanted_speed = wanted_speed;
972                         break;
973                 }
974
975         }
976
977         /* decide on jumping & liftoff */
978         if(bpa->data.mode == eBoidMode_OnLand) {
979                 /* fuzziness makes boids capable of misjudgement */
980                 float mul = 1.0 + state->rule_fuzziness;
981                 
982                 if(boids->options & BOID_ALLOW_FLIGHT && bbd->wanted_co[2] > 0.0f) {
983                         float cvel[3], dir[3];
984
985                         VECCOPY(dir, pa->prev_state.ave);
986                         normalize_v2(dir);
987
988                         VECCOPY(cvel, bbd->wanted_co);
989                         normalize_v2(cvel);
990
991                         if(dot_v2v2(cvel, dir) > 0.95 / mul)
992                                 bpa->data.mode = eBoidMode_Liftoff;
993                 }
994                 else if(val.jump_speed > 0.0f) {
995                         float jump_v[3];
996                         int jump = 0;
997
998                         /* jump to get to a location */
999                         if(bbd->wanted_co[2] > 0.0f) {
1000                                 float cvel[3], dir[3];
1001                                 float z_v, ground_v, cur_v;
1002                                 float len;
1003
1004                                 VECCOPY(dir, pa->prev_state.ave);
1005                                 normalize_v2(dir);
1006
1007                                 VECCOPY(cvel, bbd->wanted_co);
1008                                 normalize_v2(cvel);
1009
1010                                 len = len_v2(pa->prev_state.vel);
1011
1012                                 /* first of all, are we going in a suitable direction? */
1013                                 /* or at a suitably slow speed */
1014                                 if(dot_v2v2(cvel, dir) > 0.95f / mul || len <= state->rule_fuzziness) {
1015                                         /* try to reach goal at highest point of the parabolic path */
1016                                         cur_v = len_v2(pa->prev_state.vel);
1017                                         z_v = sasqrt(-2.0f * bbd->sim->scene->physics_settings.gravity[2] * bbd->wanted_co[2]);
1018                                         ground_v = len_v2(bbd->wanted_co)*sasqrt(-0.5f * bbd->sim->scene->physics_settings.gravity[2] / bbd->wanted_co[2]);
1019
1020                                         len = sasqrt((ground_v-cur_v)*(ground_v-cur_v) + z_v*z_v);
1021
1022                                         if(len < val.jump_speed * mul || bbd->part->boids->options & BOID_ALLOW_FLIGHT) {
1023                                                 jump = 1;
1024
1025                                                 len = MIN2(len, val.jump_speed);
1026
1027                                                 VECCOPY(jump_v, dir);
1028                                                 jump_v[2] = z_v;
1029                                                 mul_v3_fl(jump_v, ground_v);
1030
1031                                                 normalize_v3(jump_v);
1032                                                 mul_v3_fl(jump_v, len);
1033                                                 add_v2_v2v2(jump_v, jump_v, pa->prev_state.vel);
1034                                         }
1035                                 }
1036                         }
1037
1038                         /* jump to go faster */
1039                         if(jump == 0 && val.jump_speed > val.max_speed && bbd->wanted_speed > val.max_speed) {
1040                                 
1041                         }
1042
1043                         if(jump) {
1044                                 VECCOPY(pa->prev_state.vel, jump_v);
1045                                 bpa->data.mode = eBoidMode_Falling;
1046                         }
1047                 }
1048         }
1049 }
1050 /* tries to realize the wanted velocity taking all constraints into account */
1051 void boid_body(BoidBrainData *bbd, ParticleData *pa)
1052 {
1053         BoidSettings *boids = bbd->part->boids;
1054         BoidParticle *bpa = pa->boid;
1055         BoidValues val;
1056         EffectedPoint epoint;
1057         float acc[3] = {0.0f, 0.0f, 0.0f}, tan_acc[3], nor_acc[3];
1058         float dvec[3], bvec[3];
1059         float new_dir[3], new_speed;
1060         float old_dir[3], old_speed;
1061         float wanted_dir[3];
1062         float q[4], mat[3][3]; /* rotation */
1063         float ground_co[3] = {0.0f, 0.0f, 0.0f}, ground_nor[3] = {0.0f, 0.0f, 1.0f};
1064         float force[3] = {0.0f, 0.0f, 0.0f};
1065         float pa_mass=bbd->part->mass, dtime=bbd->dfra*bbd->timestep;
1066
1067         set_boid_values(&val, boids, pa);
1068
1069         /* make sure there's something in new velocity, location & rotation */
1070         copy_particle_key(&pa->state,&pa->prev_state,0);
1071
1072         if(bbd->part->flag & PART_SIZEMASS)
1073                 pa_mass*=pa->size;
1074
1075         /* if boids can't fly they fall to the ground */
1076         if((boids->options & BOID_ALLOW_FLIGHT)==0 && ELEM(bpa->data.mode, eBoidMode_OnLand, eBoidMode_Climbing)==0 && psys_uses_gravity(bbd->sim))
1077                 bpa->data.mode = eBoidMode_Falling;
1078
1079         if(bpa->data.mode == eBoidMode_Falling) {
1080                 /* Falling boids are only effected by gravity. */
1081                 acc[2] = bbd->sim->scene->physics_settings.gravity[2];
1082         }
1083         else {
1084                 /* figure out acceleration */
1085                 float landing_level = 2.0f;
1086                 float level = landing_level + 1.0f;
1087                 float new_vel[3];
1088
1089                 if(bpa->data.mode == eBoidMode_Liftoff) {
1090                         bpa->data.mode = eBoidMode_InAir;
1091                         bpa->ground = boid_find_ground(bbd, pa, ground_co, ground_nor);
1092                 }
1093                 else if(bpa->data.mode == eBoidMode_InAir && boids->options & BOID_ALLOW_LAND) {
1094                         /* auto-leveling & landing if close to ground */
1095
1096                         bpa->ground = boid_find_ground(bbd, pa, ground_co, ground_nor);
1097                         
1098                         /* level = how many particle sizes above ground */
1099                         level = (pa->prev_state.co[2] - ground_co[2])/(2.0f * pa->size) - 0.5;
1100
1101                         landing_level = - boids->landing_smoothness * pa->prev_state.vel[2] * pa_mass;
1102
1103                         if(pa->prev_state.vel[2] < 0.0f) {
1104                                 if(level < 1.0f) {
1105                                         bbd->wanted_co[0] = bbd->wanted_co[1] = bbd->wanted_co[2] = 0.0f;
1106                                         bbd->wanted_speed = 0.0f;
1107                                         bpa->data.mode = eBoidMode_Falling;
1108                                 }
1109                                 else if(level < landing_level) {
1110                                         bbd->wanted_speed *= (level - 1.0f)/landing_level;
1111                                         bbd->wanted_co[2] *= (level - 1.0f)/landing_level;
1112                                 }
1113                         }
1114                 }
1115
1116                 VECCOPY(old_dir, pa->prev_state.ave);
1117                 new_speed = normalize_v3_v3(wanted_dir, bbd->wanted_co);
1118
1119                 /* first check if we have valid direction we want to go towards */
1120                 if(new_speed == 0.0f) {
1121                         VECCOPY(new_dir, old_dir);
1122                 }
1123                 else {
1124                         float old_dir2[2], wanted_dir2[2], nor[3], angle;
1125                         copy_v2_v2(old_dir2, old_dir);
1126                         normalize_v2(old_dir2);
1127                         copy_v2_v2(wanted_dir2, wanted_dir);
1128                         normalize_v2(wanted_dir2);
1129
1130                         /* choose random direction to turn if wanted velocity */
1131                         /* is directly behind regardless of z-coordinate */
1132                         if(dot_v2v2(old_dir2, wanted_dir2) < -0.99f) {
1133                                 wanted_dir[0] = 2.0f*(0.5f - BLI_frand());
1134                                 wanted_dir[1] = 2.0f*(0.5f - BLI_frand());
1135                                 wanted_dir[2] = 2.0f*(0.5f - BLI_frand());
1136                                 normalize_v3(wanted_dir);
1137                         }
1138
1139                         /* constrain direction with maximum angular velocity */
1140                         angle = saacos(dot_v3v3(old_dir, wanted_dir));
1141                         angle = MIN2(angle, val.max_ave);
1142
1143                         cross_v3_v3v3(nor, old_dir, wanted_dir);
1144                         axis_angle_to_quat( q,nor, angle);
1145                         VECCOPY(new_dir, old_dir);
1146                         mul_qt_v3(q, new_dir);
1147                         normalize_v3(new_dir);
1148
1149                         /* save direction in case resulting velocity too small */
1150                         axis_angle_to_quat( q,nor, angle*dtime);
1151                         VECCOPY(pa->state.ave, old_dir);
1152                         mul_qt_v3(q, pa->state.ave);
1153                         normalize_v3(pa->state.ave);
1154                 }
1155
1156                 /* constrain speed with maximum acceleration */
1157                 old_speed = len_v3(pa->prev_state.vel);
1158                 
1159                 if(bbd->wanted_speed < old_speed)
1160                         new_speed = MAX2(bbd->wanted_speed, old_speed - val.max_acc);
1161                 else
1162                         new_speed = MIN2(bbd->wanted_speed, old_speed + val.max_acc);
1163
1164                 /* combine direction and speed */
1165                 VECCOPY(new_vel, new_dir);
1166                 mul_v3_fl(new_vel, new_speed);
1167
1168                 /* maintain minimum flying velocity if not landing */
1169                 if(level >= landing_level) {
1170                         float len2 = dot_v2v2(new_vel,new_vel);
1171                         float root;
1172
1173                         len2 = MAX2(len2, val.min_speed*val.min_speed);
1174                         root = sasqrt(new_speed*new_speed - len2);
1175
1176                         new_vel[2] = new_vel[2] < 0.0f ? -root : root;
1177
1178                         normalize_v2(new_vel);
1179                         mul_v2_fl(new_vel, sasqrt(len2));
1180                 }
1181
1182                 /* finally constrain speed to max speed */
1183                 new_speed = normalize_v3(new_vel);
1184                 mul_v3_fl(new_vel, MIN2(new_speed, val.max_speed));
1185
1186                 /* get acceleration from difference of velocities */
1187                 sub_v3_v3v3(acc, new_vel, pa->prev_state.vel);
1188
1189                 /* break acceleration to components */
1190                 project_v3_v3v3(tan_acc, acc, pa->prev_state.ave);
1191                 sub_v3_v3v3(nor_acc, acc, tan_acc);
1192         }
1193
1194         /* account for effectors */
1195         pd_point_from_particle(bbd->sim, pa, &pa->state, &epoint);
1196         pdDoEffectors(bbd->sim->psys->effectors, bbd->sim->colliders, bbd->part->effector_weights, &epoint, force, NULL);
1197
1198         if(ELEM(bpa->data.mode, eBoidMode_OnLand, eBoidMode_Climbing)) {
1199                 float length = normalize_v3(force);
1200
1201                 length = MAX2(0.0f, length - boids->land_stick_force);
1202
1203                 mul_v3_fl(force, length);
1204         }
1205         
1206         add_v3_v3(acc, force);
1207
1208         /* store smoothed acceleration for nice banking etc. */
1209         VECADDFAC(bpa->data.acc, bpa->data.acc, acc, dtime);
1210         mul_v3_fl(bpa->data.acc, 1.0f / (1.0f + dtime));
1211
1212         /* integrate new location & velocity */
1213
1214         /* by regarding the acceleration as a force at this stage we*/
1215         /* can get better control allthough it's a bit unphysical       */
1216         mul_v3_fl(acc, 1.0f/pa_mass);
1217
1218         VECCOPY(dvec, acc);
1219         mul_v3_fl(dvec, dtime*dtime*0.5f);
1220         
1221         VECCOPY(bvec, pa->prev_state.vel);
1222         mul_v3_fl(bvec, dtime);
1223         add_v3_v3(dvec, bvec);
1224         add_v3_v3(pa->state.co, dvec);
1225
1226         VECADDFAC(pa->state.vel, pa->state.vel, acc, dtime);
1227
1228         if(bpa->data.mode != eBoidMode_InAir)
1229                 bpa->ground = boid_find_ground(bbd, pa, ground_co, ground_nor);
1230
1231         /* change modes, constrain movement & keep track of down vector */
1232         switch(bpa->data.mode) {
1233                 case eBoidMode_InAir:
1234                 {
1235                         float grav[3] = {0.0f, 0.0f, bbd->sim->scene->physics_settings.gravity[2] < 0.0f ? -1.0f : 0.0f};
1236
1237                         /* don't take forward acceleration into account (better banking) */
1238                         if(dot_v3v3(bpa->data.acc, pa->state.vel) > 0.0f) {
1239                                 project_v3_v3v3(dvec, bpa->data.acc, pa->state.vel);
1240                                 sub_v3_v3v3(dvec, bpa->data.acc, dvec);
1241                         }
1242                         else {
1243                                 VECCOPY(dvec, bpa->data.acc);
1244                         }
1245
1246                         /* gather apparent gravity */
1247                         VECADDFAC(bpa->gravity, grav, dvec, -boids->banking);
1248                         normalize_v3(bpa->gravity);
1249
1250                         /* stick boid on goal when close enough */
1251                         if(bbd->goal_ob && boid_goal_signed_dist(pa->state.co, bbd->goal_co, bbd->goal_nor) <= pa->size * boids->height) {
1252                                 bpa->data.mode = eBoidMode_Climbing;
1253                                 bpa->ground = bbd->goal_ob;
1254                                 boid_find_ground(bbd, pa, ground_co, ground_nor);
1255                                 boid_climb(boids, pa, ground_co, ground_nor);
1256                         }
1257                         /* land boid when belowg ground */
1258                         else if(boids->options & BOID_ALLOW_LAND && pa->state.co[2] <= ground_co[2] + pa->size * boids->height) {
1259                                 pa->state.co[2] = ground_co[2] + pa->size * boids->height;
1260                                 pa->state.vel[2] = 0.0f;
1261                                 bpa->data.mode = eBoidMode_OnLand;
1262                         }
1263                         break;
1264                 }
1265                 case eBoidMode_Falling:
1266                 {
1267                         float grav[3] = {0.0f, 0.0f, bbd->sim->scene->physics_settings.gravity[2] < 0.0f ? -1.0f : 0.0f};
1268
1269                         /* gather apparent gravity */
1270                         VECADDFAC(bpa->gravity, bpa->gravity, grav, dtime);
1271                         normalize_v3(bpa->gravity);
1272
1273                         if(boids->options & BOID_ALLOW_LAND) {
1274                                 /* stick boid on goal when close enough */
1275                                 if(bbd->goal_ob && boid_goal_signed_dist(pa->state.co, bbd->goal_co, bbd->goal_nor) <= pa->size * boids->height) {
1276                                         bpa->data.mode = eBoidMode_Climbing;
1277                                         bpa->ground = bbd->goal_ob;
1278                                         boid_find_ground(bbd, pa, ground_co, ground_nor);
1279                                         boid_climb(boids, pa, ground_co, ground_nor);
1280                                 }
1281                                 /* land boid when really near ground */
1282                                 else if(pa->state.co[2] <= ground_co[2] + 1.01 * pa->size * boids->height){
1283                                         pa->state.co[2] = ground_co[2] + pa->size * boids->height;
1284                                         pa->state.vel[2] = 0.0f;
1285                                         bpa->data.mode = eBoidMode_OnLand;
1286                                 }
1287                                 /* if we're falling, can fly and want to go upwards lets fly */
1288                                 else if(boids->options & BOID_ALLOW_FLIGHT && bbd->wanted_co[2] > 0.0f)
1289                                         bpa->data.mode = eBoidMode_InAir;
1290                         }
1291                         else
1292                                 bpa->data.mode = eBoidMode_InAir;
1293                         break;
1294                 }
1295                 case eBoidMode_Climbing:
1296                 {
1297                         boid_climb(boids, pa, ground_co, ground_nor);
1298                         //float nor[3];
1299                         //VECCOPY(nor, ground_nor);
1300
1301                         ///* gather apparent gravity to r_ve */
1302                         //VECADDFAC(pa->r_ve, pa->r_ve, ground_nor, -1.0);
1303                         //normalize_v3(pa->r_ve);
1304
1305                         ///* raise boid it's size from surface */
1306                         //mul_v3_fl(nor, pa->size * boids->height);
1307                         //add_v3_v3v3(pa->state.co, ground_co, nor);
1308
1309                         ///* remove normal component from velocity */
1310                         //project_v3_v3v3(v, pa->state.vel, ground_nor);
1311                         //sub_v3_v3v3(pa->state.vel, pa->state.vel, v);
1312                         break;
1313                 }
1314                 case eBoidMode_OnLand:
1315                 {
1316                         /* stick boid on goal when close enough */
1317                         if(bbd->goal_ob && boid_goal_signed_dist(pa->state.co, bbd->goal_co, bbd->goal_nor) <= pa->size * boids->height) {
1318                                 bpa->data.mode = eBoidMode_Climbing;
1319                                 bpa->ground = bbd->goal_ob;
1320                                 boid_find_ground(bbd, pa, ground_co, ground_nor);
1321                                 boid_climb(boids, pa, ground_co, ground_nor);
1322                         }
1323                         /* ground is too far away so boid falls */
1324                         else if(pa->state.co[2]-ground_co[2] > 1.1 * pa->size * boids->height)
1325                                 bpa->data.mode = eBoidMode_Falling;
1326                         else {
1327                                 /* constrain to surface */
1328                                 pa->state.co[2] = ground_co[2] + pa->size * boids->height;
1329                                 pa->state.vel[2] = 0.0f;
1330                         }
1331
1332                         if(boids->banking > 0.0f) {
1333                                 float grav[3];
1334                                 /* Don't take gravity's strength in to account, */
1335                                 /* otherwise amount of banking is hard to control. */
1336                                 negate_v3_v3(grav, ground_nor);
1337
1338                                 project_v3_v3v3(dvec, bpa->data.acc, pa->state.vel);
1339                                 sub_v3_v3v3(dvec, bpa->data.acc, dvec);
1340
1341                                 /* gather apparent gravity */
1342                                 VECADDFAC(bpa->gravity, grav, dvec, -boids->banking);
1343                                 normalize_v3(bpa->gravity);
1344                         }
1345                         else {
1346                                 /* gather negative surface normal */
1347                                 VECADDFAC(bpa->gravity, bpa->gravity, ground_nor, -1.0f);
1348                                 normalize_v3(bpa->gravity);
1349                         }
1350                         break;
1351                 }
1352         }
1353
1354         /* save direction to state.ave unless the boid is falling */
1355         /* (boids can't effect their direction when falling) */
1356         if(bpa->data.mode!=eBoidMode_Falling && len_v3(pa->state.vel) > 0.1*pa->size) {
1357                 normalize_v3_v3(pa->state.ave, pa->state.vel);
1358         }
1359
1360         /* apply damping */
1361         if(ELEM(bpa->data.mode, eBoidMode_OnLand, eBoidMode_Climbing))
1362                 mul_v3_fl(pa->state.vel, 1.0f - 0.2f*bbd->part->dampfac);
1363
1364         /* calculate rotation matrix based on forward & down vectors */
1365         if(bpa->data.mode == eBoidMode_InAir) {
1366                 VECCOPY(mat[0], pa->state.ave);
1367
1368                 project_v3_v3v3(dvec, bpa->gravity, pa->state.ave);
1369                 sub_v3_v3v3(mat[2], bpa->gravity, dvec);
1370                 normalize_v3(mat[2]);
1371         }
1372         else {
1373                 project_v3_v3v3(dvec, pa->state.ave, bpa->gravity);
1374                 sub_v3_v3v3(mat[0], pa->state.ave, dvec);
1375                 normalize_v3(mat[0]);
1376
1377                 VECCOPY(mat[2], bpa->gravity);
1378         }
1379         negate_v3(mat[2]);
1380         cross_v3_v3v3(mat[1], mat[2], mat[0]);
1381         
1382         /* apply rotation */
1383         mat3_to_quat_is_ok( q,mat);
1384         copy_qt_qt(pa->state.rot, q);
1385 }
1386
1387 BoidRule *boid_new_rule(int type)
1388 {
1389         BoidRule *rule = NULL;
1390         if(type <= 0)
1391                 return NULL;
1392
1393         switch(type) {
1394                 case eBoidRuleType_Goal:
1395                 case eBoidRuleType_Avoid:
1396                         rule = MEM_callocN(sizeof(BoidRuleGoalAvoid), "BoidRuleGoalAvoid");
1397                         break;
1398                 case eBoidRuleType_AvoidCollision:
1399                         rule = MEM_callocN(sizeof(BoidRuleAvoidCollision), "BoidRuleAvoidCollision");
1400                         ((BoidRuleAvoidCollision*)rule)->look_ahead = 2.0f;
1401                         break;
1402                 case eBoidRuleType_FollowLeader:
1403                         rule = MEM_callocN(sizeof(BoidRuleFollowLeader), "BoidRuleFollowLeader");
1404                         ((BoidRuleFollowLeader*)rule)->distance = 1.0f;
1405                         break;
1406                 case eBoidRuleType_AverageSpeed:
1407                         rule = MEM_callocN(sizeof(BoidRuleAverageSpeed), "BoidRuleAverageSpeed");
1408                         ((BoidRuleAverageSpeed*)rule)->speed = 0.5f;
1409                         break;
1410                 case eBoidRuleType_Fight:
1411                         rule = MEM_callocN(sizeof(BoidRuleFight), "BoidRuleFight");
1412                         ((BoidRuleFight*)rule)->distance = 100.0f;
1413                         ((BoidRuleFight*)rule)->flee_distance = 100.0f;
1414                         break;
1415                 default:
1416                         rule = MEM_callocN(sizeof(BoidRule), "BoidRule");
1417                         break;
1418         }
1419
1420         rule->type = type;
1421         rule->flag |= BOIDRULE_IN_AIR|BOIDRULE_ON_LAND;
1422         strcpy(rule->name, boidrule_type_items[type-1].name);
1423
1424         return rule;
1425 }
1426 void boid_default_settings(BoidSettings *boids)
1427 {
1428         boids->air_max_speed = 10.0f;
1429         boids->air_max_acc = 0.5f;
1430         boids->air_max_ave = 0.5f;
1431         boids->air_personal_space = 1.0f;
1432
1433         boids->land_max_speed = 5.0f;
1434         boids->land_max_acc = 0.5f;
1435         boids->land_max_ave = 0.5f;
1436         boids->land_personal_space = 1.0f;
1437
1438         boids->options = BOID_ALLOW_FLIGHT;
1439
1440         boids->landing_smoothness = 3.0f;
1441         boids->banking = 1.0f;
1442         boids->height = 1.0f;
1443
1444         boids->health = 1.0f;
1445         boids->accuracy = 1.0f;
1446         boids->aggression = 2.0f;
1447         boids->range = 1.0f;
1448         boids->strength = 0.1f;
1449 }
1450
1451 BoidState *boid_new_state(BoidSettings *boids)
1452 {
1453         BoidState *state = MEM_callocN(sizeof(BoidState), "BoidState");
1454
1455         state->id = boids->last_state_id++;
1456         if(state->id)
1457                 sprintf(state->name, "State %i", state->id);
1458         else
1459                 strcpy(state->name, "State");
1460
1461         state->rule_fuzziness = 0.5;
1462         state->volume = 1.0f;
1463         state->channels |= ~0;
1464
1465         return state;
1466 }
1467
1468 BoidState *boid_duplicate_state(BoidSettings *boids, BoidState *state) {
1469         BoidState *staten = MEM_dupallocN(state);
1470
1471         BLI_duplicatelist(&staten->rules, &state->rules);
1472         BLI_duplicatelist(&staten->conditions, &state->conditions);
1473         BLI_duplicatelist(&staten->actions, &state->actions);
1474
1475         staten->id = boids->last_state_id++;
1476
1477         return staten;
1478 }
1479 void boid_free_settings(BoidSettings *boids)
1480 {
1481         if(boids) {
1482                 BoidState *state = boids->states.first;
1483
1484                 for(; state; state=state->next) {
1485                         BLI_freelistN(&state->rules);
1486                         BLI_freelistN(&state->conditions);
1487                         BLI_freelistN(&state->actions);
1488                 }
1489
1490                 BLI_freelistN(&boids->states);
1491
1492                 MEM_freeN(boids);
1493         }
1494 }
1495 BoidSettings *boid_copy_settings(BoidSettings *boids)
1496 {
1497         BoidSettings *nboids = NULL;
1498
1499         if(boids) {
1500                 BoidState *state;
1501                 BoidState *nstate;
1502
1503                 nboids = MEM_dupallocN(boids);
1504
1505                 BLI_duplicatelist(&nboids->states, &boids->states);
1506
1507                 state = boids->states.first;
1508                 nstate = nboids->states.first;
1509                 for(; state; state=state->next, nstate=nstate->next) {
1510                         BLI_duplicatelist(&nstate->rules, &state->rules);
1511                         BLI_duplicatelist(&nstate->conditions, &state->conditions);
1512                         BLI_duplicatelist(&nstate->actions, &state->actions);
1513                 }
1514         }
1515
1516         return nboids;
1517 }
1518 BoidState *boid_get_current_state(BoidSettings *boids)
1519 {
1520         BoidState *state = boids->states.first;
1521
1522         for(; state; state=state->next) {
1523                 if(state->flag & BOIDSTATE_CURRENT)
1524                         break;
1525         }
1526
1527         return state;
1528 }
1529