Metaball tessellation optimization (Octree to BVH)
[blender.git] / source / blender / windowmanager / intern / wm_init_exit.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) 2007 Blender Foundation.
19  * All rights reserved.
20  *
21  * 
22  * Contributor(s): Blender Foundation
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/windowmanager/intern/wm_init_exit.c
28  *  \ingroup wm
29  *
30  * Manage initializing resources and correctly shutting down.
31  */
32
33 #include <stdlib.h>
34 #include <stdio.h>
35 #include <string.h>
36
37 #ifdef WIN32
38 #  include <windows.h>
39 #endif
40
41 #include "MEM_guardedalloc.h"
42
43 #include "DNA_scene_types.h"
44 #include "DNA_userdef_types.h"
45 #include "DNA_windowmanager_types.h"
46
47 #include "BLI_callbacks.h"
48 #include "BLI_listbase.h"
49 #include "BLI_path_util.h"
50 #include "BLI_string.h"
51 #include "BLI_threads.h"
52 #include "BLI_utildefines.h"
53
54 #include "BLO_writefile.h"
55
56 #include "BKE_blender.h"
57 #include "BKE_context.h"
58 #include "BKE_screen.h"
59 #include "BKE_DerivedMesh.h"
60 #include "BKE_global.h"
61 #include "BKE_library.h"
62 #include "BKE_main.h"
63 #include "BKE_mball_tessellate.h"
64 #include "BKE_node.h"
65 #include "BKE_report.h"
66
67 #include "BKE_addon.h"
68 #include "BKE_appdir.h"
69 #include "BKE_sequencer.h" /* free seq clipboard */
70 #include "BKE_material.h" /* clear_matcopybuf */
71 #include "BKE_tracking.h" /* free tracking clipboard */
72 #include "BKE_mask.h" /* free mask clipboard */
73
74 #include "RE_engine.h"
75 #include "RE_pipeline.h"        /* RE_ free stuff */
76
77 #ifdef WITH_PYTHON
78 #include "BPY_extern.h"
79 #endif
80
81 #ifdef WITH_GAMEENGINE
82 #  include "BL_System.h"
83 #endif
84 #include "GHOST_Path-api.h"
85 #include "GHOST_C-api.h"
86
87 #include "RNA_define.h"
88
89 #include "WM_api.h"
90 #include "WM_types.h"
91
92 #include "wm_cursors.h"
93 #include "wm_event_system.h"
94 #include "wm.h"
95 #include "wm_files.h"
96 #include "wm_window.h"
97
98 #include "ED_armature.h"
99 #include "ED_gpencil.h"
100 #include "ED_keyframing.h"
101 #include "ED_node.h"
102 #include "ED_render.h"
103 #include "ED_space_api.h"
104 #include "ED_screen.h"
105 #include "ED_util.h"
106
107 #include "UI_interface.h"
108 #include "BLF_api.h"
109 #include "BLF_translation.h"
110
111 #include "GPU_buffers.h"
112 #include "GPU_draw.h"
113 #include "GPU_init_exit.h"
114
115 #include "BKE_depsgraph.h"
116 #include "BKE_sound.h"
117 #include "COM_compositor.h"
118
119 static void wm_init_reports(bContext *C)
120 {
121         ReportList *reports = CTX_wm_reports(C);
122
123         BLI_assert(!reports || BLI_listbase_is_empty(&reports->list));
124
125         BKE_reports_init(reports, RPT_STORE);
126 }
127 static void wm_free_reports(bContext *C)
128 {
129         ReportList *reports = CTX_wm_reports(C);
130
131         BKE_reports_clear(reports);
132 }
133
134 bool wm_start_with_console = false; /* used in creator.c */
135
136 /* only called once, for startup */
137 void WM_init(bContext *C, int argc, const char **argv)
138 {
139         
140         if (!G.background) {
141                 wm_ghost_init(C);   /* note: it assigns C to ghost! */
142                 wm_init_cursor_data();
143         }
144         GHOST_CreateSystemPaths();
145
146         BKE_addon_pref_type_init();
147
148         wm_operatortype_init();
149         WM_menutype_init();
150         WM_uilisttype_init();
151
152         set_free_windowmanager_cb(wm_close_and_free);   /* library.c */
153         set_free_notifier_reference_cb(WM_main_remove_notifier_reference);   /* library.c */
154         set_blender_test_break_cb(wm_window_testbreak); /* blender.c */
155         DAG_editors_update_cb(ED_render_id_flush_update, ED_render_scene_update); /* depsgraph.c */
156         
157         ED_spacetypes_init();   /* editors/space_api/spacetype.c */
158         
159         ED_file_init();         /* for fsmenu */
160         ED_node_init_butfuncs();
161         
162         BLF_init(11, U.dpi); /* Please update source/gamengine/GamePlayer/GPG_ghost.cpp if you change this */
163         BLF_lang_init();
164
165         /* Enforce loading the UI for the initial homefile */
166         G.fileflags &= ~G_FILE_NO_UI;
167
168         /* get the default database, plus a wm */
169         wm_homefile_read(C, NULL, G.factory_startup, NULL);
170         
171         BLF_lang_set(NULL);
172
173         ED_spacemacros_init();
174
175         /* note: there is a bug where python needs initializing before loading the
176          * startup.blend because it may contain PyDrivers. It also needs to be after
177          * initializing space types and other internal data.
178          *
179          * However cant redo this at the moment. Solution is to load python
180          * before wm_homefile_read() or make py-drivers check if python is running.
181          * Will try fix when the crash can be repeated. - campbell. */
182
183 #ifdef WITH_PYTHON
184         BPY_context_set(C); /* necessary evil */
185         BPY_python_start(argc, argv);
186
187         BPY_python_reset(C);
188 #else
189         (void)argc; /* unused */
190         (void)argv; /* unused */
191 #endif
192
193         if (!G.background && !wm_start_with_console)
194                 GHOST_toggleConsole(3);
195
196         wm_init_reports(C); /* reports cant be initialized before the wm */
197
198         if (!G.background) {
199                 GPU_init();
200
201                 GPU_set_mipmap(!(U.gameflags & USER_DISABLE_MIPMAP));
202                 GPU_set_linear_mipmap(true);
203                 GPU_set_anisotropic(U.anisotropic_filter);
204                 GPU_set_gpu_mipmapping(U.use_gpu_mipmap);
205
206                 UI_init();
207         }
208         
209         clear_matcopybuf();
210         ED_render_clear_mtex_copybuf();
211
212         // glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
213                 
214         ED_preview_init_dbase();
215         
216         wm_read_history();
217
218         /* allow a path of "", this is what happens when making a new file */
219 #if 0
220         if (G.main->name[0] == 0)
221                 BLI_make_file_string("/", G.main->name, BKE_appdir_folder_default(), "untitled.blend");
222 #endif
223
224         BLI_strncpy(G.lib, G.main->name, FILE_MAX);
225
226 #ifdef WITH_COMPOSITOR
227         if (1) {
228                 extern void *COM_linker_hack;
229                 COM_linker_hack = COM_execute;
230         }
231 #endif
232         
233         /* load last session, uses regular file reading so it has to be in end (after init py etc) */
234         if (U.uiflag2 & USER_KEEP_SESSION) {
235                 /* calling WM_recover_last_session(C, NULL) has been moved to creator.c */
236                 /* that prevents loading both the kept session, and the file on the command line */
237         }
238         else {
239                 /* normally 'wm_homefile_read' will do this,
240                  * however python is not initialized when called from this function.
241                  *
242                  * unlikely any handlers are set but its possible,
243                  * note that recovering the last session does its own callbacks. */
244                 BLI_callback_exec(CTX_data_main(C), NULL, BLI_CB_EVT_VERSION_UPDATE);
245                 BLI_callback_exec(CTX_data_main(C), NULL, BLI_CB_EVT_LOAD_POST);
246         }
247 }
248
249 void WM_init_splash(bContext *C)
250 {
251         if ((U.uiflag & USER_SPLASH_DISABLE) == 0) {
252                 wmWindowManager *wm = CTX_wm_manager(C);
253                 wmWindow *prevwin = CTX_wm_window(C);
254         
255                 if (wm->windows.first) {
256                         CTX_wm_window_set(C, wm->windows.first);
257                         WM_operator_name_call(C, "WM_OT_splash", WM_OP_INVOKE_DEFAULT, NULL);
258                         CTX_wm_window_set(C, prevwin);
259                 }
260         }
261 }
262
263 bool WM_init_game(bContext *C)
264 {
265         wmWindowManager *wm = CTX_wm_manager(C);
266         wmWindow *win;
267
268         ScrArea *sa;
269         ARegion *ar = NULL;
270
271         Scene *scene = CTX_data_scene(C);
272
273         if (!scene) {
274                 /* XXX, this should not be needed. */
275                 Main *bmain = CTX_data_main(C);
276                 scene = bmain->scene.first;
277         }
278
279         win = wm->windows.first;
280
281         /* first to get a valid window */
282         if (win)
283                 CTX_wm_window_set(C, win);
284
285         sa = BKE_screen_find_big_area(CTX_wm_screen(C), SPACE_VIEW3D, 0);
286         ar = BKE_area_find_region_type(sa, RGN_TYPE_WINDOW);
287
288         /* if we have a valid 3D view */
289         if (sa && ar) {
290                 ARegion *arhide;
291
292                 CTX_wm_area_set(C, sa);
293                 CTX_wm_region_set(C, ar);
294
295                 /* disable quad view */
296                 if (ar->alignment == RGN_ALIGN_QSPLIT)
297                         WM_operator_name_call(C, "SCREEN_OT_region_quadview", WM_OP_EXEC_DEFAULT, NULL);
298
299                 /* toolbox, properties panel and header are hidden */
300                 for (arhide = sa->regionbase.first; arhide; arhide = arhide->next) {
301                         if (arhide->regiontype != RGN_TYPE_WINDOW) {
302                                 if (!(arhide->flag & RGN_FLAG_HIDDEN)) {
303                                         ED_region_toggle_hidden(C, arhide);
304                                 }
305                         }
306                 }
307
308                 /* full screen the area */
309                 if (!sa->full) {
310                         ED_screen_state_toggle(C, win, sa, SCREENMAXIMIZED);
311                 }
312
313                 /* Fullscreen */
314                 if ((scene->gm.playerflag & GAME_PLAYER_FULLSCREEN)) {
315                         WM_operator_name_call(C, "WM_OT_window_fullscreen_toggle", WM_OP_EXEC_DEFAULT, NULL);
316                         wm_get_screensize(&ar->winrct.xmax, &ar->winrct.ymax);
317                         ar->winx = ar->winrct.xmax + 1;
318                         ar->winy = ar->winrct.ymax + 1;
319                 }
320                 else {
321                         GHOST_RectangleHandle rect = GHOST_GetClientBounds(win->ghostwin);
322                         ar->winrct.ymax = GHOST_GetHeightRectangle(rect);
323                         ar->winrct.xmax = GHOST_GetWidthRectangle(rect);
324                         ar->winx = ar->winrct.xmax + 1;
325                         ar->winy = ar->winrct.ymax + 1;
326                         GHOST_DisposeRectangle(rect);
327                 }
328
329                 WM_operator_name_call(C, "VIEW3D_OT_game_start", WM_OP_EXEC_DEFAULT, NULL);
330
331                 BKE_sound_exit();
332
333                 return true;
334         }
335         else {
336                 ReportTimerInfo *rti;
337
338                 BKE_report(&wm->reports, RPT_ERROR, "No valid 3D View found, game auto start is not possible");
339
340                 /* After adding the report to the global list, reset the report timer. */
341                 WM_event_remove_timer(wm, NULL, wm->reports.reporttimer);
342
343                 /* Records time since last report was added */
344                 wm->reports.reporttimer = WM_event_add_timer(wm, CTX_wm_window(C), TIMER, 0.02);
345
346                 rti = MEM_callocN(sizeof(ReportTimerInfo), "ReportTimerInfo");
347                 wm->reports.reporttimer->customdata = rti;
348
349                 return false;
350         }
351 }
352
353 /* free strings of open recent files */
354 static void free_openrecent(void)
355 {
356         struct RecentFile *recent;
357         
358         for (recent = G.recent_files.first; recent; recent = recent->next)
359                 MEM_freeN(recent->filepath);
360         
361         BLI_freelistN(&(G.recent_files));
362 }
363
364
365 /* bad stuff*/
366
367 // XXX copy/paste buffer stuff...
368 extern void free_anim_copybuf(void);
369 extern void free_anim_drivers_copybuf(void);
370 extern void free_fmodifiers_copybuf(void);
371
372 #ifdef WIN32
373 /* Read console events until there is a key event.  Also returns on any error. */
374 static void wait_for_console_key(void)
375 {
376         HANDLE hConsoleInput = GetStdHandle(STD_INPUT_HANDLE);
377
378         if (!ELEM(hConsoleInput, NULL, INVALID_HANDLE_VALUE) && FlushConsoleInputBuffer(hConsoleInput)) {
379                 for (;;) {
380                         INPUT_RECORD buffer;
381                         DWORD ignored;
382
383                         if (!ReadConsoleInput(hConsoleInput, &buffer, 1, &ignored)) {
384                                 break;
385                         }
386
387                         if (buffer.EventType == KEY_EVENT) {
388                                 break;
389                         }
390                 }
391         }
392 }
393 #endif
394
395 /* called in creator.c even... tsk, split this! */
396 /* note, doesnt run exit() call WM_exit() for that */
397 void WM_exit_ext(bContext *C, const bool do_python)
398 {
399         wmWindowManager *wm = C ? CTX_wm_manager(C) : NULL;
400
401         BKE_sound_exit();
402
403         /* first wrap up running stuff, we assume only the active WM is running */
404         /* modal handlers are on window level freed, others too? */
405         /* note; same code copied in wm_files.c */
406         if (C && wm) {
407                 wmWindow *win;
408
409                 if (!G.background) {
410                         if ((U.uiflag2 & USER_KEEP_SESSION) || BKE_undo_valid(NULL)) {
411                                 /* save the undo state as quit.blend */
412                                 char filename[FILE_MAX];
413                                 bool has_edited;
414                                 int fileflags = G.fileflags & ~(G_FILE_COMPRESS | G_FILE_AUTOPLAY | G_FILE_LOCK | G_FILE_SIGN | G_FILE_HISTORY);
415
416                                 BLI_make_file_string("/", filename, BKE_tempdir_base(), BLENDER_QUIT_FILE);
417
418                                 has_edited = ED_editors_flush_edits(C, false);
419
420                                 if ((has_edited && BLO_write_file(CTX_data_main(C), filename, fileflags, NULL, NULL)) ||
421                                     BKE_undo_save_file(filename))
422                                 {
423                                         printf("Saved session recovery to '%s'\n", filename);
424                                 }
425                         }
426                 }
427                 
428                 WM_jobs_kill_all(wm);
429
430                 for (win = wm->windows.first; win; win = win->next) {
431                         
432                         CTX_wm_window_set(C, win);  /* needed by operator close callbacks */
433                         WM_event_remove_handlers(C, &win->handlers);
434                         WM_event_remove_handlers(C, &win->modalhandlers);
435                         ED_screen_exit(C, win, win->screen);
436                 }
437         }
438
439         BKE_addon_pref_type_free();
440         wm_operatortype_free();
441         wm_dropbox_free();
442         WM_menutype_free();
443         WM_uilisttype_free();
444         
445         /* all non-screen and non-space stuff editors did, like editmode */
446         if (C)
447                 ED_editors_exit(C);
448
449 //      XXX     
450 //      BIF_GlobalReebFree();
451 //      BIF_freeRetarget();
452         BIF_freeTemplates(C);
453
454         free_openrecent();
455         
456         BKE_mball_cubeTable_free();
457         
458         /* render code might still access databases */
459         RE_FreeAllRender();
460         RE_engines_exit();
461         
462         ED_preview_free_dbase();  /* frees a Main dbase, before free_blender! */
463
464         if (C && wm)
465                 wm_free_reports(C);  /* before free_blender! - since the ListBases get freed there */
466
467         BKE_sequencer_free_clipboard(); /* sequencer.c */
468         BKE_tracking_clipboard_free();
469         BKE_mask_clipboard_free();
470                 
471 #ifdef WITH_COMPOSITOR
472         COM_deinitialize();
473 #endif
474         
475         free_blender();  /* blender.c, does entire library and spacetypes */
476 //      free_matcopybuf();
477         free_anim_copybuf();
478         free_anim_drivers_copybuf();
479         free_fmodifiers_copybuf();
480         ED_gpencil_strokes_copybuf_free();
481         ED_clipboard_posebuf_free();
482         BKE_node_clipboard_clear();
483
484         BLF_exit();
485
486 #ifdef WITH_INTERNATIONAL
487         BLF_free_unifont();
488         BLF_free_unifont_mono();
489         BLF_lang_free();
490 #endif
491         
492         ANIM_keyingset_infos_exit();
493         
494 //      free_txt_data();
495         
496
497 #ifdef WITH_PYTHON
498         /* option not to close python so we can use 'atexit' */
499         if (do_python) {
500                 /* XXX - old note */
501                 /* before free_blender so py's gc happens while library still exists */
502                 /* needed at least for a rare sigsegv that can happen in pydrivers */
503
504                 /* Update for blender 2.5, move after free_blender because blender now holds references to PyObject's
505                  * so decref'ing them after python ends causes bad problems every time
506                  * the pyDriver bug can be fixed if it happens again we can deal with it then */
507                 BPY_python_end();
508         }
509 #else
510         (void)do_python;
511 #endif
512
513         if (!G.background) {
514                 GPU_global_buffer_pool_free();
515                 GPU_free_unused_buffers();
516
517                 GPU_exit();
518         }
519
520         BKE_reset_undo(); 
521         
522         ED_file_exit(); /* for fsmenu */
523
524         UI_exit();
525         BKE_userdef_free();
526
527         RNA_exit(); /* should be after BPY_python_end so struct python slots are cleared */
528         
529         wm_ghost_exit();
530
531         CTX_free(C);
532 #ifdef WITH_GAMEENGINE
533         SYS_DeleteSystem(SYS_GetSystem());
534 #endif
535         
536         GHOST_DisposeSystemPaths();
537
538         BLI_threadapi_exit();
539
540         if (MEM_get_memory_blocks_in_use() != 0) {
541                 size_t mem_in_use = MEM_get_memory_in_use() + MEM_get_memory_in_use();
542                 printf("Error: Not freed memory blocks: %d, total unfreed memory %f MB\n",
543                        MEM_get_memory_blocks_in_use(),
544                        (double)mem_in_use / 1024 / 1024);
545                 MEM_printmemlist();
546         }
547         wm_autosave_delete();
548
549         BKE_tempdir_session_purge();
550 }
551
552 void WM_exit(bContext *C)
553 {
554         WM_exit_ext(C, 1);
555
556         printf("\nBlender quit\n");
557
558 #ifdef WIN32
559         /* ask user to press a key when in debug mode */
560         if (G.debug & G_DEBUG) {
561                 printf("Press any key to exit . . .\n\n");
562                 wait_for_console_key();
563         }
564 #endif
565
566         exit(G.is_break == true);
567 }