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