6 * ***** BEGIN GPL LICENSE BLOCK *****
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.
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.
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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
22 * The Original Code is Copyright (C) 2007 by Janne Karhu.
23 * All rights reserved.
25 * The Original Code is: all of this file.
27 * Contributor(s): none yet.
29 * ***** END GPL LICENSE BLOCK *****
36 #include "MEM_guardedalloc.h"
38 #include "DNA_scene_types.h"
39 #include "DNA_particle_types.h"
40 #include "DNA_mesh_types.h"
41 #include "DNA_meshdata_types.h"
42 #include "DNA_modifier_types.h"
43 #include "DNA_object_force.h"
44 #include "DNA_texture_types.h"
45 #include "DNA_material_types.h"
46 #include "DNA_object_types.h"
47 #include "DNA_curve_types.h"
48 #include "DNA_key_types.h"
49 #include "DNA_ipo_types.h" // XXX old animation system stuff to remove!
51 #include "BLI_arithb.h"
52 #include "BLI_blenlib.h"
53 #include "BLI_dynstr.h"
54 #include "BLI_kdtree.h"
55 #include "BLI_linklist.h"
57 #include "BLI_threads.h"
61 #include "BKE_global.h"
63 #include "BKE_lattice.h"
64 #include "BKE_utildefines.h"
65 #include "BKE_displist.h"
66 #include "BKE_particle.h"
67 #include "BKE_DerivedMesh.h"
68 #include "BKE_object.h"
69 #include "BKE_softbody.h"
70 #include "BKE_material.h"
72 #include "BKE_library.h"
73 #include "BKE_depsgraph.h"
74 #include "BKE_modifier.h"
76 #include "BKE_cdderivedmesh.h"
77 #include "BKE_pointcache.h"
79 #include "RE_render_ext.h"
81 static void key_from_object(Object *ob, ParticleKey *key);
82 static void get_cpa_texture(DerivedMesh *dm, Material *ma, int face_index,
83 float *fuv, float *orco, ParticleTexture *ptex, int event);
85 /* few helpers for countall etc. */
86 int count_particles(ParticleSystem *psys){
87 ParticleSettings *part=psys->part;
91 for(p=0,pa=psys->particles; p<psys->totpart; p++,pa++){
92 if(pa->alive == PARS_KILLED);
93 else if(pa->alive == PARS_UNBORN && (part->flag & PART_UNBORN)==0);
94 else if(pa->alive == PARS_DEAD && (part->flag & PART_DIED)==0);
95 else if(pa->flag & (PARS_UNEXIST+PARS_NO_DISP));
100 int count_particles_mod(ParticleSystem *psys, int totgr, int cur){
101 ParticleSettings *part=psys->part;
105 for(p=0,pa=psys->particles; p<psys->totpart; p++,pa++){
106 if(pa->alive == PARS_KILLED);
107 else if(pa->alive == PARS_UNBORN && (part->flag & PART_UNBORN)==0);
108 else if(pa->alive == PARS_DEAD && (part->flag & PART_DIED)==0);
109 else if(pa->flag & (PARS_UNEXIST+PARS_NO_DISP));
110 else if(p%totgr==cur) tot++;
114 int psys_count_keys(ParticleSystem *psys)
117 int i, totpart=psys->totpart, totkey=0;
119 for(i=0, pa=psys->particles; i<totpart; i++, pa++)
120 totkey += pa->totkey;
124 /* remember to free the pointer returned from this! */
125 char *psys_menu_string(Object *ob, int for_sb)
127 ParticleSystem *psys;
132 ds = BLI_dynstr_new();
135 BLI_dynstr_append(ds, "|Object%x-1");
137 for(i=0,psys=ob->particlesystem.first; psys; i++,psys=psys->next){
139 BLI_dynstr_append(ds, "|");
140 sprintf(num,"%i. ",i+1);
141 BLI_dynstr_append(ds, num);
142 BLI_dynstr_append(ds, psys->part->id.name+2);
143 sprintf(num,"%%x%i",i+1);
144 BLI_dynstr_append(ds, num);
147 str = BLI_dynstr_get_cstring(ds);
154 /* we allocate path cache memory in chunks instead of a big continguous
155 * chunk, windows' memory allocater fails to find big blocks of memory often */
157 #define PATH_CACHE_BUF_SIZE 1024
159 static ParticleCacheKey **psys_alloc_path_cache_buffers(ListBase *bufs, int tot, int steps)
162 ParticleCacheKey **cache;
163 int i, totkey, totbufkey;
167 cache = MEM_callocN(tot*sizeof(void*), "PathCacheArray");
169 while(totkey < tot) {
170 totbufkey= MIN2(tot-totkey, PATH_CACHE_BUF_SIZE);
171 buf= MEM_callocN(sizeof(LinkData), "PathCacheLinkData");
172 buf->data= MEM_callocN(sizeof(ParticleCacheKey)*totbufkey*steps, "ParticleCacheKey");
174 for(i=0; i<totbufkey; i++)
175 cache[totkey+i] = ((ParticleCacheKey*)buf->data) + i*steps;
178 BLI_addtail(bufs, buf);
184 static void psys_free_path_cache_buffers(ParticleCacheKey **cache, ListBase *bufs)
191 for(buf= bufs->first; buf; buf=buf->next)
192 MEM_freeN(buf->data);
196 /************************************************/
198 /************************************************/
199 /* get object's active particle system safely */
200 ParticleSystem *psys_get_current(Object *ob)
202 ParticleSystem *psys;
205 for(psys=ob->particlesystem.first; psys; psys=psys->next){
206 if(psys->flag & PSYS_CURRENT)
212 short psys_get_current_num(Object *ob)
214 ParticleSystem *psys;
219 for(psys=ob->particlesystem.first, i=0; psys; psys=psys->next, i++)
220 if(psys->flag & PSYS_CURRENT)
225 /* change object's active particle system */
226 void psys_change_act(void *ob_v, void *act_v)
229 ParticleSystem *npsys, *psys;
230 short act = *((short*)act_v)-1;
233 npsys=BLI_findlink(&ob->particlesystem,act);
234 psys=psys_get_current(ob);
237 psys->flag &= ~PSYS_CURRENT;
239 npsys->flag |= PSYS_CURRENT;
242 Object *psys_get_lattice(Scene *scene, Object *ob, ParticleSystem *psys)
246 if(psys_in_edit_mode(scene, psys)==0){
248 ModifierData *md = (ModifierData*)psys_get_modifier(ob,psys);
250 for(; md; md=md->next){
251 if(md->type==eModifierType_Lattice){
252 LatticeModifierData *lmd = (LatticeModifierData *)md;
258 init_latt_deform(lattice,0);
263 void psys_disable_all(Object *ob)
265 ParticleSystem *psys=ob->particlesystem.first;
267 for(; psys; psys=psys->next)
268 psys->flag |= PSYS_DISABLED;
270 void psys_enable_all(Object *ob)
272 ParticleSystem *psys=ob->particlesystem.first;
274 for(; psys; psys=psys->next)
275 psys->flag &= ~PSYS_DISABLED;
277 int psys_ob_has_hair(Object *ob)
279 ParticleSystem *psys = ob->particlesystem.first;
281 for(; psys; psys=psys->next)
282 if(psys->part->type == PART_HAIR)
287 int psys_in_edit_mode(Scene *scene, ParticleSystem *psys)
289 return ((G.f & G_PARTICLEEDIT) && psys==psys_get_current((scene->basact)->object) && psys->edit);
291 int psys_check_enabled(Object *ob, ParticleSystem *psys)
293 ParticleSystemModifierData *psmd;
296 if(psys->flag & PSYS_DISABLED || psys->flag & PSYS_DELETE)
299 if(ob->type == OB_MESH) {
301 if(me->mr && me->mr->current != 1)
305 psmd= psys_get_modifier(ob, psys);
306 if(psys->renderdata) {
307 if(!(psmd->modifier.mode & eModifierMode_Render))
310 else if(!(psmd->modifier.mode & eModifierMode_Realtime))
316 /************************************************/
318 /************************************************/
319 void psys_free_settings(ParticleSettings *part)
326 MEM_freeN(part->pd2);
331 void free_hair(ParticleSystem *psys, int softbody)
334 int i, totpart=psys->totpart;
336 for(i=0, pa=psys->particles; i<totpart; i++, pa++) {
342 psys->flag &= ~PSYS_HAIR_DONE;
344 if(softbody && psys->soft) {
349 void free_keyed_keys(ParticleSystem *psys)
351 if(psys->particles && psys->particles->keys)
352 MEM_freeN(psys->particles->keys);
354 void free_child_path_cache(ParticleSystem *psys)
356 psys_free_path_cache_buffers(psys->childcache, &psys->childcachebufs);
357 psys->childcache = NULL;
358 psys->totchildcache = 0;
360 void psys_free_path_cache(ParticleSystem *psys)
362 psys_free_path_cache_buffers(psys->pathcache, &psys->pathcachebufs);
363 psys->pathcache= NULL;
366 free_child_path_cache(psys);
368 void psys_free_children(ParticleSystem *psys)
371 MEM_freeN(psys->child);
376 free_child_path_cache(psys);
378 /* free everything */
379 void psys_free(Object *ob, ParticleSystem * psys)
383 ParticleSystem * tpsys;
385 if(ob->particlesystem.first == NULL && G.f & G_PARTICLEEDIT)
386 G.f &= ~G_PARTICLEEDIT;
388 psys_free_path_cache(psys);
392 free_keyed_keys(psys);
394 if(psys->edit && psys->free_edit)
395 psys->free_edit(psys);
398 MEM_freeN(psys->particles);
404 MEM_freeN(psys->child);
409 if(psys->effectors.first)
410 psys_end_effectors(psys);
412 // check if we are last non-visible particle system
413 for(tpsys=ob->particlesystem.first; tpsys; tpsys=tpsys->next){
416 if(ELEM(tpsys->part->draw_as,PART_DRAW_OB,PART_DRAW_GR))
423 // clear do-not-draw-flag
425 ob->transflag &= ~OB_DUPLIPARTS;
432 if(psys->reactevents.first)
433 BLI_freelistN(&psys->reactevents);
436 BKE_ptcache_free(psys->pointcache);
442 /* these functions move away particle data and bring it back after
443 * rendering, to make different render settings possible without
444 * removing the previous data. this should be solved properly once */
446 typedef struct ParticleRenderElem {
447 int curchild, totchild, reduce;
448 float lambda, t, scalemin, scalemax;
449 } ParticleRenderElem;
451 typedef struct ParticleRenderData {
452 ChildParticle *child;
453 ParticleCacheKey **pathcache;
454 ParticleCacheKey **childcache;
455 int totchild, totcached, totchildcache;
457 int totdmvert, totdmedge, totdmface;
460 float viewmat[4][4], winmat[4][4];
465 ParticleRenderElem *elems;
467 } ParticleRenderData;
469 static float psys_render_viewport_falloff(double rate, float dist, float width)
471 return pow(rate, dist/width);
474 static float psys_render_projected_area(ParticleSystem *psys, float *center, float area, double vprate, float *viewport)
476 ParticleRenderData *data= psys->renderdata;
477 float co[4], view[3], ortho1[3], ortho2[3], w, dx, dy, radius;
479 /* transform to view space */
482 Mat4MulVec4fl(data->viewmat, co);
484 /* compute two vectors orthogonal to view vector */
487 VecOrthoBasisf(view, ortho1, ortho2);
489 /* compute on screen minification */
490 w= co[2]*data->winmat[2][3] + data->winmat[3][3];
491 dx= data->winx*ortho2[0]*data->winmat[0][0];
492 dy= data->winy*ortho2[1]*data->winmat[1][1];
493 w= sqrt(dx*dx + dy*dy)/w;
495 /* w squared because we are working with area */
498 /* viewport of the screen test */
500 /* project point on screen */
501 Mat4MulVec4fl(data->winmat, co);
503 co[0]= 0.5f*data->winx*(1.0f + co[0]/co[3]);
504 co[1]= 0.5f*data->winy*(1.0f + co[1]/co[3]);
507 /* screen space radius */
508 radius= sqrt(area/M_PI);
510 /* make smaller using fallof once over screen edge */
513 if(co[0]+radius < 0.0f)
514 *viewport *= psys_render_viewport_falloff(vprate, -(co[0]+radius), data->winx);
515 else if(co[0]-radius > data->winx)
516 *viewport *= psys_render_viewport_falloff(vprate, (co[0]-radius) - data->winx, data->winx);
518 if(co[1]+radius < 0.0f)
519 *viewport *= psys_render_viewport_falloff(vprate, -(co[1]+radius), data->winy);
520 else if(co[1]-radius > data->winy)
521 *viewport *= psys_render_viewport_falloff(vprate, (co[1]-radius) - data->winy, data->winy);
526 void psys_render_set(Object *ob, ParticleSystem *psys, float viewmat[][4], float winmat[][4], int winx, int winy, int timeoffset)
528 ParticleRenderData*data;
529 ParticleSystemModifierData *psmd= psys_get_modifier(ob, psys);
536 data= MEM_callocN(sizeof(ParticleRenderData), "ParticleRenderData");
538 data->child= psys->child;
539 data->totchild= psys->totchild;
540 data->pathcache= psys->pathcache;
541 data->totcached= psys->totcached;
542 data->childcache= psys->childcache;
543 data->totchildcache= psys->totchildcache;
546 data->dm= CDDM_copy(psmd->dm);
547 data->totdmvert= psmd->totdmvert;
548 data->totdmedge= psmd->totdmedge;
549 data->totdmface= psmd->totdmface;
552 psys->pathcache= NULL;
553 psys->childcache= NULL;
554 psys->totchild= psys->totcached= psys->totchildcache= 0;
556 Mat4CpyMat4(data->winmat, winmat);
557 Mat4MulMat4(data->viewmat, ob->obmat, viewmat);
558 Mat4MulMat4(data->mat, data->viewmat, winmat);
562 data->timeoffset= timeoffset;
564 psys->renderdata= data;
567 void psys_render_restore(Object *ob, ParticleSystem *psys)
569 ParticleRenderData*data;
570 ParticleSystemModifierData *psmd= psys_get_modifier(ob, psys);
572 data= psys->renderdata;
577 MEM_freeN(data->elems);
580 psmd->dm->needsFree= 1;
581 psmd->dm->release(psmd->dm);
584 psys_free_path_cache(psys);
587 MEM_freeN(psys->child);
592 psys->child= data->child;
593 psys->totchild= data->totchild;
594 psys->pathcache= data->pathcache;
595 psys->totcached= data->totcached;
596 psys->childcache= data->childcache;
597 psys->totchildcache= data->totchildcache;
600 psmd->totdmvert= data->totdmvert;
601 psmd->totdmedge= data->totdmedge;
602 psmd->totdmface= data->totdmface;
603 psmd->flag &= ~eParticleSystemFlag_psys_updated;
606 psys_calc_dmcache(ob, psmd->dm, psys);
609 psys->renderdata= NULL;
612 int psys_render_simplify_distribution(ParticleThreadContext *ctx, int tot)
614 DerivedMesh *dm= ctx->dm;
615 Mesh *me= (Mesh*)(ctx->ob->data);
618 ParticleRenderData *data;
619 ParticleRenderElem *elems, *elem;
620 ParticleSettings *part= ctx->psys->part;
621 float *facearea, (*facecenter)[3], size[3], fac, powrate, scaleclamp;
622 float co1[3], co2[3], co3[3], co4[3], lambda, arearatio, t, area, viewport;
624 int *origindex, *facetotvert;
625 int a, b, totorigface, totface, newtot, skipped;
627 if(part->draw_as!=PART_DRAW_PATH || !(part->draw & PART_DRAW_REN_STRAND))
629 if(!ctx->psys->renderdata)
632 data= ctx->psys->renderdata;
635 if(!(part->simplify_flag & PART_SIMPLIFY_ENABLE))
638 mvert= dm->getVertArray(dm);
639 mface= dm->getFaceArray(dm);
640 origindex= dm->getFaceDataArray(dm, CD_ORIGINDEX);
641 totface= dm->getNumFaces(dm);
642 totorigface= me->totface;
644 if(totface == 0 || totorigface == 0 || origindex == NULL)
647 facearea= MEM_callocN(sizeof(float)*totorigface, "SimplifyFaceArea");
648 facecenter= MEM_callocN(sizeof(float[3])*totorigface, "SimplifyFaceCenter");
649 facetotvert= MEM_callocN(sizeof(int)*totorigface, "SimplifyFaceArea");
650 elems= MEM_callocN(sizeof(ParticleRenderElem)*totorigface, "SimplifyFaceElem");
653 MEM_freeN(data->elems);
657 data->origindex= origindex;
659 /* compute number of children per original face */
660 for(a=0; a<tot; a++) {
661 b= origindex[ctx->index[a]];
666 /* compute areas and centers of original faces */
667 for(mf=mface, a=0; a<totface; a++, mf++) {
671 VECCOPY(co1, mvert[mf->v1].co);
672 VECCOPY(co2, mvert[mf->v2].co);
673 VECCOPY(co3, mvert[mf->v3].co);
675 VECADD(facecenter[b], facecenter[b], co1);
676 VECADD(facecenter[b], facecenter[b], co2);
677 VECADD(facecenter[b], facecenter[b], co3);
680 VECCOPY(co4, mvert[mf->v4].co);
681 VECADD(facecenter[b], facecenter[b], co4);
682 facearea[b] += AreaQ3Dfl(co1, co2, co3, co4);
686 facearea[b] += AreaT3Dfl(co1, co2, co3);
692 for(a=0; a<totorigface; a++)
693 if(facetotvert[a] > 0)
694 VecMulf(facecenter[a], 1.0f/facetotvert[a]);
696 /* for conversion from BU area / pixel area to reference screen size */
697 mesh_get_texspace(me, 0, 0, size);
698 fac= ((size[0] + size[1] + size[2])/3.0f)/part->simplify_refsize;
701 powrate= log(0.5f)/log(part->simplify_rate*0.5f);
702 if(part->simplify_flag & PART_SIMPLIFY_VIEWPORT)
703 vprate= pow(1.0 - part->simplify_viewport, 5.0);
707 /* set simplification parameters per original face */
708 for(a=0, elem=elems; a<totorigface; a++, elem++) {
709 area = psys_render_projected_area(ctx->psys, facecenter[a], facearea[a], vprate, &viewport);
710 arearatio= fac*area/facearea[a];
712 if((arearatio < 1.0f || viewport < 1.0f) && elem->totchild) {
713 /* lambda is percentage of elements to keep */
714 lambda= (arearatio < 1.0f)? pow(arearatio, powrate): 1.0f;
717 lambda= MAX2(lambda, 1.0f/elem->totchild);
719 /* compute transition region */
720 t= part->simplify_transition;
721 elem->t= (lambda-t < 0.0f)? lambda: (lambda+t > 1.0f)? 1.0f-lambda: t;
724 /* scale at end and beginning of the transition region */
725 elem->scalemax= (lambda+t < 1.0f)? 1.0f/lambda: 1.0f/(1.0f - elem->t*elem->t/t);
726 elem->scalemin= (lambda+t < 1.0f)? 0.0f: elem->scalemax*(1.0f-elem->t/t);
728 elem->scalemin= sqrt(elem->scalemin);
729 elem->scalemax= sqrt(elem->scalemax);
732 scaleclamp= MIN2(elem->totchild, 10.0f);
733 elem->scalemin= MIN2(scaleclamp, elem->scalemin);
734 elem->scalemax= MIN2(scaleclamp, elem->scalemax);
736 /* extend lambda to include transition */
737 lambda= lambda + elem->t;
744 elem->scalemax= 1.0f; //sqrt(lambda);
745 elem->scalemin= 1.0f; //sqrt(lambda);
749 elem->lambda= lambda;
750 elem->scalemin= sqrt(elem->scalemin);
751 elem->scalemax= sqrt(elem->scalemax);
756 MEM_freeN(facecenter);
757 MEM_freeN(facetotvert);
759 /* move indices and set random number skipping */
760 ctx->skip= MEM_callocN(sizeof(int)*tot, "SimplificationSkip");
763 for(a=0, newtot=0; a<tot; a++) {
764 b= origindex[ctx->index[a]];
766 if(elems[b].curchild++ < ceil(elems[b].lambda*elems[b].totchild)) {
767 ctx->index[newtot]= ctx->index[a];
768 ctx->skip[newtot]= skipped;
777 for(a=0, elem=elems; a<totorigface; a++, elem++)
783 int psys_render_simplify_params(ParticleSystem *psys, ChildParticle *cpa, float *params)
785 ParticleRenderData *data;
786 ParticleRenderElem *elem;
787 float x, w, scale, alpha, lambda, t, scalemin, scalemax;
790 if(!(psys->renderdata && (psys->part->simplify_flag & PART_SIMPLIFY_ENABLE)))
793 data= psys->renderdata;
794 if(!data->dosimplify)
797 b= data->origindex[cpa->num];
801 elem= &data->elems[b];
803 lambda= elem->lambda;
805 scalemin= elem->scalemin;
806 scalemax= elem->scalemax;
813 x= (elem->curchild+0.5f)/elem->totchild;
818 else if(x >= lambda+t) {
823 w= (lambda+t - x)/(2.0f*t);
824 scale= scalemin + (scalemax - scalemin)*w;
837 /************************************************/
838 /* Interpolated Particles */
839 /************************************************/
840 static float interpolate_particle_value(float v1, float v2, float v3, float v4, float *w, int four)
844 value= w[0]*v1 + w[1]*v2 + w[2]*v3;
850 static void weighted_particle_vector(float *v1, float *v2, float *v3, float *v4, float *weights, float *vec)
852 vec[0]= weights[0]*v1[0] + weights[1]*v2[0] + weights[2]*v3[0] + weights[3]*v4[0];
853 vec[1]= weights[0]*v1[1] + weights[1]*v2[1] + weights[2]*v3[1] + weights[3]*v4[1];
854 vec[2]= weights[0]*v1[2] + weights[1]*v2[2] + weights[2]*v3[2] + weights[3]*v4[2];
856 static void interpolate_particle(short type, ParticleKey keys[4], float dt, ParticleKey *result, int velocity)
861 VecfCubicInterpol(keys[1].co, keys[1].vel, keys[2].co, keys[2].vel, dt, result->co, result->vel);
864 set_four_ipo(dt, t, type);
866 weighted_particle_vector(keys[0].co, keys[1].co, keys[2].co, keys[3].co, t, result->co);
872 set_four_ipo(dt-0.001f, t, type);
873 weighted_particle_vector(keys[0].co, keys[1].co, keys[2].co, keys[3].co, t, temp);
874 VECSUB(result->vel, result->co, temp);
877 set_four_ipo(dt+0.001f, t, type);
878 weighted_particle_vector(keys[0].co, keys[1].co, keys[2].co, keys[3].co, t, temp);
879 VECSUB(result->vel, temp, result->co);
887 /************************************************/
888 /* Particles on a dm */
889 /************************************************/
890 /* interpolate a location on a face based on face coordinates */
891 void psys_interpolate_face(MVert *mvert, MFace *mface, MTFace *tface, float (*orcodata)[3], float *w, float *vec, float *nor, float *utan, float *vtan, float *orco,float *ornor){
892 float *v1=0, *v2=0, *v3=0, *v4=0;
893 float e1[3],e2[3],s1,s2,t1,t2;
894 float *uv1, *uv2, *uv3, *uv4;
895 float n1[3], n2[3], n3[3], n4[3];
897 float *o1, *o2, *o3, *o4;
899 v1= (mvert+mface->v1)->co;
900 v2= (mvert+mface->v2)->co;
901 v3= (mvert+mface->v3)->co;
902 VECCOPY(n1,(mvert+mface->v1)->no);
903 VECCOPY(n2,(mvert+mface->v2)->no);
904 VECCOPY(n3,(mvert+mface->v3)->no);
910 v4= (mvert+mface->v4)->co;
911 VECCOPY(n4,(mvert+mface->v4)->no);
914 vec[0]= w[0]*v1[0] + w[1]*v2[0] + w[2]*v3[0] + w[3]*v4[0];
915 vec[1]= w[0]*v1[1] + w[1]*v2[1] + w[2]*v3[1] + w[3]*v4[1];
916 vec[2]= w[0]*v1[2] + w[1]*v2[2] + w[2]*v3[2] + w[3]*v4[2];
919 if(mface->flag & ME_SMOOTH){
920 nor[0]= w[0]*n1[0] + w[1]*n2[0] + w[2]*n3[0] + w[3]*n4[0];
921 nor[1]= w[0]*n1[1] + w[1]*n2[1] + w[2]*n3[1] + w[3]*n4[1];
922 nor[2]= w[0]*n1[2] + w[1]*n2[2] + w[2]*n3[2] + w[3]*n4[2];
925 CalcNormFloat4(v1,v2,v3,v4,nor);
929 vec[0]= w[0]*v1[0] + w[1]*v2[0] + w[2]*v3[0];
930 vec[1]= w[0]*v1[1] + w[1]*v2[1] + w[2]*v3[1];
931 vec[2]= w[0]*v1[2] + w[1]*v2[2] + w[2]*v3[2];
934 if(mface->flag & ME_SMOOTH){
935 nor[0]= w[0]*n1[0] + w[1]*n2[0] + w[2]*n3[0];
936 nor[1]= w[0]*n1[1] + w[1]*n2[1] + w[2]*n3[1];
937 nor[2]= w[0]*n1[2] + w[1]*n2[2] + w[2]*n3[2];
940 CalcNormFloat(v1,v2,v3,nor);
944 /* calculate tangent vectors */
953 uv1= tuv[0]; uv2= tuv[1]; uv3= tuv[2]; uv4= tuv[3];
954 spheremap(v1[0], v1[1], v1[2], uv1, uv1+1);
955 spheremap(v2[0], v2[1], v2[2], uv2, uv2+1);
956 spheremap(v3[0], v3[1], v3[2], uv3, uv3+1);
958 spheremap(v4[0], v4[1], v4[2], uv4, uv4+1);
982 vtan[0] = (s1*e2[0] - s2*e1[0]);
983 vtan[1] = (s1*e2[1] - s2*e1[1]);
984 vtan[2] = (s1*e2[2] - s2*e1[2]);
986 utan[0] = (t1*e2[0] - t2*e1[0]);
987 utan[1] = (t1*e2[1] - t2*e1[1]);
988 utan[2] = (t1*e2[2] - t2*e1[2]);
993 o1= orcodata[mface->v1];
994 o2= orcodata[mface->v2];
995 o3= orcodata[mface->v3];
998 o4= orcodata[mface->v4];
999 orco[0]= w[0]*o1[0] + w[1]*o2[0] + w[2]*o3[0] + w[3]*o4[0];
1000 orco[1]= w[0]*o1[1] + w[1]*o2[1] + w[2]*o3[1] + w[3]*o4[1];
1001 orco[2]= w[0]*o1[2] + w[1]*o2[2] + w[2]*o3[2] + w[3]*o4[2];
1004 CalcNormFloat4(o1, o2, o3, o4, ornor);
1007 orco[0]= w[0]*o1[0] + w[1]*o2[0] + w[2]*o3[0];
1008 orco[1]= w[0]*o1[1] + w[1]*o2[1] + w[2]*o3[1];
1009 orco[2]= w[0]*o1[2] + w[1]*o2[2] + w[2]*o3[2];
1012 CalcNormFloat(o1, o2, o3, ornor);
1018 VECCOPY(ornor, nor);
1022 void psys_interpolate_uvs(MTFace *tface, int quad, float *w, float *uvco)
1024 float v10= tface->uv[0][0];
1025 float v11= tface->uv[0][1];
1026 float v20= tface->uv[1][0];
1027 float v21= tface->uv[1][1];
1028 float v30= tface->uv[2][0];
1029 float v31= tface->uv[2][1];
1033 v40= tface->uv[3][0];
1034 v41= tface->uv[3][1];
1036 uvco[0]= w[0]*v10 + w[1]*v20 + w[2]*v30 + w[3]*v40;
1037 uvco[1]= w[0]*v11 + w[1]*v21 + w[2]*v31 + w[3]*v41;
1040 uvco[0]= w[0]*v10 + w[1]*v20 + w[2]*v30;
1041 uvco[1]= w[0]*v11 + w[1]*v21 + w[2]*v31;
1045 void psys_interpolate_mcol(MCol *mcol, int quad, float *w, MCol *mc)
1047 char *cp, *cp1, *cp2, *cp3, *cp4;
1050 cp1= (char *)&mcol[0];
1051 cp2= (char *)&mcol[1];
1052 cp3= (char *)&mcol[2];
1055 cp4= (char *)&mcol[3];
1057 cp[0]= (int)(w[0]*cp1[0] + w[1]*cp2[0] + w[2]*cp3[0] + w[3]*cp4[0]);
1058 cp[1]= (int)(w[0]*cp1[1] + w[1]*cp2[1] + w[2]*cp3[1] + w[3]*cp4[1]);
1059 cp[2]= (int)(w[0]*cp1[2] + w[1]*cp2[2] + w[2]*cp3[2] + w[3]*cp4[2]);
1060 cp[3]= (int)(w[0]*cp1[3] + w[1]*cp2[3] + w[2]*cp3[3] + w[3]*cp4[3]);
1063 cp[0]= (int)(w[0]*cp1[0] + w[1]*cp2[0] + w[2]*cp3[0]);
1064 cp[1]= (int)(w[0]*cp1[1] + w[1]*cp2[1] + w[2]*cp3[1]);
1065 cp[2]= (int)(w[0]*cp1[2] + w[1]*cp2[2] + w[2]*cp3[2]);
1066 cp[3]= (int)(w[0]*cp1[3] + w[1]*cp2[3] + w[2]*cp3[3]);
1070 float psys_interpolate_value_from_verts(DerivedMesh *dm, short from, int index, float *fw, float *values)
1072 if(values==0 || index==-1)
1076 case PART_FROM_VERT:
1077 return values[index];
1078 case PART_FROM_FACE:
1079 case PART_FROM_VOLUME:
1081 MFace *mf=dm->getFaceData(dm,index,CD_MFACE);
1082 return interpolate_particle_value(values[mf->v1],values[mf->v2],values[mf->v3],values[mf->v4],fw,mf->v4);
1089 /* conversion of pa->fw to origspace layer coordinates */
1090 static void psys_w_to_origspace(float *w, float *uv)
1096 /* conversion of pa->fw to weights in face from origspace */
1097 static void psys_origspace_to_w(OrigSpaceFace *osface, int quad, float *w, float *neww)
1099 float v[4][3], co[3];
1101 v[0][0]= osface->uv[0][0]; v[0][1]= osface->uv[0][1]; v[0][2]= 0.0f;
1102 v[1][0]= osface->uv[1][0]; v[1][1]= osface->uv[1][1]; v[1][2]= 0.0f;
1103 v[2][0]= osface->uv[2][0]; v[2][1]= osface->uv[2][1]; v[2][2]= 0.0f;
1105 psys_w_to_origspace(w, co);
1109 v[3][0]= osface->uv[3][0]; v[3][1]= osface->uv[3][1]; v[3][2]= 0.0f;
1110 MeanValueWeights(v, 4, co, neww);
1113 MeanValueWeights(v, 3, co, neww);
1118 /* find the derived mesh face for a particle, set the mf passed. this is slow
1119 * and can be optimized but only for many lookups. returns the face index. */
1120 int psys_particle_dm_face_lookup(Object *ob, DerivedMesh *dm, int index, float *fw, struct LinkNode *node)
1122 Mesh *me= (Mesh*)ob->data;
1124 OrigSpaceFace *osface;
1126 int quad, findex, totface;
1127 float uv[2], (*faceuv)[2];
1129 mface = dm->getFaceDataArray(dm, CD_MFACE);
1130 origindex = dm->getFaceDataArray(dm, CD_ORIGINDEX);
1131 osface = dm->getFaceDataArray(dm, CD_ORIGSPACE);
1133 totface = dm->getNumFaces(dm);
1135 if(osface==NULL || origindex==NULL) {
1136 /* Assume we dont need osface data */
1137 if (index <totface) {
1138 //printf("\tNO CD_ORIGSPACE, assuming not needed\n");
1141 printf("\tNO CD_ORIGSPACE, error out of range\n");
1142 return DMCACHE_NOTFOUND;
1145 else if(index >= me->totface)
1146 return DMCACHE_NOTFOUND; /* index not in the original mesh */
1148 psys_w_to_origspace(fw, uv);
1150 if(node) { /* we have a linked list of faces that we use, faster! */
1151 for(;node; node=node->next) {
1152 findex= GET_INT_FROM_POINTER(node->link);
1153 faceuv= osface[findex].uv;
1154 quad= mface[findex].v4;
1156 /* check that this intersects - Its possible this misses :/ -
1157 * could also check its not between */
1159 if(IsectPQ2Df(uv, faceuv[0], faceuv[1], faceuv[2], faceuv[3]))
1162 else if(IsectPT2Df(uv, faceuv[0], faceuv[1], faceuv[2]))
1166 else { /* if we have no node, try every face */
1167 for(findex=0; findex<totface; findex++) {
1168 if(origindex[findex] == index) {
1169 faceuv= osface[findex].uv;
1170 quad= mface[findex].v4;
1172 /* check that this intersects - Its possible this misses :/ -
1173 * could also check its not between */
1175 if(IsectPQ2Df(uv, faceuv[0], faceuv[1], faceuv[2], faceuv[3]))
1178 else if(IsectPT2Df(uv, faceuv[0], faceuv[1], faceuv[2]))
1184 return DMCACHE_NOTFOUND;
1187 static int psys_map_index_on_dm(DerivedMesh *dm, int from, int index, int index_dmcache, float *fw, float foffset, int *mapindex, float *mapfw)
1192 if (dm->deformedOnly || index_dmcache == DMCACHE_ISCHILD) {
1193 /* for meshes that are either only defined or for child particles, the
1194 * index and fw do not require any mapping, so we can directly use it */
1195 if(from == PART_FROM_VERT) {
1196 if(index >= dm->getNumVerts(dm))
1201 else { /* FROM_FACE/FROM_VOLUME */
1202 if(index >= dm->getNumFaces(dm))
1206 QUATCOPY(mapfw, fw);
1209 /* for other meshes that have been modified, we try to map the particle
1210 * to their new location, which means a different index, and for faces
1211 * also a new face interpolation weights */
1212 if(from == PART_FROM_VERT) {
1213 if (index_dmcache == DMCACHE_NOTFOUND || index_dmcache > dm->getNumVerts(dm))
1216 *mapindex = index_dmcache;
1218 else { /* FROM_FACE/FROM_VOLUME */
1219 /* find a face on the derived mesh that uses this face */
1221 OrigSpaceFace *osface;
1226 if(i== DMCACHE_NOTFOUND || i >= dm->getNumFaces(dm))
1231 /* modify the original weights to become
1232 * weights for the derived mesh face */
1233 osface= dm->getFaceDataArray(dm, CD_ORIGSPACE);
1234 mface= dm->getFaceData(dm, i, CD_MFACE);
1237 mapfw[0]= mapfw[1]= mapfw[2]= mapfw[3]= 0.0f;
1239 psys_origspace_to_w(&osface[i], mface->v4, fw, mapfw);
1246 /* interprets particle data to get a point on a mesh in object space */
1247 void psys_particle_on_dm(DerivedMesh *dm, int from, int index, int index_dmcache, float *fw, float foffset, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor)
1249 float tmpnor[3], mapfw[4];
1250 float (*orcodata)[3];
1253 if(!psys_map_index_on_dm(dm, from, index, index_dmcache, fw, foffset, &mapindex, mapfw)) {
1254 if(vec) { vec[0]=vec[1]=vec[2]=0.0; }
1255 if(nor) { nor[0]=nor[1]=0.0; nor[2]=1.0; }
1256 if(orco) { orco[0]=orco[1]=orco[2]=0.0; }
1257 if(ornor) { ornor[0]=ornor[1]=0.0; ornor[2]=1.0; }
1258 if(utan) { utan[0]=utan[1]=utan[2]=0.0; }
1259 if(vtan) { vtan[0]=vtan[1]=vtan[2]=0.0; }
1264 orcodata= dm->getVertDataArray(dm, CD_ORCO);
1266 if(from == PART_FROM_VERT) {
1267 dm->getVertCo(dm,mapindex,vec);
1270 dm->getVertNo(dm,mapindex,nor);
1275 VECCOPY(orco, orcodata[mapindex])
1278 dm->getVertNo(dm,mapindex,nor);
1283 utan[0]= utan[1]= utan[2]= 0.0f;
1284 vtan[0]= vtan[1]= vtan[2]= 0.0f;
1287 else { /* PART_FROM_FACE / PART_FROM_VOLUME */
1292 mface=dm->getFaceData(dm,mapindex,CD_MFACE);
1293 mvert=dm->getVertDataArray(dm,CD_MVERT);
1294 mtface=CustomData_get_layer(&dm->faceData,CD_MTFACE);
1299 if(from==PART_FROM_VOLUME) {
1300 psys_interpolate_face(mvert,mface,mtface,orcodata,mapfw,vec,tmpnor,utan,vtan,orco,ornor);
1302 VECCOPY(nor,tmpnor);
1305 VecMulf(tmpnor,-foffset);
1306 VECADD(vec,vec,tmpnor);
1309 psys_interpolate_face(mvert,mface,mtface,orcodata,mapfw,vec,nor,utan,vtan,orco,ornor);
1313 float psys_particle_value_from_verts(DerivedMesh *dm, short from, ParticleData *pa, float *values)
1318 if(!psys_map_index_on_dm(dm, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, &mapindex, mapfw))
1321 return psys_interpolate_value_from_verts(dm, from, mapindex, mapfw, values);
1324 ParticleSystemModifierData *psys_get_modifier(Object *ob, ParticleSystem *psys)
1327 ParticleSystemModifierData *psmd;
1329 for(md=ob->modifiers.first; md; md=md->next){
1330 if(md->type==eModifierType_ParticleSystem){
1331 psmd= (ParticleSystemModifierData*) md;
1332 if(psmd->psys==psys){
1339 /************************************************/
1340 /* Particles on a shape */
1341 /************************************************/
1342 /* ready for future use */
1343 static void psys_particle_on_shape(int distr, int index, float *fuv, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor)
1346 float zerovec[3]={0.0f,0.0f,0.0f};
1348 VECCOPY(vec,zerovec);
1351 VECCOPY(nor,zerovec);
1354 VECCOPY(utan,zerovec);
1357 VECCOPY(vtan,zerovec);
1360 VECCOPY(orco,zerovec);
1363 VECCOPY(ornor,zerovec);
1366 /************************************************/
1367 /* Particles on emitter */
1368 /************************************************/
1369 void psys_particle_on_emitter(ParticleSystemModifierData *psmd, int from, int index, int index_dmcache, float *fuv, float foffset, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor){
1371 if(psmd->psys->part->distr==PART_DISTR_GRID && psmd->psys->part->from != PART_FROM_VERT){
1377 /* we cant use the num_dmcache */
1378 psys_particle_on_dm(psmd->dm,from,index,index_dmcache,fuv,foffset,vec,nor,utan,vtan,orco,ornor);
1381 psys_particle_on_shape(from,index,fuv,vec,nor,utan,vtan,orco,ornor);
1384 /************************************************/
1386 /************************************************/
1387 static void hair_to_particle(ParticleKey *key, HairKey *hkey)
1389 VECCOPY(key->co, hkey->co);
1390 key->time = hkey->time;
1392 static void bp_to_particle(ParticleKey *key, BodyPoint *bp, HairKey *hkey)
1394 VECCOPY(key->co, bp->pos);
1395 key->time = hkey->time;
1397 static float vert_weight(MDeformVert *dvert, int group)
1404 for(i= dvert->totweight; i>0; i--, dw++) {
1405 if(dw->def_nr == group) return dw->weight;
1406 if(i==1) break; /*otherwise dw will point to somewhere it shouldn't*/
1412 static void do_prekink(ParticleKey *state, ParticleKey *par, float *par_rot, float time, float freq, float shape, float amplitude, short type, short axis, float obmat[][4])
1414 float vec[3]={0.0,0.0,0.0}, q1[4]={1,0,0,0},q2[4];
1417 CLAMP(time,0.0,1.0);
1419 if(shape!=0.0f && type!=PART_KINK_BRAID) {
1421 time= (float)pow(time, 1.0+shape);
1423 time= (float)pow(time, 1.0/(1.0-shape));
1428 t*=(float)M_PI*freq;
1433 case PART_KINK_CURL:
1436 QUATCOPY(q2,par_rot)
1438 vectoquat(par->vel,axis,(axis+1)%3, q2);
1439 QuatMulVecf(q2,vec);
1440 VecMulf(vec,amplitude);
1441 VECADD(state->co,state->co,vec);
1443 VECSUB(vec,state->co,par->co);
1446 VecRotToQuat(par->vel,t,q1);
1448 QuatMulVecf(q1,vec);
1450 VECADD(state->co,par->co,vec);
1452 case PART_KINK_RADIAL:
1453 VECSUB(vec,state->co,par->co);
1456 VecMulf(vec,amplitude*(float)sin(t));
1458 VECADD(state->co,state->co,vec);
1460 case PART_KINK_WAVE:
1463 Mat4Mul3Vecfl(obmat,vec);
1466 QuatMulVecf(par_rot,vec);
1468 Projf(q1,vec,par->vel);
1473 VecMulf(vec,amplitude*(float)sin(t));
1475 VECADD(state->co,state->co,vec);
1477 case PART_KINK_BRAID:
1479 float y_vec[3]={0.0,1.0,0.0};
1480 float z_vec[3]={0.0,0.0,1.0};
1481 float vec_from_par[3], vec_one[3], radius, state_co[3];
1482 float inp_y,inp_z,length;
1485 QUATCOPY(q2,par_rot)
1487 vectoquat(par->vel,axis,(axis+1)%3,q2);
1488 QuatMulVecf(q2,y_vec);
1489 QuatMulVecf(q2,z_vec);
1491 VECSUB(vec_from_par,state->co,par->co);
1492 VECCOPY(vec_one,vec_from_par);
1493 radius=Normalize(vec_one);
1495 inp_y=Inpf(y_vec,vec_one);
1496 inp_z=Inpf(z_vec,vec_one);
1499 VECCOPY(state_co,y_vec);
1501 VecMulf(y_vec,amplitude*(float)cos(t));
1502 VecMulf(z_vec,amplitude/2.0f*(float)sin(2.0f*t));
1505 VECCOPY(state_co,z_vec);
1506 VecMulf(state_co,(float)sin(M_PI/3.0f));
1507 VECADDFAC(state_co,state_co,y_vec,-0.5f);
1509 VecMulf(y_vec,-amplitude*(float)cos(t + M_PI/3.0f));
1510 VecMulf(z_vec,amplitude/2.0f*(float)cos(2.0f*t + M_PI/6.0f));
1513 VECCOPY(state_co,z_vec);
1514 VecMulf(state_co,-(float)sin(M_PI/3.0f));
1515 VECADDFAC(state_co,state_co,y_vec,-0.5f);
1517 VecMulf(y_vec,amplitude*(float)-sin(t+M_PI/6.0f));
1518 VecMulf(z_vec,amplitude/2.0f*(float)-sin(2.0f*t+M_PI/3.0f));
1521 VecMulf(state_co,amplitude);
1522 VECADD(state_co,state_co,par->co);
1523 VECSUB(vec_from_par,state->co,state_co);
1525 length=Normalize(vec_from_par);
1526 VecMulf(vec_from_par,MIN2(length,amplitude/2.0f));
1528 VECADD(state_co,par->co,y_vec);
1529 VECADD(state_co,state_co,z_vec);
1530 VECADD(state_co,state_co,vec_from_par);
1532 shape=(2.0f*(float)M_PI)*(1.0f+shape);
1536 shape=(float)sqrt((double)shape);
1537 VecLerpf(state->co,state->co,state_co,shape);
1540 VECCOPY(state->co,state_co);
1547 static void do_clump(ParticleKey *state, ParticleKey *par, float time, float clumpfac, float clumppow, float pa_clump)
1549 if(par && clumpfac!=0.0){
1555 cpow=1.0f+9.0f*clumppow;
1557 if(clumpfac<0.0) /* clump roots instead of tips */
1558 clump = -clumpfac*pa_clump*(float)pow(1.0-(double)time,(double)cpow);
1560 clump = clumpfac*pa_clump*(float)pow((double)time,(double)cpow);
1561 VecLerpf(state->co,state->co,par->co,clump);
1565 int do_guide(Scene *scene, ParticleKey *state, int pa_num, float time, ListBase *lb)
1568 ParticleEffectorCache *ec;
1571 ParticleKey key, par;
1573 float effect[3]={0.0,0.0,0.0}, distance, f_force, mindist, totforce=0.0;
1574 float guidevec[4], guidedir[3], rot2[4], temp[3], angle, pa_loc[3], pa_zero[3]={0.0f,0.0f,0.0f};
1575 float veffect[3]={0.0,0.0,0.0}, guidetime;
1577 effect[0]=effect[1]=effect[2]=0.0;
1580 for(ec = lb->first; ec; ec= ec->next){
1582 if(ec->type & PSYS_EC_EFFECTOR){
1584 if(pd->forcefield==PFIELD_GUIDE){
1585 cu = (Curve*)eob->data;
1587 distance=ec->distances[pa_num];
1588 mindist=pd->f_strength;
1590 VECCOPY(pa_loc, ec->locations+3*pa_num);
1591 VECCOPY(pa_zero,pa_loc);
1592 VECADD(pa_zero,pa_zero,ec->firstloc);
1594 guidetime=time/(1.0-pd->free_end);
1596 /* WARNING: bails out with continue here */
1597 if(((pd->flag & PFIELD_USEMAX) && distance>pd->maxdist) || guidetime>1.0f) continue;
1599 if(guidetime>1.0f) continue;
1601 /* calculate contribution factor for this guide */
1603 if(distance<=mindist);
1604 else if(pd->flag & PFIELD_USEMAX) {
1605 if(mindist>=pd->maxdist) f_force= 0.0f;
1606 else if(pd->f_power!=0.0f){
1607 f_force= 1.0f - (distance-mindist)/(pd->maxdist - mindist);
1608 f_force = (float)pow(f_force, pd->f_power);
1611 else if(pd->f_power!=0.0f){
1612 f_force= 1.0f/(1.0f + distance-mindist);
1613 f_force = (float)pow(f_force, pd->f_power);
1616 if(pd->flag & PFIELD_GUIDE_PATH_ADD)
1617 where_on_path(eob, f_force*guidetime, guidevec, guidedir);
1619 where_on_path(eob, guidetime, guidevec, guidedir);
1621 Mat4MulVecfl(ec->ob->obmat,guidevec);
1622 Mat4Mul3Vecfl(ec->ob->obmat,guidedir);
1624 Normalize(guidedir);
1627 /* curve direction */
1628 Crossf(temp, ec->firstdir, guidedir);
1629 angle=Inpf(ec->firstdir,guidedir)/(VecLength(ec->firstdir));
1630 angle=saacos(angle);
1631 VecRotToQuat(temp,angle,rot2);
1632 QuatMulVecf(rot2,pa_loc);
1635 VecRotToQuat(guidedir,guidevec[3]-ec->firstloc[3],rot2);
1636 QuatMulVecf(rot2,pa_loc);
1638 //vectoquat(guidedir, pd->kink_axis, (pd->kink_axis+1)%3, q);
1639 //QuatMul(par.rot,rot2,q);
1643 // par.rot[1]=par.rot[2]=par.rot[3]=0.0f;
1648 VecMulf(pa_loc, calc_taper(scene, cu->taperobj, (int)(f_force*guidetime*100.0), 100));
1653 par.co[0]=par.co[1]=par.co[2]=0.0f;
1654 VECCOPY(key.co,pa_loc);
1655 do_prekink(&key, &par, 0, guidetime, pd->kink_freq, pd->kink_shape, pd->kink_amp, pd->kink, pd->kink_axis, 0);
1656 do_clump(&key, &par, guidetime, pd->clump_fac, pd->clump_pow, 1.0f);
1657 VECCOPY(pa_loc,key.co);
1659 VECADD(pa_loc,pa_loc,guidevec);
1660 VECSUB(pa_loc,pa_loc,pa_zero);
1661 VECADDFAC(effect,effect,pa_loc,f_force);
1662 VECADDFAC(veffect,veffect,guidedir,f_force);
1670 VecMulf(effect,1.0f/totforce);
1671 CLAMP(totforce,0.0,1.0);
1672 VECADD(effect,effect,pa_zero);
1673 VecLerpf(state->co,state->co,effect,totforce);
1676 VecMulf(veffect,VecLength(state->vel));
1677 VECCOPY(state->vel,veffect);
1683 static void do_rough(float *loc, float t, float fac, float size, float thres, ParticleKey *state)
1689 if((float)fabs((float)(-1.5+loc[0]+loc[1]+loc[2]))<1.5f*thres) return;
1693 rough[0]=-1.0f+2.0f*BLI_gTurbulence(size, rco[0], rco[1], rco[2], 2,0,2);
1694 rough[1]=-1.0f+2.0f*BLI_gTurbulence(size, rco[1], rco[2], rco[0], 2,0,2);
1695 rough[2]=-1.0f+2.0f*BLI_gTurbulence(size, rco[2], rco[0], rco[1], 2,0,2);
1696 VECADDFAC(state->co,state->co,rough,fac);
1698 static void do_rough_end(float *loc, float t, float fac, float shape, ParticleKey *state, ParticleKey *par)
1700 float rough[3], rnor[3];
1703 roughfac=fac*(float)pow((double)t,shape);
1705 rough[0]=-1.0f+2.0f*rough[0];
1706 rough[1]=-1.0f+2.0f*rough[1];
1707 rough[2]=-1.0f+2.0f*rough[2];
1708 VecMulf(rough,roughfac);
1712 VECCOPY(rnor,par->vel);
1715 VECCOPY(rnor,state->vel);
1718 Projf(rnor,rough,rnor);
1719 VECSUB(rough,rough,rnor);
1721 VECADD(state->co,state->co,rough);
1723 static void do_path_effectors(Scene *scene, Object *ob, ParticleSystem *psys, int i, ParticleCacheKey *ca, int k, int steps, float *rootco, float effector, float dfra, float cfra, float *length, float *vec)
1725 float force[3] = {0.0f,0.0f,0.0f}, vel[3] = {0.0f,0.0f,0.0f};
1726 ParticleKey eff_key;
1729 VECCOPY(eff_key.co,(ca-1)->co);
1730 VECCOPY(eff_key.vel,(ca-1)->vel);
1731 QUATCOPY(eff_key.rot,(ca-1)->rot);
1733 pa= psys->particles+i;
1734 do_effectors(i, pa, &eff_key, scene, ob, psys, rootco, force, vel, dfra, cfra);
1736 VecMulf(force, effector*pow((float)k / (float)steps, 100.0f * psys->part->eff_hair) / (float)steps);
1738 VecAddf(force, force, vec);
1743 VecSubf(vec, (ca+1)->co, ca->co);
1744 *length = VecLength(vec);
1747 VECADDFAC(ca->co, (ca-1)->co, force, *length);
1749 static int check_path_length(int k, ParticleCacheKey *keys, ParticleCacheKey *state, float max_length, float *cur_length, float length, float *dvec)
1751 if(*cur_length + length > max_length){
1752 VecMulf(dvec, (max_length - *cur_length) / length);
1753 VECADD(state->co, (state - 1)->co, dvec);
1755 /* something over the maximum step value */
1759 *cur_length+=length;
1763 static void offset_child(ChildParticle *cpa, ParticleKey *par, ParticleKey *child, float flat, float radius)
1765 VECCOPY(child->co,cpa->fuv);
1766 VecMulf(child->co,radius);
1770 VECCOPY(child->vel,par->vel);
1772 QuatMulVecf(par->rot,child->co);
1774 QUATCOPY(child->rot,par->rot);
1776 VECADD(child->co,child->co,par->co);
1778 float *psys_cache_vgroup(DerivedMesh *dm, ParticleSystem *psys, int vgroup)
1782 if(psys->vgroup[vgroup]){
1783 MDeformVert *dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
1785 int totvert=dm->getNumVerts(dm), i;
1786 vg=MEM_callocN(sizeof(float)*totvert, "vg_cache");
1787 if(psys->vg_neg&(1<<vgroup)){
1788 for(i=0; i<totvert; i++)
1789 vg[i]=1.0f-vert_weight(dvert+i,psys->vgroup[vgroup]-1);
1792 for(i=0; i<totvert; i++)
1793 vg[i]=vert_weight(dvert+i,psys->vgroup[vgroup]-1);
1799 void psys_find_parents(Object *ob, ParticleSystemModifierData *psmd, ParticleSystem *psys)
1801 ParticleSettings *part=psys->part;
1804 int p, totparent,totchild=psys->totchild;
1805 float co[3], orco[3];
1806 int from=PART_FROM_FACE;
1807 totparent=(int)(totchild*part->parents*0.3);
1809 if(G.rendering && part->child_nbr && part->ren_child_nbr)
1810 totparent*=(float)part->child_nbr/(float)part->ren_child_nbr;
1812 tree=BLI_kdtree_new(totparent);
1814 for(p=0,cpa=psys->child; p<totparent; p++,cpa++){
1815 psys_particle_on_emitter(psmd,from,cpa->num,DMCACHE_ISCHILD,cpa->fuv,cpa->foffset,co,0,0,0,orco,0);
1816 BLI_kdtree_insert(tree, p, orco, NULL);
1819 BLI_kdtree_balance(tree);
1821 for(; p<totchild; p++,cpa++){
1822 psys_particle_on_emitter(psmd,from,cpa->num,DMCACHE_ISCHILD,cpa->fuv,cpa->foffset,co,0,0,0,orco,0);
1823 cpa->parent=BLI_kdtree_find_nearest(tree, orco, NULL, NULL);
1826 BLI_kdtree_free(tree);
1829 static void get_strand_normal(Material *ma, float *surfnor, float surfdist, float *nor)
1831 float cross[3], nstrand[3], vnor[3], blend;
1833 if(!((ma->mode & MA_STR_SURFDIFF) || (ma->strand_surfnor > 0.0f)))
1836 if(ma->mode & MA_STR_SURFDIFF) {
1837 Crossf(cross, surfnor, nor);
1838 Crossf(nstrand, nor, cross);
1840 blend= INPR(nstrand, surfnor);
1841 CLAMP(blend, 0.0f, 1.0f);
1843 VecLerpf(vnor, nstrand, surfnor, blend);
1849 if(ma->strand_surfnor > 0.0f) {
1850 if(ma->strand_surfnor > surfdist) {
1851 blend= (ma->strand_surfnor - surfdist)/ma->strand_surfnor;
1852 VecLerpf(vnor, vnor, surfnor, blend);
1860 int psys_threads_init_path(ParticleThread *threads, Scene *scene, float cfra, int editupdate)
1862 ParticleThreadContext *ctx= threads[0].ctx;
1863 Object *ob= ctx->ob;
1864 ParticleSystem *psys= ctx->psys;
1865 ParticleSettings *part = psys->part;
1866 ParticleEditSettings *pset = &scene->toolsettings->particle;
1867 int totparent=0, between=0;
1868 int steps = (int)pow(2.0,(double)part->draw_step);
1869 int totchild = psys->totchild;
1870 int i, seed, totthread= threads[0].tot;
1872 /*---start figuring out what is actually wanted---*/
1873 if(psys_in_edit_mode(scene, psys))
1874 if(psys->renderdata==0 && (psys->edit==NULL || pset->flag & PE_SHOW_CHILD)==0)
1877 if(totchild && part->from!=PART_FROM_PARTICLE && part->childtype==PART_CHILD_FACES){
1878 totparent=(int)(totchild*part->parents*0.3);
1880 if(G.rendering && part->child_nbr && part->ren_child_nbr)
1881 totparent*=(float)part->child_nbr/(float)part->ren_child_nbr;
1883 /* part->parents could still be 0 so we can't test with totparent */
1887 if(psys->renderdata)
1888 steps=(int)pow(2.0,(double)part->ren_step);
1890 totchild=(int)((float)totchild*(float)part->disp/100.0f);
1891 totparent=MIN2(totparent,totchild);
1894 if(totchild==0) return 0;
1896 /* init random number generator */
1897 if(ctx->psys->part->flag & PART_ANIM_BRANCHING)
1898 seed= 31415926 + ctx->psys->seed + (int)cfra;
1900 seed= 31415926 + ctx->psys->seed;
1902 if(part->flag & PART_BRANCHING || ctx->editupdate || totchild < 10000)
1905 for(i=0; i<totthread; i++) {
1906 threads[i].rng_path= rng_new(seed);
1907 threads[i].tot= totthread;
1910 /* fill context values */
1911 ctx->between= between;
1913 ctx->totchild= totchild;
1914 ctx->totparent= totparent;
1915 ctx->parent_pass= 0;
1918 psys->lattice = psys_get_lattice(scene, ob, psys);
1920 /* cache all relevant vertex groups if they exist */
1921 if(part->from!=PART_FROM_PARTICLE){
1922 ctx->vg_length = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_LENGTH);
1923 ctx->vg_clump = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_CLUMP);
1924 ctx->vg_kink = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_KINK);
1925 ctx->vg_rough1 = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_ROUGH1);
1926 ctx->vg_rough2 = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_ROUGH2);
1927 ctx->vg_roughe = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_ROUGHE);
1928 if(psys->part->flag & PART_CHILD_EFFECT)
1929 ctx->vg_effector = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_EFFECTOR);
1932 /* set correct ipo timing */
1933 #if 0 // XXX old animation system
1934 if(part->flag&PART_ABS_TIME && part->ipo){
1935 calc_ipo(part->ipo, cfra);
1936 execute_ipo((ID *)part, part->ipo);
1938 #endif // XXX old animation system
1943 /* note: this function must be thread safe, except for branching! */
1944 void psys_thread_create_path(ParticleThread *thread, struct ChildParticle *cpa, ParticleCacheKey *keys, int i)
1946 ParticleThreadContext *ctx= thread->ctx;
1947 Object *ob= ctx->ob;
1948 ParticleSystem *psys = ctx->psys;
1949 ParticleSettings *part = psys->part;
1950 ParticleCacheKey **cache= psys->childcache;
1951 ParticleCacheKey **pcache= psys->pathcache;
1952 ParticleCacheKey *state, *par = NULL, *key[4];
1953 ParticleData *pa=NULL;
1954 ParticleTexture ptex;
1955 float *cpa_fuv=0, *par_rot=0;
1956 float co[3], orco[3], ornor[3], t, rough_t, cpa_1st[3], dvec[3];
1957 float branch_begin, branch_end, branch_prob, branchfac, rough_rand;
1958 float pa_rough1, pa_rough2, pa_roughe;
1959 float length, pa_length, pa_clump, pa_kink, pa_effector;
1960 float max_length = 1.0f, cur_length = 0.0f;
1961 float eff_length, eff_vec[3];
1962 int k, cpa_num, guided = 0;
1965 if(part->flag & PART_BRANCHING) {
1966 branch_begin=rng_getFloat(thread->rng_path);
1967 branch_end=branch_begin+(1.0f-branch_begin)*rng_getFloat(thread->rng_path);
1968 branch_prob=rng_getFloat(thread->rng_path);
1969 rough_rand=rng_getFloat(thread->rng_path);
1978 if(i<psys->totpart){
1988 if(ctx->editupdate && !(part->flag & PART_BRANCHING)) {
1991 while(w<4 && cpa->pa[w]>=0) {
1992 if(psys->particles[cpa->pa[w]].flag & PARS_EDIT_RECALC) {
2002 memset(keys, 0, sizeof(*keys)*(ctx->steps+1));
2005 /* get parent paths */
2007 while(w<4 && cpa->pa[w]>=0){
2008 key[w] = pcache[cpa->pa[w]];
2012 /* get the original coordinates (orco) for texture usage */
2015 foffset= cpa->foffset;
2016 if(part->childtype == PART_CHILD_FACES)
2017 foffset = -(2.0f + part->childspread);
2019 cpa_from = PART_FROM_FACE;
2021 psys_particle_on_emitter(ctx->psmd,cpa_from,cpa_num,DMCACHE_ISCHILD,cpa->fuv,foffset,co,ornor,0,0,orco,0);
2023 /* we need to save the actual root position of the child for positioning it accurately to the surface of the emitter */
2024 VECCOPY(cpa_1st,co);
2025 Mat4MulVecfl(ob->obmat,cpa_1st);
2030 if(ctx->editupdate && !(part->flag & PART_BRANCHING)) {
2031 if(!(psys->particles[cpa->parent].flag & PARS_EDIT_RECALC))
2034 memset(keys, 0, sizeof(*keys)*(ctx->steps+1));
2037 /* get the parent path */
2038 key[0]=pcache[cpa->parent];
2040 /* get the original coordinates (orco) for texture usage */
2041 pa=psys->particles+cpa->parent;
2043 cpa_from=part->from;
2047 psys_particle_on_emitter(ctx->psmd,cpa_from,cpa_num,DMCACHE_ISCHILD,cpa_fuv,pa->foffset,co,ornor,0,0,orco,0);
2050 keys->steps = ctx->steps;
2052 /* correct child ipo timing */
2053 #if 0 // XXX old animation system
2054 if((part->flag&PART_ABS_TIME)==0 && part->ipo){
2055 float dsta=part->end-part->sta;
2056 calc_ipo(part->ipo, 100.0f*(ctx->cfra-(part->sta+dsta*cpa->rand[1]))/(part->lifetime*(1.0f - part->randlife*cpa->rand[0])));
2057 execute_ipo((ID *)part, part->ipo);
2059 #endif // XXX old animation system
2061 /* get different child parameters from textures & vgroups */
2062 ptex.length=part->length*(1.0f - part->randlength*cpa->rand[0]);
2068 get_cpa_texture(ctx->dm,ctx->ma,cpa_num,cpa_fuv,orco,&ptex,
2069 MAP_PA_DENS|MAP_PA_LENGTH|MAP_PA_CLUMP|MAP_PA_KINK|MAP_PA_ROUGH);
2071 pa_length=ptex.length;
2072 pa_clump=ptex.clump;
2074 pa_rough1=ptex.rough;
2075 pa_rough2=ptex.rough;
2076 pa_roughe=ptex.rough;
2079 if(ptex.exist < cpa->rand[1]) {
2085 pa_length*=psys_interpolate_value_from_verts(ctx->dm,cpa_from,cpa_num,cpa_fuv,ctx->vg_length);
2087 pa_clump*=psys_interpolate_value_from_verts(ctx->dm,cpa_from,cpa_num,cpa_fuv,ctx->vg_clump);
2089 pa_kink*=psys_interpolate_value_from_verts(ctx->dm,cpa_from,cpa_num,cpa_fuv,ctx->vg_kink);
2091 pa_rough1*=psys_interpolate_value_from_verts(ctx->dm,cpa_from,cpa_num,cpa_fuv,ctx->vg_rough1);
2093 pa_rough2*=psys_interpolate_value_from_verts(ctx->dm,cpa_from,cpa_num,cpa_fuv,ctx->vg_rough2);
2095 pa_roughe*=psys_interpolate_value_from_verts(ctx->dm,cpa_from,cpa_num,cpa_fuv,ctx->vg_roughe);
2096 if(ctx->vg_effector)
2097 pa_effector*=psys_interpolate_value_from_verts(ctx->dm,cpa_from,cpa_num,cpa_fuv,ctx->vg_effector);
2099 /* create the child path */
2100 for(k=0,state=keys; k<=ctx->steps; k++,state++){
2104 state->co[0] = state->co[1] = state->co[2] = 0.0f;
2105 state->vel[0] = state->vel[1] = state->vel[2] = 0.0f;
2106 state->rot[0] = state->rot[1] = state->rot[2] = state->rot[3] = 0.0f;
2108 //QUATCOPY(state->rot,key[0]->rot);
2110 /* child position is the weighted sum of parent positions */
2111 while(w<4 && cpa->pa[w]>=0){
2112 state->co[0] += cpa->w[w] * key[w]->co[0];
2113 state->co[1] += cpa->w[w] * key[w]->co[1];
2114 state->co[2] += cpa->w[w] * key[w]->co[2];
2116 state->vel[0] += cpa->w[w] * key[w]->vel[0];
2117 state->vel[1] += cpa->w[w] * key[w]->vel[1];
2118 state->vel[2] += cpa->w[w] * key[w]->vel[2];
2123 /* calculate the offset between actual child root position and first position interpolated from parents */
2124 VECSUB(cpa_1st,cpa_1st,state->co);
2126 /* apply offset for correct positioning */
2127 VECADD(state->co,state->co,cpa_1st);
2130 /* offset the child from the parent position */
2131 offset_child(cpa, (ParticleKey*)key[0], (ParticleKey*)state, part->childflat, part->childrad);
2137 /* apply effectors */
2138 if(part->flag & PART_CHILD_EFFECT) {
2139 for(k=0,state=keys; k<=ctx->steps; k++,state++) {
2141 do_path_effectors(ctx->scene, ob, psys, cpa->pa[0], state, k, ctx->steps, keys->co, pa_effector, 0.0f, ctx->cfra, &eff_length, eff_vec);
2144 VecSubf(eff_vec,(state+1)->co,state->co);
2145 eff_length= VecLength(eff_vec);
2150 for(k=0,state=keys; k<=ctx->steps; k++,state++){
2151 t=(float)k/(float)ctx->steps;
2154 if(i>=ctx->totparent) {
2155 /* this is now threadsafe, virtual parents are calculated before rest of children */
2156 par = cache[cpa->parent] + k;
2161 else if(cpa->parent>=0){
2162 par=pcache[cpa->parent]+k;
2166 /* apply different deformations to the child path */
2167 if(part->flag & PART_CHILD_EFFECT)
2168 /* state is safe to cast, since only co and vel are used */
2169 guided = do_guide(ctx->scene, (ParticleKey*)state, cpa->parent, t, &(psys->effectors));
2173 do_prekink((ParticleKey*)state, (ParticleKey*)par, par_rot, t,
2174 part->kink_freq * pa_kink, part->kink_shape, part->kink_amp, part->kink, part->kink_axis, ob->obmat);
2176 do_clump((ParticleKey*)state, (ParticleKey*)par, t, part->clumpfac, part->clumppow, pa_clump);
2179 if(part->flag & PART_BRANCHING && ctx->between == 0 && part->flag & PART_ANIM_BRANCHING)
2180 rough_t = t * rough_rand;
2184 if(part->rough1 != 0.0 && pa_rough1 != 0.0)
2185 do_rough(orco, rough_t, pa_rough1*part->rough1, part->rough1_size, 0.0, (ParticleKey*)state);
2187 if(part->rough2 != 0.0 && pa_rough2 != 0.0)
2188 do_rough(cpa->rand, rough_t, pa_rough2*part->rough2, part->rough2_size, part->rough2_thres, (ParticleKey*)state);
2190 if(part->rough_end != 0.0 && pa_roughe != 0.0)
2191 do_rough_end(cpa->rand, rough_t, pa_roughe*part->rough_end, part->rough_end_shape, (ParticleKey*)state, (ParticleKey*)par);
2193 if(part->flag & PART_BRANCHING && ctx->between==0){
2194 if(branch_prob > part->branch_thres){
2198 if(part->flag & PART_SYMM_BRANCHING){
2199 if(t < branch_begin || t > branch_end)
2202 if((t-branch_begin)/(branch_end-branch_begin)<0.5)
2203 branchfac=2.0f*(t-branch_begin)/(branch_end-branch_begin);
2205 branchfac=2.0f*(branch_end-t)/(branch_end-branch_begin);
2207 CLAMP(branchfac,0.0f,1.0f);
2211 if(t < branch_begin){
2215 branchfac=(t-branch_begin)/((1.0f-branch_begin)*0.5f);
2216 CLAMP(branchfac,0.0f,1.0f);
2222 VecLerpf(state->co, (pcache[i] + k)->co, state->co, branchfac);
2224 /* this is not threadsafe, but should only happen for
2225 * branching particles particles, which are not threaded */
2226 VecLerpf(state->co, (cache[i - psys->totpart] + k)->co, state->co, branchfac);
2229 /* we have to correct velocity because of kink & clump */
2231 VECSUB((state-1)->vel,state->co,(state-2)->co);
2232 VecMulf((state-1)->vel,0.5);
2234 if(ctx->ma && (part->draw & PART_DRAW_MAT_COL))
2235 get_strand_normal(ctx->ma, ornor, cur_length, (state-1)->vel);
2238 /* check if path needs to be cut before actual end of data points */
2240 VECSUB(dvec,state->co,(state-1)->co);
2241 if(part->flag&PART_ABS_LENGTH)
2242 length=VecLength(dvec);
2244 length=1.0f/(float)ctx->steps;
2246 k=check_path_length(k,keys,state,max_length,&cur_length,length,dvec);
2249 /* initialize length calculation */
2250 if(part->flag&PART_ABS_LENGTH)
2251 max_length= part->abslength*pa_length;
2253 max_length= pa_length;
2258 if(ctx->ma && (part->draw & PART_DRAW_MAT_COL)) {
2259 VECCOPY(state->col, &ctx->ma->r)
2260 get_strand_normal(ctx->ma, ornor, cur_length, state->vel);
2265 static void *exec_child_path_cache(void *data)
2267 ParticleThread *thread= (ParticleThread*)data;
2268 ParticleThreadContext *ctx= thread->ctx;
2269 ParticleSystem *psys= ctx->psys;
2270 ParticleCacheKey **cache= psys->childcache;
2272 int i, totchild= ctx->totchild, first= 0;
2274 if(thread->tot > 1){
2275 first= ctx->parent_pass? 0 : ctx->totparent;
2276 totchild= ctx->parent_pass? ctx->totparent : ctx->totchild;
2279 cpa= psys->child + first + thread->num;
2280 for(i=first+thread->num; i<totchild; i+=thread->tot, cpa+=thread->tot)
2281 psys_thread_create_path(thread, cpa, cache[i], i);
2286 void psys_cache_child_paths(Scene *scene, Object *ob, ParticleSystem *psys, float cfra, int editupdate)
2288 ParticleSettings *part = psys->part;
2289 ParticleThread *pthreads;
2290 ParticleThreadContext *ctx;
2291 ParticleCacheKey **cache;
2293 int i, totchild, totparent, totthread;
2295 pthreads= psys_threads_create(scene, ob, psys);
2297 if(!psys_threads_init_path(pthreads, scene, cfra, editupdate)) {
2298 psys_threads_free(pthreads);
2302 ctx= pthreads[0].ctx;
2303 totchild= ctx->totchild;
2304 totparent= ctx->totparent;
2306 if(editupdate && psys->childcache && !(part->flag & PART_BRANCHING) && totchild == psys->totchildcache) {
2307 cache = psys->childcache;
2310 /* clear out old and create new empty path cache */
2311 free_child_path_cache(psys);
2312 psys->childcache= psys_alloc_path_cache_buffers(&psys->childcachebufs, totchild, ctx->steps+1);
2313 psys->totchildcache = totchild;
2316 totthread= pthreads[0].tot;
2320 /* make virtual child parents thread safe by calculating them first */
2322 BLI_init_threads(&threads, exec_child_path_cache, totthread);
2324 for(i=0; i<totthread; i++) {
2325 pthreads[i].ctx->parent_pass = 1;
2326 BLI_insert_thread(&threads, &pthreads[i]);
2329 BLI_end_threads(&threads);
2331 for(i=0; i<totthread; i++)
2332 pthreads[i].ctx->parent_pass = 0;
2335 BLI_init_threads(&threads, exec_child_path_cache, totthread);
2337 for(i=0; i<totthread; i++)
2338 BLI_insert_thread(&threads, &pthreads[i]);
2340 BLI_end_threads(&threads);
2343 exec_child_path_cache(&pthreads[0]);
2345 psys_threads_free(pthreads);
2348 /* Calculates paths ready for drawing/rendering. */
2349 /* -Usefull for making use of opengl vertex arrays for super fast strand drawing. */
2350 /* -Makes child strands possible and creates them too into the cache. */
2351 /* -Cached path data is also used to determine cut position for the editmode tool. */
2352 void psys_cache_paths(Scene *scene, Object *ob, ParticleSystem *psys, float cfra, int editupdate)
2354 ParticleCacheKey *ca, **cache=psys->pathcache;
2355 ParticleSystemModifierData *psmd = psys_get_modifier(ob, psys);
2356 ParticleEditSettings *pset = &scene->toolsettings->particle;
2357 ParticleSettings *part = psys->part;
2360 ParticleKey keys[4], result, *kkey[2] = {NULL, NULL};
2361 HairKey *hkey[2] = {NULL, NULL};
2363 ParticleEdit *edit = 0;
2364 ParticleEditKey *ekey = 0;
2367 BodyPoint *bp[2] = {NULL, NULL};
2371 float birthtime = 0.0, dietime = 0.0;
2372 float t, time = 0.0, keytime = 0.0, dfra = 1.0, frs_sec = scene->r.frs_sec;
2373 float col[3] = {0.5f, 0.5f, 0.5f};
2374 float prev_tangent[3], hairmat[4][4];
2376 int steps = (int)pow(2.0, (double)psys->part->draw_step);
2377 int totpart = psys->totpart;
2380 float length, vec[3];
2381 float *vg_effector= NULL, effector=0.0f;
2382 float *vg_length= NULL, pa_length=1.0f, max_length=1.0f, cur_length=0.0f;
2385 /* we don't have anything valid to create paths from so let's quit here */
2386 if((psys->flag & PSYS_HAIR_DONE)==0 && (psys->flag & PSYS_KEYED)==0)
2389 if(psys->renderdata) {
2390 steps = (int)pow(2.0, (double)psys->part->ren_step);
2392 else if(psys_in_edit_mode(scene, psys)) {
2395 //timed = edit->draw_timed;
2397 if(pset->brushtype == PE_BRUSH_WEIGHT) {
2398 sel_col[0] = sel_col[1] = sel_col[2] = 1.0f;
2399 nosel_col[0] = nosel_col[1] = nosel_col[2] = 0.0f;
2402 sel_col[0] = (float)edit->sel_col[0] / 255.0f;
2403 sel_col[1] = (float)edit->sel_col[1] / 255.0f;
2404 sel_col[2] = (float)edit->sel_col[2] / 255.0f;
2405 nosel_col[0] = (float)edit->nosel_col[0] / 255.0f;
2406 nosel_col[1] = (float)edit->nosel_col[1] / 255.0f;
2407 nosel_col[2] = (float)edit->nosel_col[2] / 255.0f;
2411 if(editupdate && psys->pathcache && totpart == psys->totcached) {
2412 cache = psys->pathcache;
2415 /* clear out old and create new empty path cache */
2416 psys_free_path_cache(psys);
2417 cache= psys_alloc_path_cache_buffers(&psys->pathcachebufs, totpart, steps+1);
2418 psys->pathcache= cache;
2421 if(edit==NULL && psys->soft && psys->softflag & OB_SB_ENABLE) {
2427 psys->lattice = psys_get_lattice(scene, ob, psys);
2428 ma= give_current_material(ob, psys->part->omat);
2429 if(ma && (psys->part->draw & PART_DRAW_MAT_COL))
2430 VECCOPY(col, &ma->r)
2432 if(psys->part->from!=PART_FROM_PARTICLE) {
2433 if(!(psys->part->flag & PART_CHILD_EFFECT))
2434 vg_effector = psys_cache_vgroup(psmd->dm, psys, PSYS_VG_EFFECTOR);
2436 if(!edit && !psys->totchild)
2437 vg_length = psys_cache_vgroup(psmd->dm, psys, PSYS_VG_LENGTH);
2440 /*---first main loop: create all actual particles' paths---*/
2441 for(i=0,pa=psys->particles; i<totpart; i++, pa++){
2442 if(psys && edit==NULL && (pa->flag & PARS_NO_DISP || pa->flag & PARS_UNEXIST)) {
2444 bp[0] += pa->totkey; /* TODO use of initialized value? */
2448 if(editupdate && !(pa->flag & PARS_EDIT_RECALC)) continue;
2449 else memset(cache[i], 0, sizeof(*cache[i])*(steps+1));
2451 if(!edit && !psys->totchild) {
2452 pa_length = part->length * (1.0f - part->randlength*pa->r_ave[0]);
2454 pa_length *= psys_particle_value_from_verts(psmd->dm,part->from,pa,vg_length);
2457 cache[i]->steps = steps;
2460 ekey = edit->keys[i];
2462 /*--get the first data points--*/
2463 if(psys->flag & PSYS_KEYED) {
2465 kkey[1] = kkey[0] + 1;
2467 birthtime = kkey[0]->time;
2468 dietime = kkey[0][pa->totkey-1].time;
2472 hkey[1] = hkey[0] + 1;
2474 birthtime = hkey[0]->time;
2475 dietime = hkey[0][pa->totkey-1].time;
2477 psys_mat_hair_to_global(ob, psmd->dm, psys->part->from, pa, hairmat);
2481 bp[0] = soft->bpoint + pa->bpi;
2485 /*--interpolate actual path from data points--*/
2486 for(k=0, ca=cache[i]; k<=steps; k++, ca++){
2487 time = (float)k / (float)steps;
2489 t = birthtime + time * (dietime - birthtime);
2491 if(psys->flag & PSYS_KEYED) {
2492 while(kkey[1]->time < t) {
2496 kkey[0] = kkey[1] - 1;
2499 while(hkey[1]->time < t) {
2504 hkey[0] = hkey[1] - 1;
2509 bp_to_particle(keys + 1, bp[0], hkey[0]);
2510 bp_to_particle(keys + 2, bp[1], hkey[1]);
2512 else if(psys->flag & PSYS_KEYED) {
2513 memcpy(keys + 1, kkey[0], sizeof(ParticleKey));
2514 memcpy(keys + 2, kkey[1], sizeof(ParticleKey));
2517 hair_to_particle(keys + 1, hkey[0]);
2518 hair_to_particle(keys + 2, hkey[1]);
2522 if((psys->flag & PSYS_KEYED)==0) {
2524 if(hkey[0] != pa->hair)
2525 bp_to_particle(keys, bp[0] - 1, hkey[0] - 1);
2527 bp_to_particle(keys, bp[0], hkey[0]);
2530 if(hkey[0] != pa->hair)
2531 hair_to_particle(keys, hkey[0] - 1);
2533 hair_to_particle(keys, hkey[0]);
2537 if(hkey[1] != pa->hair + pa->totkey - 1)
2538 bp_to_particle(keys + 3, bp[1] + 1, hkey[1] + 1);
2540 bp_to_particle(keys + 3, bp[1], hkey[1]);
2543 if(hkey[1] != pa->hair + pa->totkey - 1)
2544 hair_to_particle(keys + 3, hkey[1] + 1);
2546 hair_to_particle(keys + 3, hkey[1]);
2550 dfra = keys[2].time - keys[1].time;
2552 keytime = (t - keys[1].time) / dfra;
2554 /* convert velocity to timestep size */
2555 if(psys->flag & PSYS_KEYED){
2556 VecMulf(keys[1].vel, dfra / frs_sec);
2557 VecMulf(keys[2].vel, dfra / frs_sec);
2560 /* now we should have in chronologiacl order k1<=k2<=t<=k3<=k4 with keytime between [0,1]->[k2,k3] (k1 & k4 used for cardinal & bspline interpolation)*/
2561 interpolate_particle((psys->flag & PSYS_KEYED) ? -1 /* signal for cubic interpolation */
2562 : ((psys->part->flag & PART_HAIR_BSPLINE) ? KEY_BSPLINE : KEY_CARDINAL)
2563 ,keys, keytime, &result, 0);
2565 /* the velocity needs to be converted back from cubic interpolation */
2566 if(psys->flag & PSYS_KEYED){
2567 VecMulf(result.vel, frs_sec / dfra);
2569 else if(soft==NULL) { /* softbody and keyed are allready in global space */
2570 Mat4MulVecfl(hairmat, result.co);
2573 VECCOPY(ca->co, result.co);
2575 /* selection coloring in edit mode */
2577 if(pset->brushtype==PE_BRUSH_WEIGHT){
2579 VecLerpf(ca->col, nosel_col, sel_col, hkey[0]->weight);
2581 VecLerpf(ca->col, nosel_col, sel_col,
2582 (1.0f - keytime) * hkey[0]->weight + keytime * hkey[1]->weight);
2585 if((ekey + (hkey[0] - pa->hair))->flag & PEK_SELECT){
2586 if((ekey + (hkey[1] - pa->hair))->flag & PEK_SELECT){
2587 VECCOPY(ca->col, sel_col);
2590 VecLerpf(ca->col, sel_col, nosel_col, keytime);
2594 if((ekey + (hkey[1] - pa->hair))->flag & PEK_SELECT){
2595 VecLerpf(ca->col, nosel_col, sel_col, keytime);
2598 VECCOPY(ca->col, nosel_col);
2604 VECCOPY(ca->col, col);
2608 /*--modify paths--*/
2610 VecSubf(vec,(cache[i]+1)->co,cache[i]->co);
2611 length = VecLength(vec);
2615 effector*= psys_particle_value_from_verts(psmd->dm,psys->part->from,pa,vg_effector);
2617 for(k=0, ca=cache[i]; k<=steps; k++, ca++) {
2618 /* apply effectors */
2619 if(!(psys->part->flag & PART_CHILD_EFFECT) && edit==0 && k)
2620 do_path_effectors(scene, ob, psys, i, ca, k, steps, cache[i]->co, effector, dfra, cfra, &length, vec);
2622 /* apply guide curves to path data */
2623 if(edit==0 && psys->effectors.first && (psys->part->flag & PART_CHILD_EFFECT)==0)
2624 /* ca is safe to cast, since only co and vel are used */
2625 do_guide(scene, (ParticleKey*)ca, i, (float)k/(float)steps, &psys->effectors);
2628 if(psys->lattice && edit==0)
2629 calc_latt_deform(psys->lattice, ca->co, 1.0f);
2631 /* figure out rotation */
2634 float cosangle, angle, tangent[3], normal[3], q[4];
2637 VECSUB(tangent, ca->co, (ca - 1)->co);
2639 vectoquat(tangent, OB_POSX, OB_POSZ, (ca-1)->rot);
2641 VECCOPY(prev_tangent, tangent);
2642 Normalize(prev_tangent);
2645 VECSUB(tangent, ca->co, (ca - 1)->co);
2648 cosangle= Inpf(tangent, prev_tangent);
2650 /* note we do the comparison on cosangle instead of
2651 * angle, since floating point accuracy makes it give
2652 * different results across platforms */
2653 if(cosangle > 0.999999f) {
2654 QUATCOPY((ca - 1)->rot, (ca - 2)->rot);
2657 angle= saacos(cosangle);
2658 Crossf(normal, prev_tangent, tangent);
2659 VecRotToQuat(normal, angle, q);
2660 QuatMul((ca - 1)->rot, q, (ca - 2)->rot);
2663 VECCOPY(prev_tangent, tangent);
2667 QUATCOPY(ca->rot, (ca - 1)->rot);
2674 VECSUB(ca->vel, ca->co, (ca-1)->co);
2677 VECCOPY((ca-1)->vel, ca->vel);
2682 if(!edit && !psys->totchild) {
2683 /* check if path needs to be cut before actual end of data points */
2685 VECSUB(dvec,ca->co,(ca-1)->co);
2686 if(part->flag&PART_ABS_LENGTH)
2687 len=VecLength(dvec);
2689 len=1.0f/(float)steps;
2691 k=check_path_length(k,cache[i],ca,max_length,&cur_length,len,dvec);
2694 /* initialize length calculation */
2695 if(part->flag&PART_ABS_LENGTH)
2696 max_length= part->abslength*pa_length;
2698 max_length= pa_length;
2706 psys->totcached = totpart;
2708 if(psys && psys->lattice){
2709 end_latt_deform(psys->lattice);
2710 psys->lattice= NULL;
2714 MEM_freeN(vg_effector);
2717 MEM_freeN(vg_length);
2719 /************************************************/
2720 /* Particle Key handling */
2721 /************************************************/
2722 void copy_particle_key(ParticleKey *to, ParticleKey *from, int time){
2724 memcpy(to,from,sizeof(ParticleKey));
2727 float to_time=to->time;
2728 memcpy(to,from,sizeof(ParticleKey));
2732 VECCOPY(to->co,from->co);
2733 VECCOPY(to->vel,from->vel);
2734 QUATCOPY(to->rot,from->rot);
2736 to->time=from->time;
2737 to->flag=from->flag;
2741 void psys_get_from_key(ParticleKey *key, float *loc, float *vel, float *rot, float *time){
2742 if(loc) VECCOPY(loc,key->co);
2743 if(vel) VECCOPY(vel,key->vel);
2744 if(rot) QUATCOPY(rot,key->rot);
2745 if(time) *time=key->time;
2747 /*-------changing particle keys from space to another-------*/
2748 void psys_key_to_object(Object *ob, ParticleKey *key, float imat[][4]){
2749 float q[4], imat2[4][4];
2752 Mat4Invert(imat2,ob->obmat);
2756 VECADD(key->vel,key->vel,key->co);
2758 Mat4MulVecfl(imat,key->co);
2759 Mat4MulVecfl(imat,key->vel);
2762 VECSUB(key->vel,key->vel,key->co);
2763 QuatMul(key->rot,q,key->rot);
2765 static void key_from_object(Object *ob, ParticleKey *key){
2768 VECADD(key->vel,key->vel,key->co);
2770 Mat4MulVecfl(ob->obmat,key->co);
2771 Mat4MulVecfl(ob->obmat,key->vel);
2772 Mat4ToQuat(ob->obmat,q);
2774 VECSUB(key->vel,key->vel,key->co);
2775 QuatMul(key->rot,q,key->rot);
2778 static void triatomat(float *v1, float *v2, float *v3, float (*uv)[2], float mat[][4])
2780 float det, w1, w2, d1[2], d2[2];
2782 memset(mat, 0, sizeof(float)*4*4);
2785 /* first axis is the normal */
2786 CalcNormFloat(v1, v2, v3, mat[2]);
2788 /* second axis along (1, 0) in uv space */
2790 d1[0]= uv[1][0] - uv[0][0];
2791 d1[1]= uv[1][1] - uv[0][1];
2792 d2[0]= uv[2][0] - uv[0][0];
2793 d2[1]= uv[2][1] - uv[0][1];
2795 det = d2[0]*d1[1] - d2[1]*d1[0];
2802 mat[1][0]= w1*(v2[0] - v1[0]) + w2*(v3[0] - v1[0]);
2803 mat[1][1]= w1*(v2[1] - v1[1]) + w2*(v3[1] - v1[1]);
2804 mat[1][2]= w1*(v2[2] - v1[2]) + w2*(v3[2] - v1[2]);
2808 mat[1][0]= mat[1][1]= mat[1][2]= 0.0f;
2811 VecSubf(mat[1], v2, v1);
2815 /* third as a cross product */
2816 Crossf(mat[0], mat[1], mat[2]);
2819 static void psys_face_mat(Object *ob, DerivedMesh *dm, ParticleData *pa, float mat[][4], int orco)
2823 OrigSpaceFace *osface;
2824 float (*orcodata)[3];
2826 int i = pa->num_dmcache==DMCACHE_NOTFOUND ? pa->num : pa->num_dmcache;
2828 if (i==-1 || i >= dm->getNumFaces(dm)) { Mat4One(mat); return; }
2830 mface=dm->getFaceData(dm,i,CD_MFACE);
2831 osface=dm->getFaceData(dm,i,CD_ORIGSPACE);
2833 if(orco && (orcodata=dm->getVertDataArray(dm, CD_ORCO))) {
2834 VECCOPY(v[0], orcodata[mface->v1]);
2835 VECCOPY(v[1], orcodata[mface->v2]);
2836 VECCOPY(v[2], orcodata[mface->v3]);
2838 /* ugly hack to use non-transformed orcos, since only those
2839 * give symmetric results for mirroring in particle mode */
2840 transform_mesh_orco_verts(ob->data, v, 3, 1);
2843 dm->getVertCo(dm,mface->v1,v[0]);
2844 dm->getVertCo(dm,mface->v2,v[1]);
2845 dm->getVertCo(dm,mface->v3,v[2]);
2848 triatomat(v[0], v[1], v[2], (osface)? osface->uv: NULL, mat);
2851 void psys_mat_hair_to_object(Object *ob, DerivedMesh *dm, short from, ParticleData *pa, float hairmat[][4])
2855 psys_face_mat(0, dm, pa, hairmat, 0);
2856 psys_particle_on_dm(dm, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, vec, 0, 0, 0, 0, 0);
2857 VECCOPY(hairmat[3],vec);
2860 void psys_mat_hair_to_orco(Object *ob, DerivedMesh *dm, short from, ParticleData *pa, float hairmat[][4])
2862 float vec[3], orco[3];
2864 psys_face_mat(ob, dm, pa, hairmat, 1);
2865 psys_particle_on_dm(dm, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, vec, 0, 0, 0, orco, 0);
2867 /* see psys_face_mat for why this function is called */
2868 transform_mesh_orco_verts(ob->data, &orco, 1, 1);
2869 VECCOPY(hairmat[3],orco);
2872 void psys_vec_rot_to_face(DerivedMesh *dm, ParticleData *pa, float *vec)
2876 psys_face_mat(0, dm, pa, mat, 0);
2877 Mat4Transp(mat); /* cheap inverse for rotation matrix */
2878 Mat4Mul3Vecfl(mat, vec);
2881 void psys_mat_hair_to_global(Object *ob, DerivedMesh *dm, short from, ParticleData *pa, float hairmat[][4])
2883 float facemat[4][4];
2885 psys_mat_hair_to_object(ob, dm, from, pa, facemat);
2887 Mat4MulMat4(hairmat, facemat, ob->obmat);
2890 /************************************************/
2891 /* ParticleSettings handling */
2892 /************************************************/
2893 static void default_particle_settings(ParticleSettings *part)
2897 part->type= PART_EMITTER;
2898 part->distr= PART_DISTR_JIT;
2899 part->draw_as=PART_DRAW_DOT;
2900 part->bb_uv_split=1;
2901 part->bb_align=PART_BB_VIEW;
2902 part->bb_split_offset=PART_BB_OFF_LINEAR;
2903 part->flag=PART_REACT_MULTIPLE|PART_HAIR_GEOMETRY;
2907 part->lifetime= 50.0;
2909 part->totpart= 1000;
2911 part->timetweak= 1.0;
2912 part->keyed_time= 0.5;
2915 part->integrator= PART_INT_MIDPOINT;
2916 part->phystype= PART_PHYS_NEWTON;
2921 part->adapt_angle= 5;
2924 part->reactevent= PART_EVENT_DEATH;
2926 part->from= PART_FROM_FACE;
2929 part->boidneighbours= 5;
2931 part->max_vel = 10.0f;
2932 part->average_vel = 0.3f;
2933 part->max_tan_acc = 0.2f;
2934 part->max_lat_acc = 1.0f;
2936 part->reactshape=1.0f;
2940 part->childsize=1.0;
2943 part->ren_child_nbr=100;
2944 part->childrad=0.2f;
2945 part->childflat=0.0f;
2946 part->clumppow=0.0f;
2947 part->kink_amp=0.2f;
2948 part->kink_freq=2.0;
2950 part->rough1_size=1.0;
2951 part->rough2_size=1.0;
2952 part->rough_end_shape=1.0;
2954 part->draw_line[0]=0.5;
2959 for(i=0; i<BOID_TOT_RULES; i++){
2960 part->boidrule[i]=(char)i;
2961 part->boidfac[i]=0.5;
2964 #if 0 // XXX old animation system
2966 #endif // XXX old animation system
2968 part->simplify_refsize= 1920;
2969 part->simplify_rate= 1.0f;
2970 part->simplify_transition= 0.1f;
2971 part->simplify_viewport= 0.8;
2975 ParticleSettings *psys_new_settings(char *name, Main *main)
2977 ParticleSettings *part;
2979 part= alloc_libblock(&main->particle, ID_PA, name);
2981 default_particle_settings(part);
2986 ParticleSettings *psys_copy_settings(ParticleSettings *part)
2988 ParticleSettings *partn;
2990 partn= copy_libblock(part);
2991 if(partn->pd) partn->pd= MEM_dupallocN(part->pd);
2992 if(partn->pd2) partn->pd2= MEM_dupallocN(part->pd2);
2997 void make_local_particlesettings(ParticleSettings *part)
3000 ParticleSettings *par;
3003 /* - only lib users: do nothing
3004 * - only local users: set flag
3005 * - mixed: make copy
3008 if(part->id.lib==0) return;
3009 if(part->id.us==1) {
3011 part->id.flag= LIB_LOCAL;
3012 new_id(0, (ID *)part, 0);
3017 ob= G.main->object.first;
3019 ParticleSystem *psys=ob->particlesystem.first;
3020 for(; psys; psys=psys->next){
3021 if(psys->part==part) {
3022 if(ob->id.lib) lib= 1;
3029 if(local && lib==0) {
3031 part->id.flag= LIB_LOCAL;
3032 new_id(0, (ID *)part, 0);
3034 else if(local && lib) {
3036 par= psys_copy_settings(part);
3040 ob= G.main->object.first;
3042 ParticleSystem *psys=ob->particlesystem.first;
3043 for(; psys; psys=psys->next){
3044 if(psys->part==part && ob->id.lib==0) {
3055 /* should be integrated to depgraph signals */
3056 void psys_flush_settings(struct Scene *scene, ParticleSettings *part, int event, int hair_recalc)