Merge branch 'master' into blender2.8
[blender.git] / source / blender / editors / physics / physics_fluid.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) Blender Foundation
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/physics/physics_fluid.c
29  *  \ingroup edphys
30  */
31
32 #include <math.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <sys/stat.h>
36
37 #include "MEM_guardedalloc.h"
38
39 /* types */
40 #include "DNA_action_types.h"
41 #include "DNA_object_types.h"
42 #include "DNA_object_fluidsim_types.h"
43
44 #include "BLI_blenlib.h"
45 #include "BLI_path_util.h"
46 #include "BLI_math.h"
47 #include "BLI_utildefines.h"
48
49 #include "BKE_context.h"
50 #include "BKE_customdata.h"
51 #include "BKE_fluidsim.h"
52 #include "BKE_main.h"
53 #include "BKE_modifier.h"
54 #include "BKE_object.h"
55 #include "BKE_report.h"
56 #include "BKE_scene.h"
57
58 #include "DEG_depsgraph.h"
59
60 #include "LBM_fluidsim.h"
61
62 #include "ED_screen.h"
63
64 #include "WM_types.h"
65 #include "WM_api.h"
66
67 #include "physics_intern.h" // own include
68
69 /* enable/disable overall compilation */
70 #ifdef WITH_MOD_FLUID
71
72 #include "BKE_global.h"
73
74 #include "WM_api.h"
75
76 #include "DNA_scene_types.h"
77 #include "DNA_mesh_types.h"
78
79
80 static float get_fluid_viscosity(FluidsimSettings *settings)
81 {
82         return (1.0f/powf(10.0f, settings->viscosityExponent)) * settings->viscosityValue;
83 }
84
85 static float get_fluid_rate(FluidsimSettings *settings)
86 {
87         float rate = 1.0f; /* default rate if not animated... */
88
89         rate = settings->animRate;
90
91         if (rate < 0.0f)
92                 rate = 0.0f;
93
94         return rate;
95 }
96
97 static void get_fluid_gravity(float *gravity, Scene *scene, FluidsimSettings *fss)
98 {
99         if (scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY) {
100                 copy_v3_v3(gravity, scene->physics_settings.gravity);
101         }
102         else {
103                 copy_v3_v3(gravity, fss->grav);
104         }
105 }
106
107 static float get_fluid_size_m(Scene *scene, Object *domainob, FluidsimSettings *fss)
108 {
109         if (!scene->unit.system) {
110                 return fss->realsize;
111         }
112         else {
113                 float dim[3];
114                 float longest_axis;
115
116                 BKE_object_dimensions_get(domainob, dim);
117                 longest_axis = max_fff(dim[0], dim[1], dim[2]);
118
119                 return longest_axis * scene->unit.scale_length;
120         }
121 }
122
123 static bool fluid_is_animated_mesh(FluidsimSettings *fss)
124 {
125         return ((fss->type == OB_FLUIDSIM_CONTROL) || fss->domainNovecgen);
126 }
127
128 /* ********************** fluid sim settings struct functions ********************** */
129
130 #if 0
131 /* helper function */
132 void fluidsimGetGeometryObjFilename(Object *ob, char *dst)  //, char *srcname)
133 {
134         //BLI_snprintf(dst, FILE_MAXFILE, "%s_cfgdata_%s.bobj.gz", srcname, ob->id.name);
135         BLI_snprintf(dst, FILE_MAXFILE, "fluidcfgdata_%s.bobj.gz", ob->id.name);
136 }
137 #endif
138
139
140 /* ********************** fluid sim channel helper functions ********************** */
141
142 typedef struct FluidAnimChannels {
143         int length;
144
145         double aniFrameTime;
146
147         float *timeAtFrame;
148         float *DomainTime;
149         float *DomainGravity;
150         float *DomainViscosity;
151 } FluidAnimChannels;
152
153 typedef struct FluidObject {
154         struct FluidObject *next, *prev;
155
156         struct Object *object;
157
158         float *Translation;
159         float *Rotation;
160         float *Scale;
161         float *Active;
162
163         float *InitialVelocity;
164
165         float *AttractforceStrength;
166         float *AttractforceRadius;
167         float *VelocityforceStrength;
168         float *VelocityforceRadius;
169
170         float *VertexCache;
171         int numVerts, numTris;
172 } FluidObject;
173
174 // no. of entries for the two channel sizes
175 #define CHANNEL_FLOAT 1
176 #define CHANNEL_VEC   3
177
178 // simplify channels before printing
179 // for API this is done anyway upon init
180 #if 0
181 static void fluidsimPrintChannel(FILE *file, float *channel, int paramsize, char *str, int entries)
182 {
183         int i, j;
184         int channelSize = paramsize;
185
186         if (entries == 3) {
187                 elbeemSimplifyChannelVec3(channel, &channelSize);
188         }
189         else if (entries == 1) {
190                 elbeemSimplifyChannelFloat(channel, &channelSize);
191         }
192         else {
193                 /* invalid, cant happen? */
194         }
195
196         fprintf(file, "      CHANNEL %s =\n", str);
197         for (i=0; i < channelSize; i++) {
198                 fprintf(file, "        ");
199                 for (j=0;j <= entries;j++) {  // also print time value
200                         fprintf(file, " %f ", channel[i*(entries + 1) + j]);
201                         if (j == entries-1) { fprintf(file, "  "); }
202                 }
203                 fprintf(file, "\n");
204         }
205
206         fprintf(file,  "      ;\n");
207 }
208 #endif
209
210
211 /* Note: fluid anim channel data layout
212  * ------------------------------------
213  * CHANNEL_FLOAT:
214  * frame 1     |frame 2
215  * [dataF][time][dataF][time]
216  *
217  * CHANNEL_VEC:
218  * frame 1                   |frame 2
219  * [dataX][dataY][dataZ][time][dataX][dataY][dataZ][time]
220  *
221  */
222
223 static void init_time(FluidsimSettings *domainSettings, FluidAnimChannels *channels)
224 {
225         int i;
226
227         channels->timeAtFrame = MEM_callocN((channels->length + 1) * sizeof(float), "timeAtFrame channel");
228
229         channels->timeAtFrame[0] = channels->timeAtFrame[1] = domainSettings->animStart; // start at index 1
230
231         for (i=2; i <= channels->length; i++) {
232                 channels->timeAtFrame[i] = channels->timeAtFrame[i - 1] + (float)channels->aniFrameTime;
233         }
234 }
235
236 /* if this is slow, can replace with faster, less readable code */
237 static void set_channel(float *channel, float time, float *value, int i, int size)
238 {
239         if (size == CHANNEL_FLOAT) {
240                 channel[(i * 2) + 0] = value[0];
241                 channel[(i * 2) + 1] = time;
242         }
243         else if (size == CHANNEL_VEC) {
244                 channel[(i * 4) + 0] = value[0];
245                 channel[(i * 4) + 1] = value[1];
246                 channel[(i * 4) + 2] = value[2];
247                 channel[(i * 4) + 3] = time;
248         }
249 }
250
251 static void set_vertex_channel(Depsgraph *depsgraph, float *channel, float time, struct Scene *scene, struct FluidObject *fobj, int i)
252 {
253         Object *ob = fobj->object;
254         FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim);
255         float *verts;
256         int *tris=NULL, numVerts=0, numTris=0;
257         int modifierIndex = BLI_findindex(&ob->modifiers, fluidmd);
258         int framesize = (3*fobj->numVerts) + 1;
259         int j;
260
261         if (channel == NULL)
262                 return;
263
264         initElbeemMesh(depsgraph, scene, ob, &numVerts, &verts, &numTris, &tris, 1, modifierIndex);
265
266         /* don't allow mesh to change number of verts in anim sequence */
267         if (numVerts != fobj->numVerts) {
268                 MEM_freeN(channel);
269                 channel = NULL;
270                 return;
271         }
272
273         /* fill frame of channel with vertex locations */
274         for (j=0; j < (3*numVerts); j++) {
275                 channel[i*framesize + j] = verts[j];
276         }
277         channel[i*framesize + framesize-1] = time;
278
279         MEM_freeN(verts);
280         MEM_freeN(tris);
281 }
282
283 static void free_domain_channels(FluidAnimChannels *channels)
284 {
285         if (!channels->timeAtFrame)
286                 return;
287         MEM_freeN(channels->timeAtFrame);
288         channels->timeAtFrame = NULL;
289         MEM_freeN(channels->DomainGravity);
290         channels->DomainGravity = NULL;
291         MEM_freeN(channels->DomainViscosity);
292         channels->DomainViscosity = NULL;
293         MEM_freeN(channels->DomainTime);
294         channels->DomainTime = NULL;
295 }
296
297 static void free_all_fluidobject_channels(ListBase *fobjects)
298 {
299         FluidObject *fobj;
300
301         for (fobj=fobjects->first; fobj; fobj=fobj->next) {
302                 if (fobj->Translation) {
303                         MEM_freeN(fobj->Translation);
304                         fobj->Translation = NULL;
305                         MEM_freeN(fobj->Rotation);
306                         fobj->Rotation = NULL;
307                         MEM_freeN(fobj->Scale);
308                         fobj->Scale = NULL;
309                         MEM_freeN(fobj->Active);
310                         fobj->Active = NULL;
311                         MEM_freeN(fobj->InitialVelocity);
312                         fobj->InitialVelocity = NULL;
313                 }
314
315                 if (fobj->AttractforceStrength) {
316                         MEM_freeN(fobj->AttractforceStrength);
317                         fobj->AttractforceStrength = NULL;
318                         MEM_freeN(fobj->AttractforceRadius);
319                         fobj->AttractforceRadius = NULL;
320                         MEM_freeN(fobj->VelocityforceStrength);
321                         fobj->VelocityforceStrength = NULL;
322                         MEM_freeN(fobj->VelocityforceRadius);
323                         fobj->VelocityforceRadius = NULL;
324                 }
325
326                 if (fobj->VertexCache) {
327                         MEM_freeN(fobj->VertexCache);
328                         fobj->VertexCache = NULL;
329                 }
330         }
331 }
332
333 static void fluid_init_all_channels(bContext *C, Object *UNUSED(fsDomain), FluidsimSettings *domainSettings, FluidAnimChannels *channels, ListBase *fobjects)
334 {
335         Scene *scene = CTX_data_scene(C);
336         ViewLayer *view_layer = CTX_data_view_layer(C);
337         Depsgraph *depsgraph = CTX_data_depsgraph(C);
338         Base *base;
339         int i;
340         int length = channels->length;
341         float eval_time;
342
343         /* init time values (assuming that time moves at a constant speed; may be overridden later) */
344         init_time(domainSettings, channels);
345
346         /* allocate domain animation channels */
347         channels->DomainGravity = MEM_callocN(length * (CHANNEL_VEC+1) * sizeof(float), "channel DomainGravity");
348         channels->DomainViscosity = MEM_callocN(length * (CHANNEL_FLOAT+1) * sizeof(float), "channel DomainViscosity");
349         channels->DomainTime = MEM_callocN(length * (CHANNEL_FLOAT+1) * sizeof(float), "channel DomainTime");
350
351         /* allocate fluid objects */
352         for (base = FIRSTBASE(view_layer); base; base = base->next) {
353                 Object *ob = base->object;
354                 FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim);
355
356                 if (fluidmd) {
357                         FluidObject *fobj = MEM_callocN(sizeof(FluidObject), "Fluid Object");
358                         fobj->object = ob;
359
360                         if (ELEM(fluidmd->fss->type, OB_FLUIDSIM_DOMAIN, OB_FLUIDSIM_PARTICLE)) {
361                                 BLI_addtail(fobjects, fobj);
362                                 continue;
363                         }
364
365                         fobj->Translation = MEM_callocN(length * (CHANNEL_VEC+1) * sizeof(float), "fluidobject Translation");
366                         fobj->Rotation = MEM_callocN(length * (CHANNEL_VEC+1) * sizeof(float), "fluidobject Rotation");
367                         fobj->Scale = MEM_callocN(length * (CHANNEL_VEC+1) * sizeof(float), "fluidobject Scale");
368                         fobj->Active = MEM_callocN(length * (CHANNEL_FLOAT+1) * sizeof(float), "fluidobject Active");
369                         fobj->InitialVelocity = MEM_callocN(length * (CHANNEL_VEC+1) * sizeof(float), "fluidobject InitialVelocity");
370
371                         if (fluidmd->fss->type == OB_FLUIDSIM_CONTROL) {
372                                 fobj->AttractforceStrength = MEM_callocN(length * (CHANNEL_FLOAT+1) * sizeof(float), "fluidobject AttractforceStrength");
373                                 fobj->AttractforceRadius = MEM_callocN(length * (CHANNEL_FLOAT+1) * sizeof(float), "fluidobject AttractforceRadius");
374                                 fobj->VelocityforceStrength = MEM_callocN(length * (CHANNEL_FLOAT+1) * sizeof(float), "fluidobject VelocityforceStrength");
375                                 fobj->VelocityforceRadius = MEM_callocN(length * (CHANNEL_FLOAT+1) * sizeof(float), "fluidobject VelocityforceRadius");
376                         }
377
378                         if (fluid_is_animated_mesh(fluidmd->fss)) {
379                                 float *verts=NULL;
380                                 int *tris=NULL, modifierIndex = BLI_findindex(&ob->modifiers, (ModifierData *)fluidmd);
381
382                                 initElbeemMesh(depsgraph, scene, ob, &fobj->numVerts, &verts, &fobj->numTris, &tris, 0, modifierIndex);
383                                 fobj->VertexCache = MEM_callocN(length *((fobj->numVerts*CHANNEL_VEC)+1) * sizeof(float), "fluidobject VertexCache");
384
385                                 MEM_freeN(verts);
386                                 MEM_freeN(tris);
387                         }
388
389                         BLI_addtail(fobjects, fobj);
390                 }
391         }
392
393         /* now we loop over the frames and fill the allocated channels with data */
394         for (i=0; i < channels->length; i++) {
395                 FluidObject *fobj;
396                 float viscosity, gravity[3];
397                 float timeAtFrame, time;
398
399                 eval_time = domainSettings->bakeStart + i;
400
401                 /* XXX: This can't be used due to an anim sys optimization that ignores recalc object animation,
402                  * leaving it for the depgraph (this ignores object animation such as modifier properties though... :/ )
403                  * --> BKE_animsys_evaluate_all_animation(CTX_data_main(C), eval_time);
404                  * This doesn't work with drivers:
405                  * --> BKE_animsys_evaluate_animdata(&fsDomain->id, fsDomain->adt, eval_time, ADT_RECALC_ALL);
406                  */
407
408                 /* Modifying the global scene isn't nice, but we can do it in
409                  * this part of the process before a threaded job is created */
410                 scene->r.cfra = (int)eval_time;
411                 ED_update_for_newframe(CTX_data_main(C), depsgraph);
412
413                 /* now scene data should be current according to animation system, so we fill the channels */
414
415                 /* Domain time */
416                 // TODO: have option for not running sim, time mangling, in which case second case comes in handy
417                 if (channels->DomainTime) {
418                         time = get_fluid_rate(domainSettings) * (float)channels->aniFrameTime;
419                         timeAtFrame = channels->timeAtFrame[i] + time;
420
421                         channels->timeAtFrame[i+1] = timeAtFrame;
422                         set_channel(channels->DomainTime, i, &time, i, CHANNEL_FLOAT);
423                 }
424                 else {
425                         timeAtFrame = channels->timeAtFrame[i+1];
426                 }
427
428                 /* Domain properties - gravity/viscosity */
429                 get_fluid_gravity(gravity, scene, domainSettings);
430                 set_channel(channels->DomainGravity, timeAtFrame, gravity, i, CHANNEL_VEC);
431                 viscosity = get_fluid_viscosity(domainSettings);
432                 set_channel(channels->DomainViscosity, timeAtFrame, &viscosity, i, CHANNEL_FLOAT);
433
434                 /* object movement */
435                 for (fobj=fobjects->first; fobj; fobj=fobj->next) {
436                         Object *ob = fobj->object;
437                         FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim);
438                         float active = (float) ((fluidmd->fss->flag & OB_FLUIDSIM_ACTIVE) ? 1 : 0);
439                         float rot_d[3] = {0.f, 0.f, 0.f}, old_rot[3] = {0.f, 0.f, 0.f};
440
441                         if (ELEM(fluidmd->fss->type, OB_FLUIDSIM_DOMAIN, OB_FLUIDSIM_PARTICLE))
442                                 continue;
443
444                         /* init euler rotation values and convert to elbeem format */
445                         /* get the rotation from ob->obmat rather than ob->rot to account for parent animations */
446                         if (i) {
447                                 copy_v3_v3(old_rot, fobj->Rotation + 4*(i-1));
448                                 mul_v3_fl(old_rot, (float)-M_PI / 180.f);
449                         }
450
451                         mat4_to_compatible_eulO(rot_d, old_rot, 0, ob->obmat);
452                         mul_v3_fl(rot_d, -180.0f / (float)M_PI);
453
454                         set_channel(fobj->Translation, timeAtFrame, ob->loc, i, CHANNEL_VEC);
455                         set_channel(fobj->Rotation, timeAtFrame, rot_d, i, CHANNEL_VEC);
456                         set_channel(fobj->Scale, timeAtFrame, ob->size, i, CHANNEL_VEC);
457                         set_channel(fobj->Active, timeAtFrame, &active, i, CHANNEL_FLOAT);
458                         set_channel(fobj->InitialVelocity, timeAtFrame, &fluidmd->fss->iniVelx, i, CHANNEL_VEC);
459
460                         // printf("Active: %f, Frame: %f\n", active, timeAtFrame);
461
462                         if (fluidmd->fss->type == OB_FLUIDSIM_CONTROL) {
463                                 set_channel(fobj->AttractforceStrength, timeAtFrame, &fluidmd->fss->attractforceStrength, i, CHANNEL_FLOAT);
464                                 set_channel(fobj->AttractforceRadius, timeAtFrame, &fluidmd->fss->attractforceRadius, i, CHANNEL_FLOAT);
465                                 set_channel(fobj->VelocityforceStrength, timeAtFrame, &fluidmd->fss->velocityforceStrength, i, CHANNEL_FLOAT);
466                                 set_channel(fobj->VelocityforceRadius, timeAtFrame, &fluidmd->fss->velocityforceRadius, i, CHANNEL_FLOAT);
467                         }
468
469                         if (fluid_is_animated_mesh(fluidmd->fss)) {
470                                 set_vertex_channel(depsgraph, fobj->VertexCache, timeAtFrame, scene, fobj, i);
471                         }
472                 }
473         }
474 }
475
476 static void export_fluid_objects(const bContext *C, ListBase *fobjects, Scene *scene, int length)
477 {
478         Depsgraph *depsgraph = CTX_data_depsgraph(C);
479         FluidObject *fobj;
480
481         for (fobj=fobjects->first; fobj; fobj=fobj->next) {
482                 Object *ob = fobj->object;
483                 FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim);
484                 int modifierIndex = BLI_findindex(&ob->modifiers, fluidmd);
485
486                 float *verts=NULL;
487                 int *tris=NULL;
488                 int numVerts=0, numTris=0;
489                 bool deform = fluid_is_animated_mesh(fluidmd->fss);
490
491                 elbeemMesh fsmesh;
492
493                 if (ELEM(fluidmd->fss->type, OB_FLUIDSIM_DOMAIN, OB_FLUIDSIM_PARTICLE))
494                         continue;
495
496                 elbeemResetMesh(&fsmesh);
497
498                 fsmesh.type = fluidmd->fss->type;
499                 fsmesh.name = ob->id.name;
500
501                 initElbeemMesh(depsgraph, scene, ob, &numVerts, &verts, &numTris, &tris, 0, modifierIndex);
502
503                 fsmesh.numVertices   = numVerts;
504                 fsmesh.numTriangles  = numTris;
505                 fsmesh.vertices      = verts;
506                 fsmesh.triangles     = tris;
507
508                 fsmesh.channelSizeTranslation  =
509                 fsmesh.channelSizeRotation     =
510                 fsmesh.channelSizeScale        =
511                 fsmesh.channelSizeInitialVel   =
512                 fsmesh.channelSizeActive       = length;
513
514                 fsmesh.channelTranslation      = fobj->Translation;
515                 fsmesh.channelRotation         = fobj->Rotation;
516                 fsmesh.channelScale            = fobj->Scale;
517                 fsmesh.channelActive           = fobj->Active;
518
519                 if ( ELEM(fsmesh.type, OB_FLUIDSIM_FLUID, OB_FLUIDSIM_INFLOW)) {
520                         fsmesh.channelInitialVel = fobj->InitialVelocity;
521                         fsmesh.localInivelCoords = ((fluidmd->fss->typeFlags & OB_FSINFLOW_LOCALCOORD) ? 1 : 0);
522                 }
523
524                 if (fluidmd->fss->typeFlags & OB_FSBND_NOSLIP)
525                         fsmesh.obstacleType = FLUIDSIM_OBSTACLE_NOSLIP;
526                 else if (fluidmd->fss->typeFlags & OB_FSBND_PARTSLIP)
527                         fsmesh.obstacleType = FLUIDSIM_OBSTACLE_PARTSLIP;
528                 else if (fluidmd->fss->typeFlags & OB_FSBND_FREESLIP)
529                         fsmesh.obstacleType = FLUIDSIM_OBSTACLE_FREESLIP;
530
531                 fsmesh.obstaclePartslip = fluidmd->fss->partSlipValue;
532                 fsmesh.volumeInitType = fluidmd->fss->volumeInitType;
533                 fsmesh.obstacleImpactFactor = fluidmd->fss->surfaceSmoothing; // misused value
534
535                 if (fsmesh.type == OB_FLUIDSIM_CONTROL) {
536                         fsmesh.cpsTimeStart = fluidmd->fss->cpsTimeStart;
537                         fsmesh.cpsTimeEnd = fluidmd->fss->cpsTimeEnd;
538                         fsmesh.cpsQuality = fluidmd->fss->cpsQuality;
539                         fsmesh.obstacleType = (fluidmd->fss->flag & OB_FLUIDSIM_REVERSE);
540
541                         fsmesh.channelSizeAttractforceRadius =
542                         fsmesh.channelSizeVelocityforceStrength =
543                         fsmesh.channelSizeVelocityforceRadius =
544                         fsmesh.channelSizeAttractforceStrength = length;
545
546                         fsmesh.channelAttractforceStrength = fobj->AttractforceStrength;
547                         fsmesh.channelAttractforceRadius = fobj->AttractforceRadius;
548                         fsmesh.channelVelocityforceStrength = fobj->VelocityforceStrength;
549                         fsmesh.channelVelocityforceRadius = fobj->VelocityforceRadius;
550                 }
551                 else {
552                         fsmesh.channelAttractforceStrength =
553                         fsmesh.channelAttractforceRadius =
554                         fsmesh.channelVelocityforceStrength =
555                         fsmesh.channelVelocityforceRadius = NULL;
556                 }
557
558                 /* animated meshes */
559                 if (deform) {
560                         fsmesh.channelSizeVertices = length;
561                         fsmesh.channelVertices = fobj->VertexCache;
562
563                         /* remove channels */
564                         fsmesh.channelTranslation      =
565                         fsmesh.channelRotation         =
566                         fsmesh.channelScale            = NULL;
567
568                         /* Override user settings, only noslip is supported here! */
569                         if (fsmesh.type != OB_FLUIDSIM_CONTROL)
570                                 fsmesh.obstacleType = FLUIDSIM_OBSTACLE_NOSLIP;
571                 }
572
573                 elbeemAddMesh(&fsmesh);
574
575                 if (verts) MEM_freeN(verts);
576                 if (tris) MEM_freeN(tris);
577         }
578 }
579
580 static int fluid_validate_scene(ReportList *reports, ViewLayer *view_layer, Object *fsDomain)
581 {
582         Base *base;
583         Object *newdomain = NULL;
584         int channelObjCount = 0;
585         int fluidInputCount = 0;
586
587         for (base = FIRSTBASE(view_layer); base; base = base->next) {
588                 Object *ob = base->object;
589                 FluidsimModifierData *fluidmdtmp = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim);
590
591                 /* only find objects with fluid modifiers */
592                 if (!fluidmdtmp || ob->type != OB_MESH) continue;
593
594                 if (fluidmdtmp->fss->type == OB_FLUIDSIM_DOMAIN) {
595                         /* if no initial domain object given, find another potential domain */
596                         if (!fsDomain) {
597                                 newdomain = ob;
598                         }
599                         /* if there's more than one domain, cancel */
600                         else if (fsDomain && ob != fsDomain) {
601                                 BKE_report(reports, RPT_ERROR, "There should be only one domain object");
602                                 return 0;
603                         }
604                 }
605
606                 /* count number of objects needed for animation channels */
607                 if ( !ELEM(fluidmdtmp->fss->type, OB_FLUIDSIM_DOMAIN, OB_FLUIDSIM_PARTICLE) )
608                         channelObjCount++;
609
610                 /* count number of fluid input objects */
611                 if (ELEM(fluidmdtmp->fss->type, OB_FLUIDSIM_FLUID, OB_FLUIDSIM_INFLOW))
612                         fluidInputCount++;
613         }
614
615         if (newdomain)
616                 fsDomain = newdomain;
617
618         if (!fsDomain) {
619                 BKE_report(reports, RPT_ERROR, "No domain object found");
620                 return 0;
621         }
622
623         if (channelObjCount >= 255) {
624                 BKE_report(reports, RPT_ERROR, "Cannot bake with more than 256 objects");
625                 return 0;
626         }
627
628         if (fluidInputCount == 0) {
629                 BKE_report(reports, RPT_ERROR, "No fluid input objects in the scene");
630                 return 0;
631         }
632
633         return 1;
634 }
635
636
637 #define FLUID_SUFFIX_CONFIG             "fluidsim.cfg"
638 #define FLUID_SUFFIX_CONFIG_TMP (FLUID_SUFFIX_CONFIG ".tmp")
639 #define FLUID_SUFFIX_SURFACE    "fluidsurface"
640
641 static bool fluid_init_filepaths(
642         Main *bmain, ReportList *reports, FluidsimSettings *domainSettings, Object *fsDomain,
643         char *targetDir, char *targetFile)
644 {
645         const char *suffixConfigTmp = FLUID_SUFFIX_CONFIG_TMP;
646
647         /* prepare names... */
648         const char *relbase = modifier_path_relbase(bmain, fsDomain);
649
650         /* We do not accept empty paths, they can end in random places silently, see T51176. */
651         if (domainSettings->surfdataPath[0] == '\0') {
652                 modifier_path_init(domainSettings->surfdataPath, sizeof(domainSettings->surfdataPath),
653                                    OB_FLUIDSIM_SURF_DIR_DEFAULT);
654                 BKE_reportf(reports, RPT_WARNING, "Fluidsim: empty cache path, reset to default '%s'",
655                             domainSettings->surfdataPath);
656         }
657
658         BLI_strncpy(targetDir, domainSettings->surfdataPath, FILE_MAXDIR);
659         BLI_path_abs(targetDir, relbase);
660
661         /* .tmp: don't overwrite/delete original file */
662         BLI_join_dirfile(targetFile, FILE_MAX, targetDir, suffixConfigTmp);
663
664         /* Ensure whole path exists and is wirtable. */
665         const bool dir_exists = BLI_dir_create_recursive(targetDir);
666         const bool is_writable = BLI_file_is_writable(targetFile);
667
668         /* We change path to some presumably valid default value, but do not allow bake process to continue,
669          * this gives user chance to set manually another path. */
670         if (!dir_exists || !is_writable) {
671                 modifier_path_init(domainSettings->surfdataPath, sizeof(domainSettings->surfdataPath),
672                                    OB_FLUIDSIM_SURF_DIR_DEFAULT);
673
674                 if (!dir_exists) {
675                         BKE_reportf(reports, RPT_ERROR, "Fluidsim: could not create cache directory '%s', reset to default '%s'",
676                                     targetDir, domainSettings->surfdataPath);
677                 }
678                 else {
679                         BKE_reportf(reports, RPT_ERROR, "Fluidsim: cache directory '%s' is not writable, reset to default '%s'",
680                                     targetDir, domainSettings->surfdataPath);
681                 }
682
683                 BLI_strncpy(targetDir, domainSettings->surfdataPath, FILE_MAXDIR);
684                 BLI_path_abs(targetDir, relbase);
685
686                 /* .tmp: don't overwrite/delete original file */
687                 BLI_join_dirfile(targetFile, FILE_MAX, targetDir, suffixConfigTmp);
688
689                 /* Ensure whole path exists and is wirtable. */
690                 if (!BLI_dir_create_recursive(targetDir) || !BLI_file_is_writable(targetFile)) {
691                         BKE_reportf(reports, RPT_ERROR, "Fluidsim: could not use default cache directory '%s', "
692                                                         "please define a valid cache path manually", targetDir);
693                 }
694                 return false;
695         }
696
697         return true;
698 }
699
700 /* ******************************************************************************** */
701 /* ********************** write fluidsim config to file ************************* */
702 /* ******************************************************************************** */
703
704 typedef struct FluidBakeJob {
705         /* from wmJob */
706         void *owner;
707         short *stop, *do_update;
708         float *progress;
709         int current_frame;
710         elbeemSimulationSettings *settings;
711 } FluidBakeJob;
712
713 static void fluidbake_free(void *customdata)
714 {
715         FluidBakeJob *fb= (FluidBakeJob *)customdata;
716         MEM_freeN(fb);
717 }
718
719 /* called by fluidbake, only to check job 'stop' value */
720 static int fluidbake_breakjob(void *customdata)
721 {
722         FluidBakeJob *fb= (FluidBakeJob *)customdata;
723
724         if (fb->stop && *(fb->stop))
725                 return 1;
726
727         /* this is not nice yet, need to make the jobs list template better
728          * for identifying/acting upon various different jobs */
729         /* but for now we'll reuse the render break... */
730         return (G.is_break);
731 }
732
733 /* called by fluidbake, wmJob sends notifier */
734 static void fluidbake_updatejob(void *customdata, float progress)
735 {
736         FluidBakeJob *fb= (FluidBakeJob *)customdata;
737
738         *(fb->do_update) = true;
739         *(fb->progress) = progress;
740 }
741
742 static void fluidbake_startjob(void *customdata, short *stop, short *do_update, float *progress)
743 {
744         FluidBakeJob *fb= (FluidBakeJob *)customdata;
745
746         fb->stop= stop;
747         fb->do_update = do_update;
748         fb->progress = progress;
749
750         G.is_break = false;  /* XXX shared with render - replace with job 'stop' switch */
751
752         elbeemSimulate();
753         *do_update = true;
754         *stop = 0;
755 }
756
757 static void fluidbake_endjob(void *customdata)
758 {
759         FluidBakeJob *fb= (FluidBakeJob *)customdata;
760
761         if (fb->settings) {
762                 MEM_freeN(fb->settings);
763                 fb->settings = NULL;
764         }
765 }
766
767 static int runSimulationCallback(void *data, int status, int frame)
768 {
769         FluidBakeJob *fb = (FluidBakeJob *)data;
770         elbeemSimulationSettings *settings = fb->settings;
771
772         if (status == FLUIDSIM_CBSTATUS_NEWFRAME) {
773                 fluidbake_updatejob(fb, frame / (float)settings->noOfFrames);
774                 //printf("elbeem blender cb s%d, f%d, domainid:%d noOfFrames: %d\n", status, frame, settings->domainId, settings->noOfFrames ); // DEBUG
775         }
776
777         if (fluidbake_breakjob(fb)) {
778                 return FLUIDSIM_CBRET_ABORT;
779         }
780
781         return FLUIDSIM_CBRET_CONTINUE;
782 }
783
784 static void fluidbake_free_data(FluidAnimChannels *channels, ListBase *fobjects, elbeemSimulationSettings *fsset, FluidBakeJob *fb)
785 {
786         free_domain_channels(channels);
787         MEM_freeN(channels);
788         channels = NULL;
789
790         free_all_fluidobject_channels(fobjects);
791         BLI_freelistN(fobjects);
792         MEM_freeN(fobjects);
793         fobjects = NULL;
794
795         if (fsset) {
796                 MEM_freeN(fsset);
797                 fsset = NULL;
798         }
799
800         if (fb) {
801                 MEM_freeN(fb);
802                 fb = NULL;
803         }
804 }
805
806 /* copied from rna_fluidsim.c: fluidsim_find_lastframe() */
807 static void fluidsim_delete_until_lastframe(FluidsimSettings *fss, const char *relbase)
808 {
809         char targetDir[FILE_MAX], targetFile[FILE_MAX];
810         char targetDirVel[FILE_MAX], targetFileVel[FILE_MAX];
811         char previewDir[FILE_MAX], previewFile[FILE_MAX];
812         int curFrame = 1, exists = 0;
813
814         BLI_join_dirfile(targetDir,    sizeof(targetDir),    fss->surfdataPath, OB_FLUIDSIM_SURF_FINAL_OBJ_FNAME);
815         BLI_join_dirfile(targetDirVel, sizeof(targetDirVel), fss->surfdataPath, OB_FLUIDSIM_SURF_FINAL_VEL_FNAME);
816         BLI_join_dirfile(previewDir,   sizeof(previewDir),   fss->surfdataPath, OB_FLUIDSIM_SURF_PREVIEW_OBJ_FNAME);
817
818         BLI_path_abs(targetDir,    relbase);
819         BLI_path_abs(targetDirVel, relbase);
820         BLI_path_abs(previewDir,   relbase);
821
822         do {
823                 BLI_strncpy(targetFile, targetDir, sizeof(targetFile));
824                 BLI_strncpy(targetFileVel, targetDirVel, sizeof(targetFileVel));
825                 BLI_strncpy(previewFile, previewDir, sizeof(previewFile));
826
827                 BLI_path_frame(targetFile, curFrame, 0);
828                 BLI_path_frame(targetFileVel, curFrame, 0);
829                 BLI_path_frame(previewFile, curFrame, 0);
830
831                 curFrame++;
832
833                 if ((exists = BLI_exists(targetFile))) {
834                         BLI_delete(targetFile, false, false);
835                         BLI_delete(targetFileVel, false, false);
836                         BLI_delete(previewFile, false, false);
837                 }
838         } while (exists);
839
840         return;
841 }
842
843 static int fluidsimBake(bContext *C, ReportList *reports, Object *fsDomain, short do_job)
844 {
845         Main *bmain = CTX_data_main(C);
846         Scene *scene = CTX_data_scene(C);
847         ViewLayer *view_layer = CTX_data_view_layer(C);
848         Depsgraph *depsgraph = CTX_data_depsgraph(C);
849         int i;
850         FluidsimSettings *domainSettings;
851
852         char debugStrBuffer[256];
853
854         int gridlevels = 0;
855         const char *relbase= modifier_path_relbase(bmain, fsDomain);
856         const char *strEnvName = "BLENDER_ELBEEMDEBUG"; // from blendercall.cpp
857         const char *suffixConfigTmp = FLUID_SUFFIX_CONFIG_TMP;
858         const char *suffixSurface = FLUID_SUFFIX_SURFACE;
859
860         char targetDir[FILE_MAX];  // store & modify output settings
861         char targetFile[FILE_MAX]; // temp. store filename from targetDir for access
862
863         float domainMat[4][4];
864         float invDomMat[4][4];
865
866         int noFrames;
867         int origFrame = scene->r.cfra;
868
869         FluidAnimChannels *channels = MEM_callocN(sizeof(FluidAnimChannels), "fluid domain animation channels");
870         ListBase *fobjects = MEM_callocN(sizeof(ListBase), "fluid objects");
871         FluidsimModifierData *fluidmd = NULL;
872         Mesh *mesh = NULL;
873
874         FluidBakeJob *fb;
875         elbeemSimulationSettings *fsset= MEM_callocN(sizeof(elbeemSimulationSettings), "Fluid sim settings");
876
877         fb= MEM_callocN(sizeof(FluidBakeJob), "fluid bake job");
878
879         if (BLI_getenv(strEnvName)) {
880                 int dlevel = atoi(BLI_getenv(strEnvName));
881                 elbeemSetDebugLevel(dlevel);
882                 BLI_snprintf(debugStrBuffer, sizeof(debugStrBuffer), "fluidsimBake::msg: Debug messages activated due to envvar '%s'\n", strEnvName);
883                 elbeemDebugOut(debugStrBuffer);
884         }
885
886         /* make sure it corresponds to startFrame setting (old: noFrames = scene->r.efra - scene->r.sfra +1) */;
887         noFrames = scene->r.efra - 0;
888         if (noFrames<=0) {
889                 BKE_report(reports, RPT_ERROR, "No frames to export (check your animation range settings)");
890                 fluidbake_free_data(channels, fobjects, fsset, fb);
891                 return 0;
892         }
893
894         /* check scene for sane object/modifier settings */
895         if (!fluid_validate_scene(reports, view_layer, fsDomain)) {
896                 fluidbake_free_data(channels, fobjects, fsset, fb);
897                 return 0;
898         }
899
900         /* these both have to be valid, otherwise we wouldn't be here */
901         fluidmd = (FluidsimModifierData *)modifiers_findByType(fsDomain, eModifierType_Fluidsim);
902         domainSettings = fluidmd->fss;
903         mesh = fsDomain->data;
904
905         domainSettings->bakeStart = 1;
906         domainSettings->bakeEnd = scene->r.efra;
907
908         // calculate bounding box
909         fluid_get_bb(mesh->mvert, mesh->totvert, fsDomain->obmat, domainSettings->bbStart, domainSettings->bbSize);
910
911         // reset last valid frame
912         domainSettings->lastgoodframe = -1;
913
914         /* delete old baked files */
915         fluidsim_delete_until_lastframe(domainSettings, relbase);
916
917         /* rough check of settings... */
918         if (domainSettings->previewresxyz > domainSettings->resolutionxyz) {
919                 BLI_snprintf(debugStrBuffer, sizeof(debugStrBuffer), "fluidsimBake::warning - Preview (%d) >= Resolution (%d)... setting equal.\n", domainSettings->previewresxyz,  domainSettings->resolutionxyz);
920                 elbeemDebugOut(debugStrBuffer);
921                 domainSettings->previewresxyz = domainSettings->resolutionxyz;
922         }
923         // set adaptive coarsening according to resolutionxyz
924         // this should do as an approximation, with in/outflow
925         // doing this more accurate would be overkill
926         // perhaps add manual setting?
927         if (domainSettings->maxRefine <0) {
928                 if (domainSettings->resolutionxyz>128) {
929                         gridlevels = 2;
930                 }
931                 else if (domainSettings->resolutionxyz > 64) {
932                         gridlevels = 1;
933                 }
934                 else {
935                         gridlevels = 0;
936                 }
937         }
938         else {
939                 gridlevels = domainSettings->maxRefine;
940         }
941         BLI_snprintf(debugStrBuffer, sizeof(debugStrBuffer), "fluidsimBake::msg: Baking %s, refine: %d\n", fsDomain->id.name, gridlevels);
942         elbeemDebugOut(debugStrBuffer);
943
944
945
946         /* ******** prepare output file paths ******** */
947         if (!fluid_init_filepaths(bmain, reports, domainSettings, fsDomain, targetDir, targetFile)) {
948                 fluidbake_free_data(channels, fobjects, fsset, fb);
949                 return false;
950         }
951
952         channels->length = scene->r.efra; // DG TODO: why using endframe and not "noFrames" here? .. because "noFrames" is buggy too? (not using sfra)
953         channels->aniFrameTime = (double)((double)domainSettings->animEnd - (double)domainSettings->animStart) / (double)noFrames;
954
955         /* ******** initialize and allocate animation channels ******** */
956         fluid_init_all_channels(C, fsDomain, domainSettings, channels, fobjects);
957
958         /* reset to original current frame */
959         scene->r.cfra = origFrame;
960         ED_update_for_newframe(CTX_data_main(C), depsgraph);
961
962         /* ******** init domain object's matrix ******** */
963         copy_m4_m4(domainMat, fsDomain->obmat);
964         if (!invert_m4_m4(invDomMat, domainMat)) {
965                 BLI_snprintf(debugStrBuffer, sizeof(debugStrBuffer), "fluidsimBake::error - Invalid obj matrix?\n");
966                 elbeemDebugOut(debugStrBuffer);
967                 BKE_report(reports, RPT_ERROR, "Invalid object matrix");
968
969                 fluidbake_free_data(channels, fobjects, fsset, fb);
970                 return 0;
971         }
972
973         /* ********  start writing / exporting ******** */
974         // use .tmp, don't overwrite/delete original file
975         BLI_join_dirfile(targetFile, sizeof(targetFile), targetDir, suffixConfigTmp);
976
977         /* ******** export domain to elbeem ******** */
978         elbeemResetSettings(fsset);
979         fsset->version = 1;
980         fsset->threads = (domainSettings->threads == 0) ? BKE_scene_num_threads(scene) : domainSettings->threads;
981         // setup global settings
982         copy_v3_v3(fsset->geoStart, domainSettings->bbStart);
983         copy_v3_v3(fsset->geoSize, domainSettings->bbSize);
984
985         // simulate with 50^3
986         fsset->resolutionxyz = (int)domainSettings->resolutionxyz;
987         fsset->previewresxyz = (int)domainSettings->previewresxyz;
988
989         fsset->realsize = get_fluid_size_m(scene, fsDomain, domainSettings);
990         fsset->viscosity = get_fluid_viscosity(domainSettings);
991         get_fluid_gravity(fsset->gravity, scene, domainSettings);
992
993         // simulate 5 frames, each 0.03 seconds, output to ./apitest_XXX.bobj.gz
994         fsset->animStart = domainSettings->animStart;
995         fsset->aniFrameTime = channels->aniFrameTime;
996         fsset->noOfFrames = noFrames; // is otherwise subtracted in parser
997
998         BLI_join_dirfile(targetFile, sizeof(targetFile), targetDir, suffixSurface);
999
1000         // defaults for compressibility and adaptive grids
1001         fsset->gstar = domainSettings->gstar;
1002         fsset->maxRefine = domainSettings->maxRefine; // check <-> gridlevels
1003         fsset->generateParticles = domainSettings->generateParticles;
1004         fsset->numTracerParticles = domainSettings->generateTracers;
1005         fsset->surfaceSmoothing = domainSettings->surfaceSmoothing;
1006         fsset->surfaceSubdivs = domainSettings->surfaceSubdivs;
1007         fsset->farFieldSize = domainSettings->farFieldSize;
1008         BLI_strncpy(fsset->outputPath, targetFile, sizeof(fsset->outputPath));
1009
1010         // domain channels
1011         fsset->channelSizeFrameTime =
1012         fsset->channelSizeViscosity =
1013         fsset->channelSizeGravity = channels->length;
1014         fsset->channelFrameTime = channels->DomainTime;
1015         fsset->channelViscosity = channels->DomainViscosity;
1016         fsset->channelGravity = channels->DomainGravity;
1017
1018         fsset->runsimCallback = &runSimulationCallback;
1019         fsset->runsimUserData = fb;
1020
1021         if (domainSettings->typeFlags & OB_FSBND_NOSLIP)                fsset->domainobsType = FLUIDSIM_OBSTACLE_NOSLIP;
1022         else if (domainSettings->typeFlags&OB_FSBND_PARTSLIP)   fsset->domainobsType = FLUIDSIM_OBSTACLE_PARTSLIP;
1023         else if (domainSettings->typeFlags&OB_FSBND_FREESLIP)   fsset->domainobsType = FLUIDSIM_OBSTACLE_FREESLIP;
1024         fsset->domainobsPartslip = domainSettings->partSlipValue;
1025
1026         /* use domainobsType also for surface generation flag (bit: >=64) */
1027         if (domainSettings->typeFlags & OB_FSSG_NOOBS)
1028                 fsset->mFsSurfGenSetting = FLUIDSIM_FSSG_NOOBS;
1029         else
1030                 fsset->mFsSurfGenSetting = 0; // "normal" mode
1031
1032         fsset->generateVertexVectors = (domainSettings->domainNovecgen==0);
1033
1034         // init blender domain transform matrix
1035         { int j;
1036         for (i=0; i<4; i++) {
1037                 for (j=0; j<4; j++) {
1038                         fsset->surfaceTrafo[i*4+j] = invDomMat[j][i];
1039                 }
1040         } }
1041
1042         /* ******** init solver with settings ******** */
1043         elbeemInit();
1044         elbeemAddDomain(fsset);
1045
1046         /* ******** export all fluid objects to elbeem ******** */
1047         export_fluid_objects(C, fobjects, scene, channels->length);
1048
1049         /* custom data for fluid bake job */
1050         fb->settings = fsset;
1051
1052         if (do_job) {
1053                 wmJob *wm_job = WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), scene, "Fluid Simulation",
1054                                             WM_JOB_PROGRESS, WM_JOB_TYPE_OBJECT_SIM_FLUID);
1055
1056                 /* setup job */
1057                 WM_jobs_customdata_set(wm_job, fb, fluidbake_free);
1058                 WM_jobs_timer(wm_job, 0.1, NC_SCENE|ND_FRAME, NC_SCENE|ND_FRAME);
1059                 WM_jobs_callbacks(wm_job, fluidbake_startjob, NULL, NULL, fluidbake_endjob);
1060
1061                 WM_jobs_start(CTX_wm_manager(C), wm_job);
1062         }
1063         else {
1064                 short dummy_stop = 0, dummy_do_update = 0;
1065                 float dummy_progress = 0.0f;
1066
1067                 /* blocking, use with exec() */
1068                 fluidbake_startjob((void *)fb, &dummy_stop, &dummy_do_update, &dummy_progress);
1069                 fluidbake_endjob((void *)fb);
1070                 fluidbake_free((void *)fb);
1071         }
1072
1073         /* ******** free stored animation data ******** */
1074         fluidbake_free_data(channels, fobjects, NULL, NULL);
1075
1076         // elbeemFree();
1077         return 1;
1078 }
1079
1080 static void UNUSED_FUNCTION(fluidsimFreeBake)(Object *UNUSED(ob))
1081 {
1082         /* not implemented yet */
1083 }
1084
1085 #else /* WITH_MOD_FLUID */
1086
1087 /* only compile dummy functions */
1088 static int fluidsimBake(bContext *UNUSED(C), ReportList *UNUSED(reports), Object *UNUSED(ob), short UNUSED(do_job))
1089 {
1090         return 0;
1091 }
1092
1093 #endif /* WITH_MOD_FLUID */
1094
1095 /***************************** Operators ******************************/
1096
1097 static int fluid_bake_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1098 {
1099         /* only one bake job at a time */
1100         if (WM_jobs_test(CTX_wm_manager(C), CTX_data_scene(C), WM_JOB_TYPE_OBJECT_SIM_FLUID))
1101                 return OPERATOR_CANCELLED;
1102
1103         if (!fluidsimBake(C, op->reports, CTX_data_active_object(C), true))
1104                 return OPERATOR_CANCELLED;
1105
1106         return OPERATOR_FINISHED;
1107 }
1108
1109 static int fluid_bake_exec(bContext *C, wmOperator *op)
1110 {
1111         if (!fluidsimBake(C, op->reports, CTX_data_active_object(C), false))
1112                 return OPERATOR_CANCELLED;
1113
1114         return OPERATOR_FINISHED;
1115 }
1116
1117 void FLUID_OT_bake(wmOperatorType *ot)
1118 {
1119         /* identifiers */
1120         ot->name = "Fluid Simulation Bake";
1121         ot->description = "Bake fluid simulation";
1122         ot->idname = "FLUID_OT_bake";
1123
1124         /* api callbacks */
1125         ot->invoke = fluid_bake_invoke;
1126         ot->exec = fluid_bake_exec;
1127         ot->poll = ED_operator_object_active_editable;
1128 }