Window resize aspect ratio glOrtho

Author Mitja Felicijan <mitja.felicijan@gmail.com> 2026-05-11 09:59:55 +0200
Committer Mitja Felicijan <mitja.felicijan@gmail.com> 2026-05-11 09:59:55 +0200
Commit d5430da02bf1004b91b9d75784dba4ccf1ede01a (patch)
-rw-r--r-- main.c 21
1 files changed, 19 insertions, 2 deletions
diff --git a/main.c b/main.c
...
221
	glEnable(GL_DEPTH_TEST);
221
	glEnable(GL_DEPTH_TEST);
222
	glMatrixMode(GL_PROJECTION);
222
	glMatrixMode(GL_PROJECTION);
223
	glLoadIdentity();
223
	glLoadIdentity();
224
	glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
224
  
  
225
	int w = game.width;
  
226
	int h = game.height;
  
227
	if (h == 0) h = 1;
  
228
	float aspect = (float)w / (float)h;
  
229
	if (w >= h) {
  
230
		glOrtho(0.5 - 0.5 * aspect, 0.5 + 0.5 * aspect, 0.0, 1.0, -1.0, 1.0);
  
231
	} else {
  
232
		glOrtho(0.0, 1.0, 0.5 - 0.5 / aspect, 0.5 + 0.5 / aspect, -1.0, 1.0);
  
233
	}
225
}
234
}
226
  
235
  
227
void handle_mouse_event(int button, int state, int x, int y) {
236
void handle_mouse_event(int button, int state, int x, int y) {
...
264
}
273
}
265
  
274
  
266
void handle_reshape(int w, int h) {
275
void handle_reshape(int w, int h) {
  
276
	if (h == 0) h = 1;
267
	glViewport (0, 0, (GLsizei) w, (GLsizei) h);
277
	glViewport (0, 0, (GLsizei) w, (GLsizei) h);
268
	glMatrixMode(GL_PROJECTION);
278
	glMatrixMode(GL_PROJECTION);
269
	glLoadIdentity();
279
	glLoadIdentity();
270
	glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
280
  
  
281
	float aspect = (float)w / (float)h;
  
282
	if (w >= h) {
  
283
		glOrtho(0.5 - 0.5 * aspect, 0.5 + 0.5 * aspect, 0.0, 1.0, -1.0, 1.0);
  
284
	} else {
  
285
		glOrtho(0.0, 1.0, 0.5 - 0.5 / aspect, 0.5 + 0.5 / aspect, -1.0, 1.0);
  
286
	}
  
287
  
271
	glMatrixMode(GL_MODELVIEW);
288
	glMatrixMode(GL_MODELVIEW);
272
	glLoadIdentity();
289
	glLoadIdentity();
273
}
290
}
...