Author: richm (posted 2012-11-28 23:59:32, viewed 240 times)
| 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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
|
public class Game
{
private final int DEFAULT_FPS = 60;
private int width;
private int height;
private String title;
private boolean running;
private int targetFPS;
public static MatrixData matrixData;
public Game(int width, int height, String title)
{
this.width = width;
this.height = height;
this.title = title;
}
private void start()
{
if (this.isRunning())
{
return;
}
this.initGL();
this.initGame();
this.run();
}
public void stop()
{
this.running = false;
}
private void initGL()
{
try
{
PixelFormat pixelFormat = new PixelFormat();
ContextAttribs contextAttributes = new ContextAttribs(3, 2);
contextAttributes.withForwardCompatible(true);
contextAttributes.withProfileCore(true);
Display.setDisplayMode(new DisplayMode(this.width, this.height));
Display.setTitle(this.title);
Display.create(pixelFormat, contextAttributes);
GL11.glViewport(0, 0, this.width, this.height);
} catch (LWJGLException e)
{
e.printStackTrace();
System.exit(1);
}
GL11.glClearColor(0.1F, 0.1F, 0.15F, 1.0F);
GL11.glViewport(0, 0, this.width, this.height);
Game.matrixData = new MatrixData();
Game.matrixData.setupMatrices(60F, ((float) width / (float) height), 0.1F, 100.0F);
Game.exitOnGLError("InitGL");
}
private void initGame()
{
this.targetFPS = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDisplayMode().getRefreshRate();
if (this.targetFPS == java.awt.DisplayMode.REFRESH_RATE_UNKNOWN)
{
this.targetFPS = this.DEFAULT_FPS;
}
Screen.screens.push(new GameScreen());
this.running = true;
}
private void run()
{
while (this.isRunning())
{
this.update();
this.render();
Display.sync(this.targetFPS);
Display.update();
}
this.cleanup();
}
private void update()
{
if (Display.isCloseRequested())
{
this.stop();
}
float rotationDelta = 15f;
float scaleDelta = 0.1f;
float posDelta = 0.1f;
Vector3f scaleAddResolution = new Vector3f(scaleDelta, scaleDelta, scaleDelta);
Vector3f scaleMinusResolution = new Vector3f(-scaleDelta, -scaleDelta, -scaleDelta);
Keyboard.poll();
while (Keyboard.next())
{
if (!Keyboard.getEventKeyState())
continue;
switch (Keyboard.getEventKey())
{
case Keyboard.KEY_UP:
matrixData.modelPos.y += posDelta;
break;
case Keyboard.KEY_DOWN:
matrixData.modelPos.y -= posDelta;
break;
case Keyboard.KEY_P:
Vector3f.add(matrixData.modelScale, scaleAddResolution, matrixData.modelScale);
break;
case Keyboard.KEY_M:
Vector3f.add(matrixData.modelScale, scaleMinusResolution, matrixData.modelScale);
break;
case Keyboard.KEY_LEFT:
matrixData.modelAngle.z += rotationDelta;
break;
case Keyboard.KEY_RIGHT:
matrixData.modelAngle.z -= rotationDelta;
break;
}
}
Game.matrixData.updateMatrices();
if (!Screen.screens.empty())
{
Iterator<Screen> itr = Screen.screens.iterator();
while (itr.hasNext())
{
Screen screen = itr.next();
if (!screen.isPaused())
{
screen.update();
}
}
}
Game.exitOnGLError("Update");
}
private void render()
{
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
if (!Screen.screens.empty())
{
Iterator<Screen> itr = Screen.screens.iterator();
while (itr.hasNext())
{
Screen screen = itr.next();
if (!screen.isHidden())
{
screen.render();
}
}
}
Game.exitOnGLError("Render");
}
private void cleanup()
{
for (Texture texture : Texture.toDelete)
{
GL11.glDeleteTextures(texture.getID());
}
GL20.glUseProgram(0);
for (ShaderProgram shader : ShaderProgram.toDelete)
{
GL20.glDetachShader(shader.getID(), shader.getVertexShader().getID());
GL20.glDetachShader(shader.getID(), shader.getFragmentShader().getID());
GL20.glDeleteShader(shader.getVertexShader().getID());
GL20.glDeleteShader(shader.getFragmentShader().getID());
GL20.glDeleteProgram(shader.getID());
}
ShaderProgram.toDelete.clear();
for (VertexArray vertexArray : VertexArray.toDelete)
{
GL30.glBindVertexArray(vertexArray.getID());
boolean[] enabled = vertexArray.getAttributes();
for (int i = 0; i < enabled.length; i++)
{
if (enabled[i])
{
GL20.glDisableVertexAttribArray(i);
}
}
for (VertexBuffer buffer : vertexArray.getVertexBuffers())
{
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
GL15.glDeleteBuffers(buffer.getID());
GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, 0);
GL15.glDeleteBuffers(buffer.getID());
}
GL30.glBindVertexArray(0);
GL30.glDeleteVertexArrays(vertexArray.getID());
}
VertexArray.toDelete.clear();
System.out.println("Closing...");
Display.destroy();
}
public int getWidth()
{
return this.width;
}
public int getHeight()
{
return this.height;
}
public String getTitle()
{
return this.title;
}
public boolean isRunning()
{
return this.running;
}
public static MatrixData getMatrixData()
{
return Game.matrixData;
}
public static void exitOnGLError(String errorMessage) {
int errorValue = GL11.glGetError();
if (errorValue != GL11.GL_NO_ERROR) {
String errorString = GLU.gluErrorString(errorValue);
System.err.println("ERROR - " + errorMessage + ": " + errorString);
if (Display.isCreated()) Display.destroy();
System.exit(-1);
}
}
public static void main(String[] args)
{
new Game(400, 400, "Game").start();
}
}
public class MatrixData
{
private final double PI = 3.14159265358979323846;
public int projectionMatrixLocation;
public Matrix4f projectionMatrix;
public int viewMatrixLocation;
public Matrix4f viewMatrix;
public int modelMatrixLocation;
public Matrix4f modelMatrix;
public Vector3f modelPos;
public Vector3f modelAngle;
public Vector3f modelScale;
public Vector3f cameraPos;
public FloatBuffer matrix44Buffer;
public int shaderID;
public MatrixData()
{
}
public void setupMatrices(float fov, float aspectRatio, float zNear, float zFar)
{
System.out.println("FOV: " + fov + " AspectRatio: " + aspectRatio + " zNear: " + zNear + " zFar: " + zFar);
this.projectionMatrix = new Matrix4f();
float yScale = this.coTangent(this.degreesToRadians(fov / 2F));
float xScale = yScale / aspectRatio;
float frustumLength = zFar - zNear;
this.projectionMatrix.m00 = xScale;
this.projectionMatrix.m11 = yScale;
this.projectionMatrix.m22 = -((zFar + zNear) / frustumLength);
this.projectionMatrix.m23 = -1;
this.projectionMatrix.m32 = ((2 * zNear * zFar) / frustumLength);
this.viewMatrix = new Matrix4f();
this.modelMatrix = new Matrix4f();
this.matrix44Buffer = BufferUtils.createFloatBuffer(16);
this.modelPos = new Vector3f(0.0F, 0.0F, 0.0F);
this.modelAngle = new Vector3f(0.0F, 0.0F, 0.0F);
this.modelScale = new Vector3f(1.0F, 1.0F, 1.0F);
this.cameraPos = new Vector3f(0.0F, 0.0F, 0.0F);
}
public void updateMatrices()
{
this.viewMatrix = new Matrix4f();
this.modelMatrix = new Matrix4f();
Matrix4f.translate(this.cameraPos, this.viewMatrix, this.viewMatrix);
Matrix4f.scale(this.modelScale, this.modelMatrix, this.modelMatrix);
Matrix4f.translate(this.modelPos, this.modelMatrix, this.modelMatrix);
Matrix4f.rotate(this.degreesToRadians(this.modelAngle.z), new Vector3f(0, 0, 1), this.modelMatrix, this.modelMatrix);
Matrix4f.rotate(this.degreesToRadians(this.modelAngle.y), new Vector3f(0, 1, 0), this.modelMatrix, this.modelMatrix);
Matrix4f.rotate(this.degreesToRadians(this.modelAngle.x), new Vector3f(1, 0, 0), this.modelMatrix, this.modelMatrix);
GL20.glUseProgram(this.shaderID);
projectionMatrix.store(matrix44Buffer);
matrix44Buffer.flip();
GL20.glUniformMatrix4(projectionMatrixLocation, false, matrix44Buffer);
viewMatrix.store(matrix44Buffer);
matrix44Buffer.flip();
GL20.glUniformMatrix4(viewMatrixLocation, false, matrix44Buffer);
modelMatrix.store(matrix44Buffer);
matrix44Buffer.flip();
GL20.glUniformMatrix4(modelMatrixLocation, false, matrix44Buffer);
GL20.glUseProgram(0);
}
private float coTangent(float angle)
{
return (float) (1.0F / Math.tan(angle));
}
private float degreesToRadians(float degrees)
{
return degrees * (float) (PI / 180D);
}
}
public class GameScreen extends Screen
{
public static final String name = "GameScreen";
private VertexArray vao;
private VertexBuffer vbo;
private VertexBuffer vboI;
private Quad quad;
private ShaderProgram shaderProgram;
private Texture texture;
public GameScreen()
{
super(name);
}
@Override
public void initialise()
{
this.quad = new Quad(new Vector3f(0, 0, 0), 1);
this.quad.create();
this.quad.setIndices(new byte[] { 0, 1, 2, 2, 3, 0 });
this.vao = new VertexArray();
GL30.glBindVertexArray(this.vao.getID());
this.vbo = new VertexBuffer();
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, this.vbo.getID());
GL15.glBufferData(GL15.GL_ARRAY_BUFFER, this.quad.getVerticesBuffer(), GL15.GL_STREAM_DRAW);
GL20.glVertexAttribPointer(0, VertexData.positionElementCount, GL11.GL_FLOAT, false, VertexData.stride, VertexData.positionByteOffset);
this.vao.setAttribute(0, true);
GL20.glVertexAttribPointer(1, VertexData.colorElementCount, GL11.GL_FLOAT, false, VertexData.stride, VertexData.colorByteOffset);
this.vao.setAttribute(1, true);
GL20.glVertexAttribPointer(2, VertexData.textureElementCount, GL11.GL_FLOAT, false, VertexData.stride, VertexData.textureByteOffset);
this.vao.setAttribute(2, true);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
GL30.glBindVertexArray(0);
this.vboI = new VertexBuffer();
GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, this.vboI.getID());
GL15.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, this.quad.getIndicesBuffer(), GL15.GL_STATIC_DRAW);
GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, 0);
this.shaderProgram = new ShaderProgram();
this.shaderProgram.setVertexShader(new VertexShader("/vertex.glsl"));
this.shaderProgram.setFragmentShader(new FragmentShader("/fragment.glsl"));
GL20.glLinkProgram(this.shaderProgram.getID());
GL20.glBindAttribLocation(this.shaderProgram.getID(), 0, "in_Position");
GL20.glBindAttribLocation(this.shaderProgram.getID(), 1, "in_Color");
GL20.glBindAttribLocation(this.shaderProgram.getID(), 2, "in_TextureCoord");
Game.matrixData.projectionMatrixLocation = GL20.glGetUniformLocation(this.shaderProgram.getID(), "projectionMatrix");
Game.matrixData.viewMatrixLocation = GL20.glGetUniformLocation(this.shaderProgram.getID(), "viewMatrix");
Game.matrixData.modelMatrixLocation = GL20.glGetUniformLocation(this.shaderProgram.getID(), "modelMatrix");
GL20.glValidateProgram(this.shaderProgram.getID());
Game.matrixData.shaderID = this.shaderProgram.getID();
this.texture = TextureLoader.loadTexture("/texture.png", GL13.GL_TEXTURE0);
Game.exitOnGLError("Initialise");
}
@Override
public void update()
{
Game.exitOnGLError("Update");
}
@Override
public void render()
{
GL20.glUseProgram(shaderProgram.getID());
GL13.glActiveTexture(GL13.GL_TEXTURE0);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.texture.getID());
GL30.glBindVertexArray(this.vao.getID());
GL20.glEnableVertexAttribArray(0);
GL20.glEnableVertexAttribArray(1);
GL20.glEnableVertexAttribArray(2);
GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, this.vbo.getID());
GL11.glDrawElements(GL11.GL_TRIANGLES, this.quad.getIndices().length, GL11.GL_UNSIGNED_BYTE, 0);
GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, 0);
GL20.glDisableVertexAttribArray(0);
GL20.glDisableVertexAttribArray(1);
GL20.glDisableVertexAttribArray(2);
GL30.glBindVertexArray(0);
GL20.glUseProgram(0);
Game.exitOnGLError("Render");
}
}
public class Quad
{
private VertexData[] vertices;
private byte[] indices;
private Vector3f position;
private int size;
public Quad(Vector3f position, int size)
{
this.position = position;
this.size = size;
}
public void create()
{
float x = this.position.x;
float y = this.position.y;
float z = this.position.z;
VertexData v0 = new VertexData();
VertexData v1 = new VertexData();
VertexData v2 = new VertexData();
VertexData v3 = new VertexData();
v0.setXYZ(x, y, z);
v1.setXYZ(x, y + size, z);
v2.setXYZ(x + size, y + size, z);
v3.setXYZ(x + size, y, z);
v0.setRGB(1.0F, 0.0F, 0.0F);
v1.setRGB(1.0F, 0.0F, 0.0F);
v2.setRGB(1.0F, 0.0F, 0.0F);
v3.setRGB(1.0F, 0.0F, 0.0F);
v0.setST(0, 0);
v0.setST(0, 1);
v0.setST(1, 1);
v0.setST(1, 0);
this.vertices = new VertexData[] { v0, v1, v2, v3 };
}
public VertexData[] getVertices()
{
return this.vertices;
}
public byte[] getIndices()
{
return this.indices;
}
public void setIndices(byte[] indices)
{
this.indices = indices;
}
public FloatBuffer getVerticesBuffer()
{
ByteBuffer byteBuffer = BufferUtils.createByteBuffer(this.vertices.length * VertexData.stride);
FloatBuffer floatBuffer = byteBuffer.asFloatBuffer();
for (int i = 0; i < this.vertices.length; i++)
{
floatBuffer.put(vertices[i].getElements());
}
floatBuffer.flip();
return floatBuffer;
}
public ByteBuffer getIndicesBuffer()
{
ByteBuffer buffer = BufferUtils.createByteBuffer(this.indices.length);
buffer.put(this.indices);
buffer.flip();
return buffer;
}
}
public class VertexArray
{
public static Set<VertexArray> toDelete = new HashSet<VertexArray>();
private int id;
private Set<VertexBuffer> buffers;
private boolean[] attributes;
public VertexArray()
{
this.buffers = new HashSet<VertexBuffer>();
this.attributes = new boolean[16];
this.id = GL30.glGenVertexArrays();
VertexArray.toDelete.add(this);
}
public int getID()
{
return this.id;
}
public Set<VertexBuffer> getVertexBuffers()
{
return this.buffers;
}
public boolean[] getAttributes()
{
return this.attributes;
}
public void setAttribute(int index, boolean bool)
{
this.attributes[index] = bool;
}
}
public class VertexBuffer
{
public static final Set<VertexBuffer> toDelete = new HashSet<VertexBuffer>();
private int id;
public VertexBuffer()
{
this.id = GL15.glGenBuffers();
VertexBuffer.toDelete.add(this);
}
public int getID()
{
return this.id;
}
}
public class ShaderProgram
{
public static final Set<ShaderProgram> toDelete = new HashSet<ShaderProgram>();
private int programID;
private VertexShader vertexShader;
private FragmentShader fragmentShader;
public ShaderProgram()
{
this.programID = GL20.glCreateProgram();
ShaderProgram.toDelete.add(this);
}
public int getID()
{
return this.programID;
}
public VertexShader getVertexShader()
{
return this.vertexShader;
}
public void setVertexShader(VertexShader vertexShader)
{
if (this.vertexShader != null)
{
GL20.glDetachShader(this.programID, this.vertexShader.getID());
GL20.glDeleteShader(this.vertexShader.getID());
}
this.vertexShader = vertexShader;
GL20.glAttachShader(this.programID, this.vertexShader.getID());
}
public FragmentShader getFragmentShader()
{
return this.fragmentShader;
}
public void setFragmentShader(FragmentShader fragmentShader)
{
if (this.fragmentShader != null)
{
GL20.glDetachShader(this.programID, this.fragmentShader.getID());
GL20.glDeleteShader(this.fragmentShader.getID());
}
this.fragmentShader = fragmentShader;
GL20.glAttachShader(this.programID, this.fragmentShader.getID());
}
@SuppressWarnings("deprecation")
public static int loadShader(String filepath, int type)
{
StringBuilder sb = new StringBuilder();
int shaderID = 0;
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(ShaderProgram.class.getResourceAsStream(filepath)));
String line;
while ((line = reader.readLine()) != null)
{
sb.append(line).append("\n");
}
reader.close();
} catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
shaderID = GL20.glCreateShader(type);
GL20.glShaderSource(shaderID, sb.toString());
GL20.glCompileShader(shaderID);
if (GL20.glGetShader(shaderID, GL20.GL_COMPILE_STATUS) == GL11.GL_FALSE)
{
System.err.println("Shader could not be compiled. " + filepath);
System.exit(1);
}
return shaderID;
}
} |
Special syntax:
- To highlight a line (yellow background), prefix it with '@@'
- To indicate that a line should be removed (red background), prefix it with '-'
- To indicate that a line should be added (green background), prefix it with '+'
- To post multiple snippets, seperate them by '~~~~'
|
Add your game by posting it in the WIP section,
or publish it in Showcase.
The first screenshot will be displayed as a thumbnail.
|
|