File: Painter.cpp

package info (click to toggle)
storm-lang 0.7.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 51,984 kB
  • sloc: ansic: 261,420; cpp: 140,270; sh: 14,877; perl: 9,846; python: 2,525; lisp: 2,504; asm: 860; makefile: 678; pascal: 70; java: 52; xml: 37; awk: 12
file content (428 lines) | stat: -rw-r--r-- 10,938 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
#include "stdafx.h"
#include "Painter.h"
#include "App.h"
#include "Surface.h"
#include "Exception.h"

namespace gui {

	Painter::Painter()
		: continuous(false), uiContinuous(false), synchronizedPresent(false), resized(false), currentRendering(false),
		  repaintCounter(0), currentRepaint(0), tickCallbackId(0), surface(null) {

		attachedTo = Window::invalid;
		app = gui::app(engine());
		bgColor = app->defaultBgColor;
		mgr = gui::renderMgr(engine());
		lock = new (this) Lock();
	}

	Painter::~Painter() {
		detach();
	}

	Bool Painter::render(Size size, Graphics *graphics) {
		return false;
	}

	Image *Painter::captureImage(Size size) {
		return captureImage(size, bgColor);
	}

	Image *Painter::captureImage(Size size, Color bgColor) {
		if (attachedTo == Window::invalid || !surface || !graphics) {
			// TODO: We might be able to lift this limitation. It is possible to create freestanding GL contexts, for example.
			throw new (this) GuiError(S("Can not capture an image from a Painter that is not attached to a window."));
		}

		Bool first = true;
		while (true) {
			if (!first)
				os::UThread::leave();

			Lock::Guard z(lock);
			if (currentRendering) {
				// Wait for no rendering to be happening at the moment.
				first = false;
				continue;
			}

			Size oldSize = surface->size;
			Float oldScale = surface->scale;

			surface->prepareGrab(size, 1);
			graphics->surfaceResized();

			try {
				graphics->beforeRender(bgColor);
				render(surface->size, graphics);
				graphics->afterRender();

			} catch (...) {
				surface->resize(oldSize, oldScale);
				graphics->surfaceResized();
				resized = true;

				throw;
			}

			// Extract the picture!
			Image *result = surface->grabImage(engine());

			surface->resize(oldSize, oldScale);
			graphics->surfaceResized();
			resized = true;

			if (!result)
				throw new (this) GuiError(S("This rendering method does not support 'captureImage'."));

			return result;
		}
	}

	void Painter::attach(Window *to) {
		Handle handle = to->handle();
		if (handle != attachedTo) {
			detach();

			surface = mgr->attach(this, handle);
			if (surface) {
				graphics = surface->createGraphics(engine());
				attachedTo = handle;
			} else {
				// Will be attached again later. This currently only happens in Gtk+.
				attachedTo = Window::invalid;
			}
		}
	}

	void Painter::detach() {
		if (attachedTo != Window::invalid) {
			attachedTo = Window::invalid;
			destroy();
		}
	}

	void Painter::resize(Size sz, Float scale) {
		if (surface) {
			// Do not attempt to resize the drawing surface if we're currently drawing to it.
			Lock::Guard z(lock);

			// This seems to not be neccessary. Probably because the resources are actually
			// associated to the underlying D3D device, and not the RenderTarget.
			// If the resize call fails for some reason, this is probably the cause.

			// destroyResources();

			// Don't resize if there is nothing to do.
			if (sz == surface->size && scale == surface->scale)
				return;

			surface->resize(sz, scale);
			if (graphics)
				graphics->surfaceResized();

			// Invalidate the current frame.
			resized = true;
		}
	}

	void Painter::destroy() {
		// Wait until we're not rendering anymore.
		Lock::Guard z(lock);

		if (graphics) {
			graphics->surfaceDestroyed();
			graphics->destroy();
		}
		graphics = null;
		delete surface;
		surface = null;

		mgr->detach(this);
	}

	void Painter::repaint() {
		if (!surface)
			return;

		if (continuous) {
			waitForFrame();
		} else {
			doRepaint(false, false);
		}
	}

	void Painter::doRepaint(bool waitForVSync, bool fromDraw) {
		if (!surface)
			return;

		bool more = false;
		try {
			Lock::Guard z(lock);
			repaintCounter++;
			resized = false;
			more = doRepaintI(waitForVSync, fromDraw);
		} catch (...) {
			throw;
		}

		if (more != continuous) {
			continuous = more;
			if (more) {
				// Register!
				mgr->painterReady();
			}
		}
	}

	bool Painter::doRepaintI(bool waitForVSync, bool fromDraw) {
		if (!surface)
			return false;

		// Make sure we're not presenting while drawing.
		Lock::Guard z(lock);

		// If we're currently rendering in the same thread, don't do it since rendering is not
		// reentrant. We do this inside the lock so that it protects the 'currentRendering' variable
		// as well.
		if (currentRendering)
			return false;
		currentRendering = true;

		bool more = false;
		bool ok = false;

		try {
			graphics->beforeRender(bgColor);
			more = render(surface->size / surface->scale, graphics);
			ok = graphics->afterRender();
		} catch (...) {
			graphics->afterRender();
			currentRendering = false;
			throw;
		}

		// It is OK to re-set the variable here already since the remainder of the function does not
		// call in to user code, and since we are protected by a lock.
		currentRendering = false;

		// Don't try to present if something failed.
		if (!ok)
			return more;

		// Try to present the frame.
		switch (surface->present(waitForVSync)) {
		case Surface::pSuccess:
			// All is well. Remember that we presented the frame.
			synchronizedPresent = false;
			atomicWrite(currentRepaint, atomicRead(repaintCounter));
			break;
		case Surface::pRecreate:
			// We need to re-create the render target.
			destroy();
			surface = mgr->attach(this, attachedTo);
			graphics = surface->createGraphics(engine());
			// TODO: We probably want to redraw immediately here. We can at least schedule a re-draw
			// on the next frame! On Windows, this is almost equivalent, as we won't wait for vsync
			// since Present() failed. On Linux, this will not happen.
			return true;
		case Surface::pRepaint:
			// If this was not a direct call from "repaint", we need to schedule a repaint through
			// the windowing system.
			synchronizedPresent = true;
			if (!fromDraw)
				repaintAttachedWindow();
			break;
		case Surface::pFailure:
			// Something else failed. Not too much we can do, I guess. This likely indicates either
			// a bug in the implementation, or an out of memory condition.
			WARNING(L"Rendering failure! Either you are out of (graphics) memory, or you have found a bug.");
			break;
		}

		return more;
	}

	void Painter::uiAfterRepaint(RepaintParams *params) {
		if (synchronizedPresent) {
			Lock::Guard z(lock);

			// If we don't have any surface, then we're being destroyed.
			if (!surface)
				return;

			surface->repaint(params);
			atomicWrite(currentRepaint, atomicRead(repaintCounter));

			// If we are in continuous mode, schedule drawing the next frame right now.
			if (continuous) {
				mgr->painterReady();
#ifdef UI_SINGLETHREAD
				// If single threaded, we need to repaint now.
				repaintAttachedWindow();
#endif
			}

			// Update the repaint registration.
			if (uiContinuous != continuous) {
				uiSetContinuous(continuous);
				uiContinuous = continuous;
			}
		}
	}

	bool Painter::ready() {
		// Wait until the previous frame is actually shown.
		return atomicRead(currentRepaint) == atomicRead(repaintCounter);
	}

	void Painter::waitForFrame() {
		if (synchronizedPresent) {
			// Just wait until we're not drawing at the moment.
			Lock::Guard z(lock);
		} else {
			// Wait until we have rendered a frame, so that Windows think we did it to satisfy the
			// paint request.
			Nat old = atomicRead(currentRepaint);
			while (old == atomicRead(currentRepaint))
				os::UThread::leave();
		}
	}


#ifdef UI_SINGLETHREAD

	void Painter::repaintI(RepaintParams *params) {
		beforeRepaint(params);

		// Do we need to render the frame now, or did we already render something before?
		if (ready())
			doRepaint(false, true);

		afterRepaint();
	}

	void Painter::uiAttach(Window *to) {
		attach(to);
	}

	void Painter::uiDetach() {
		if (uiContinuous) {
			uiSetContinuous(false);
			uiContinuous = false;
		}

		detach();
	}

	void Painter::uiResize(Size size, Float scale) {
		resize(size, scale);
	}

	void Painter::uiRepaint(RepaintParams *par) {
		repaintI(par);
		uiAfterRepaint(par);
	}

#endif
#ifdef UI_MULTITHREAD

	void Painter::repaintI(RepaintParams *params) {
		if (resized && synchronizedPresent) {
			// If we're resized and are running in the "synchronized present" mode, always repaint now.
			doRepaint(false, true);
		} else if (!ready()) {
			// There is a frame ready right now! No need to wait even if we're not in continuous mode!
		} else if (continuous && resized) {
			// Note: This only happens on windows. In this case, we don't want to wait for a frame
			// as it makes resizing the window laggy.
		} else if (continuous) {
			// Make sure we have a frame to render.
			waitForFrame();
		} else {
			doRepaint(false, true);
		}
	}

	void Painter::uiAttach(Window *to) {
		// Note: We're blocking the UI thread here, as Gtk+ requires some intricate interaction with
		// the UI thread to create GL context, etc.
		os::Future<void> result(os::FutureMode::exclusive);
		Painter *me = this;
		os::FnCall<void, 2> params = os::fnCall().add(me).add(to);
		os::UThread::spawn(address(&Painter::attach), true, params, result, &associatedThread()->thread());
		result.result();
	}

	void Painter::uiDetach() {
		if (uiContinuous) {
			uiSetContinuous(false);
			uiContinuous = false;
		}

		os::Future<void> result;
		Painter *me = this;
		os::FnCall<void, 2> params = os::fnCall().add(me);
		os::UThread::spawn(address(&Painter::detach), true, params, result, &associatedThread()->thread());
		result.result();
	}

	void Painter::uiResize(Size size, Float scale) {
		os::Future<void> result;
		Painter *me = this;
		os::FnCall<void, 3> params = os::fnCall().add(me).add(size).add(scale);
		os::UThread::spawn(address(&Painter::resize), true, params, result, &associatedThread()->thread());
		result.result();
	}

	void Painter::uiRepaint(RepaintParams *par) {
		os::Future<void> result;
		Painter *me = this;
		os::FnCall<void, 2> params = os::fnCall().add(me).add(par);
		os::UThread::spawn(address(&Painter::repaintI), true, params, result, &associatedThread()->thread());
		result.result();

		uiAfterRepaint(par);
	}

#endif

#ifdef GUI_WIN32

	void Painter::repaintAttachedWindow() {
		WARNING(L"This operation is not supported on Win32, as it should not be needed.");
	}

	void Painter::uiSetContinuous(bool) {
		// Not needed on Windows.
	}

#endif
#ifdef GUI_GTK

	void Painter::repaintAttachedWindow() {
#ifdef UI_MULTITHREAD
		if (!uiContinuous)
			app->repaint(attachedTo.widget());
#else
		gtk_widget_queue_draw(attachedTo.widget());
#endif
	}

	// Called on each tick. We only need to queue a repaint for the widget.
	static gboolean tickCallback(GtkWidget *widget, GdkFrameClock *clock, gpointer data) {
		gtk_widget_queue_draw(widget);
		return G_SOURCE_CONTINUE;
	}

	void Painter::uiSetContinuous(bool continuous) {
		if (continuous) {
			tickCallbackId = gtk_widget_add_tick_callback(attachedTo.widget(), &tickCallback, NULL, NULL);
		} else {
			gtk_widget_remove_tick_callback(attachedTo.widget(), tickCallbackId);
		}
	}

#endif
}