Advertisement
Guest User

Untitled

a guest
Aug 10th, 2014
290
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.62 KB | None | 0 0
  1.  
  2. import java.io.BufferedReader;
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.FileReader;
  6. import java.io.IOException;
  7. import java.io.InputStream;
  8. import java.nio.ByteBuffer;
  9. import java.nio.FloatBuffer;
  10. import java.nio.IntBuffer;
  11.  
  12. import org.lwjgl.BufferUtils;
  13. import org.lwjgl.Sys;
  14. import org.lwjgl.input.Keyboard;
  15. import org.lwjgl.input.Mouse;
  16. import org.lwjgl.opengl.ContextAttribs;
  17. import org.lwjgl.opengl.Display;
  18. import org.lwjgl.opengl.DisplayMode;
  19. import org.lwjgl.opengl.PixelFormat;
  20. import org.lwjgl.util.vector.Vector3f;
  21. import org.newdawn.slick.Color;
  22. import org.newdawn.slick.TrueTypeFont;
  23.  
  24. import static org.lwjgl.opengl.GL11.*;
  25. import static org.lwjgl.opengl.GL12.*;
  26. import static org.lwjgl.opengl.GL13.*;
  27. import static org.lwjgl.opengl.GL15.*;
  28. import static org.lwjgl.opengl.GL20.*;
  29. import static org.lwjgl.util.glu.GLU.*;
  30. import de.matthiasmann.twl.utils.PNGDecoder;
  31.  
  32. public class MainScreen {
  33.  
  34. private static boolean isFullScreen=false;//Check full screen settings
  35. private static boolean isGameRunning=true;//End of game settings
  36. private static boolean initialCameraPositionHasBeenSet = false;//origin location for the camera for setUpUtil making sure it has a starting pos
  37. private static boolean hasBeenSetUp=false;//For setting up utils so that i can create it once and never worry again,
  38. private boolean wireFrameMode=true;
  39.  
  40. private static float lastTime=0.0f;//Used mainly for handling time offsets for mouse control
  41. private static float time,dt;/////// Could be used for other time issues but will need another variable because they are both used
  42.  
  43. private static float mouseSensitivity = 1.0f;//Mouse sensitivity settings
  44. private static float movementSpeed = 1.0f; //General ms (Movement Speed) settings
  45. private static final float CUBE_LENGTH=1.0f;//Base final cube size, Note: this cannot change as everything graphically is based off it
  46. private static int blockX,blockY,blockZ;//For all of the x,y,z locations of the blocks in the game, VBO positions of the quads are based off this.
  47. private static float screenResolutionWidth=800,screenResolutionHeight=600;//screen resolution x, y
  48.  
  49. static int VBOVertexHandle;//GL location vertex
  50. static int VBONormalHandle;///GL color vertex
  51. static int VBOTextureHandle;//GL Texture vertex
  52.  
  53. static int dirtTexture;
  54. static int defaultTexture;
  55.  
  56. static int fps;
  57.  
  58. int shaderProgram;
  59. int vertexShader;
  60. int fragmentShader;
  61.  
  62. StringBuilder vertexShaderSource = new StringBuilder();;
  63. StringBuilder fragmentShaderSource = new StringBuilder();
  64.  
  65. TrueTypeFont font;
  66.  
  67. static Block blocks[][][]= new Block[Chunk.CHUNK_SIZE][Chunk.CHUNK_SIZE][Chunk.CHUNK_SIZE];//Created blocks, to be held in multiple chunks
  68. static Chunk chunks;//Rendered chunks in 16 * 16 *16 lots
  69.  
  70. Camera c =new Camera();// Main camera mode, created from user defined Camera class
  71. DisplayMode displayMode;//GL display mode settings for the main window
  72. /**
  73. * Main game loop method, all is controlled here
  74. *
  75. */
  76. public void runGame(){
  77.  
  78. while(isGameRunning){
  79.  
  80. try {
  81.  
  82. createWindow();
  83. setUpUtil();
  84. running();
  85.  
  86. } catch (Exception e) {
  87.  
  88. e.printStackTrace();
  89.  
  90. }
  91.  
  92. }
  93. }
  94.  
  95. /**Main method in this class that runs all of the methods used for openGl and creating the images
  96. * in the 3D space
  97. *
  98. */
  99. private void running() {
  100. InitGL();
  101.  
  102. chunks=new Chunk(0,0,0,blocks);
  103.  
  104. while (!Display.isCloseRequested()) {
  105. try{
  106. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  107. glLoadIdentity();// Can be replaces by push matrix pop matrix around open gl code before update
  108. c.processMouse(mouseSensitivity);
  109. c.processKeyboard(getTimeChange(), movementSpeed);
  110. c.applyTranslations();
  111. startTime();
  112. if(c.yaw() %60==0){
  113. RebuildMesh(0,0,0);
  114. }
  115. render();
  116.  
  117. Display.update();
  118. Display.sync(60);
  119.  
  120. }catch(Exception e){
  121.  
  122. }
  123. }
  124. destroy();
  125. isGameRunning=false;
  126.  
  127. }
  128. /**
  129. * Destroys everything that has been created
  130. */
  131. private void destroy() {
  132. //need to destroy open GL bindings in here also
  133.  
  134. glDisableClientState(GL_VERTEX_ARRAY);
  135. glDisableClientState(GL_TEXTURE_COORD_ARRAY);
  136. glDisableClientState(GL_SHADE_MODEL);
  137. glDeleteBuffers(VBOVertexHandle);
  138. glDeleteBuffers(VBOTextureHandle);
  139. glDeleteBuffers(VBONormalHandle);
  140. glDeleteShader(vertexShader);
  141. glDeleteShader(fragmentShader);
  142. Display.destroy();
  143. Keyboard.destroy();
  144. Mouse.destroy();
  145.  
  146. }
  147.  
  148. /**
  149. * Initiates the inital values of the camera, x,y,zand all of the initial mouse positions.
  150. */
  151. void setUpUtil()
  152. {
  153. if(!hasBeenSetUp){
  154.  
  155. loadTextures();
  156. font=FontCreator.loadFont("simplifica");
  157. if(!initialCameraPositionHasBeenSet)
  158. {
  159. c.setPosition(0,0,9.0f);
  160. initialCameraPositionHasBeenSet=true;
  161. }
  162.  
  163. hasBeenSetUp=true;
  164. }
  165. c.applyOptimalStates();
  166. c.processMouse(mouseSensitivity);
  167. c.processKeyboard(getTimeChange(),movementSpeed);
  168. }
  169. /**
  170. * Texture to be loaded
  171. */
  172. private void loadTextures() {
  173. dirtTexture = setupTextures("dirt_32");
  174. defaultTexture = setupTextures("default_32");
  175. }
  176.  
  177. /**
  178. * Creates the basic main window to view the game is.
  179. * Fullscreen is set here upon first start up of the game.
  180. * @throws Exception
  181. */
  182. void createWindow() throws Exception
  183. {
  184. if(!Display.isCreated())
  185. {
  186. Display.setFullscreen(isFullScreen);
  187. DisplayMode d[] = Display.getAvailableDisplayModes();
  188. for (int i = 0; i < d.length; i++)
  189. {
  190. if (d[i].getWidth() == screenResolutionWidth && d[i].getHeight() == screenResolutionHeight && d[i].getBitsPerPixel() == 32) {
  191. displayMode = d[i];
  192. break;
  193. }
  194. }
  195.  
  196. Display.setDisplayMode(displayMode);
  197. Display.setTitle("Bending");
  198. Display.create();
  199.  
  200. }
  201.  
  202. }
  203.  
  204. /**
  205. *
  206. * @param key used as a base pathfile name /resources/texures will already by created just need the png file name, without the extention
  207. */
  208. private int setupTextures(String key) {
  209. IntBuffer tmp = BufferUtils.createIntBuffer(1);
  210. glGenTextures(tmp);
  211. tmp.rewind();
  212. try {
  213. InputStream in = new FileInputStream("res/Textures/"+key+".png");
  214. PNGDecoder decoder = new PNGDecoder(in);
  215.  
  216. System.out.println("width=" + decoder.getWidth());
  217. System.out.println("height=" + decoder.getHeight());
  218.  
  219. ByteBuffer buf = ByteBuffer.allocateDirect(4 * decoder.getWidth() * decoder.getHeight());
  220. decoder.decode(buf, decoder.getWidth() * 4, PNGDecoder.Format.RGBA);
  221. buf.flip();
  222.  
  223. glBindTexture(GL_TEXTURE_2D, tmp.get(0));
  224. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  225. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  226. glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  227. glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
  228. glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
  229. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, decoder.getWidth(), decoder.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buf);
  230. int unsigned = (buf.get(0) & 0xff);
  231.  
  232. System.out.println(unsigned);
  233. System.out.println(buf.get(1));
  234. System.out.println(buf.get(2));
  235. System.out.println(buf.get(3));
  236.  
  237. } catch (FileNotFoundException ex) {
  238. System.out.println("Error " + "/res/Textures/" + key + ".png" + " not found");
  239. } catch (IOException e) {
  240. System.out.println("Error decoding " + "/res/Textures/" + key + ".png");
  241. }
  242. tmp.rewind();
  243.  
  244. return tmp.get(0);
  245. }
  246.  
  247. /**
  248. * Basic render of the game, handles all of the visible chunks and blocks within view
  249. * @param wireFrameMode
  250. *
  251. */
  252. public void render()
  253. {
  254. calculateFps();
  255. glPushMatrix();
  256. glActiveTexture(GL_TEXTURE0);
  257. glBindTexture(GL_TEXTURE_2D, defaultTexture);
  258. glBindBuffer(GL_ARRAY_BUFFER, VBOVertexHandle);
  259. glVertexPointer(3, GL_FLOAT, 0, 0L);
  260.  
  261. glBindBuffer(GL_ARRAY_BUFFER, VBONormalHandle);
  262. glNormalPointer(GL_FLOAT, 0, 0L);
  263.  
  264. glBindBuffer(GL_ARRAY_BUFFER, VBOTextureHandle);
  265. glTexCoordPointer(2, GL_FLOAT, 0, 0L);
  266. if(wireFrameMode){
  267. glDrawArrays(GL_LINE_LOOP,0,Chunk.CHUNK_SIZE * Chunk.CHUNK_SIZE * Chunk.CHUNK_SIZE * 4 * 6);
  268. }else{
  269. glDrawArrays(GL_QUADS, 0, Chunk.CHUNK_SIZE * Chunk.CHUNK_SIZE * Chunk.CHUNK_SIZE * 4 * 6);//24 points on a cube to draw. 4 points per face 6 faces
  270. }
  271. font.drawString(50, 50, "FPS: " + fps, Color.green);
  272. glPopMatrix();
  273.  
  274. glFlush();
  275. }
  276.  
  277. private static int getTexture(Block block)
  278. {
  279.  
  280. switch (block.GetID()) {
  281. case 1:
  282. case 2:
  283. return dirtTexture;
  284. case 3:
  285. }
  286. return defaultTexture;//failed to load texture
  287. }
  288. /**
  289. * Creates the Chunk for rendering
  290. *
  291. */
  292. public static void createChunk(float x, float y, float z){
  293. chunks.setStartX((int) x);
  294. chunks.setStartY((int) y);
  295. chunks.setStartZ((int) z);
  296. return;
  297.  
  298. }
  299. /**
  300. * Creates a basic cube for the engine, fundimental method
  301. * @param x position in the world
  302. * @param y also position in the world
  303. * @param z also position in the world
  304. * @return returns a float array for use in openGL
  305. */
  306. public static float[] createBlock(float x, float y, float z)
  307. {
  308. int offset = (int) (CUBE_LENGTH / 2);
  309. return new float[] {
  310.  
  311. x + offset, y + offset,z,
  312. x - offset, y + offset,z,
  313. x - offset, y + offset,z - CUBE_LENGTH,
  314. x + offset, y + offset,z - CUBE_LENGTH,
  315.  
  316. x + offset, y - offset, z - CUBE_LENGTH,
  317. x - offset, y - offset,z - CUBE_LENGTH,
  318. x - offset, y - offset,z,
  319. x + offset, y - offset,z,
  320.  
  321. x + offset, y + offset, z - CUBE_LENGTH,
  322. x - offset, y + offset, z - CUBE_LENGTH,
  323. x - offset, y - offset,z - CUBE_LENGTH,
  324. x + offset, y - offset,z - CUBE_LENGTH,
  325.  
  326. x + offset, y - offset, z,
  327. x - offset, y - offset, z,
  328. x - offset, y + offset, z,
  329. x + offset, y + offset, z,
  330.  
  331. x - offset, y + offset, z - CUBE_LENGTH,
  332. x - offset, y + offset, z,
  333. x - offset, y - offset, z,
  334. x - offset, y - offset,z - CUBE_LENGTH,
  335.  
  336. x + offset, y + offset, z,
  337. x + offset, y + offset,z - CUBE_LENGTH,
  338. x + offset, y - offset, z - CUBE_LENGTH,
  339. x + offset, y - offset, z
  340. };
  341.  
  342. }
  343.  
  344. /**
  345. * Write fps and info to top left off screen for dev mode
  346. * turns on free flight and a range of other dev options
  347. */
  348. private void setDevMode(){
  349.  
  350. }
  351. /**
  352. * Starts up base settings of open GL
  353. * This is where the Depth and base background and 2d textures on all of the polygons is set
  354. *
  355. */
  356. private void InitGL()
  357. {
  358. glEnable(GL_TEXTURE_2D);
  359. glShadeModel(GL_SMOOTH);glClearColor(0.4f, 0.6f, 0.9f, 0f);
  360. glClearDepth(1.0f);
  361. glEnable(GL_DEPTH_TEST);
  362. glDepthFunc(GL_LEQUAL);
  363.  
  364. glEnable(GL_BLEND);
  365. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  366.  
  367.  
  368. glEnableClientState(GL_VERTEX_ARRAY);
  369. glEnableClientState(GL_TEXTURE_COORD_ARRAY);
  370.  
  371. glMatrixMode(GL_PROJECTION);
  372. glLoadIdentity();
  373.  
  374. gluPerspective( 45.0f, (float)displayMode.getWidth() / (float)displayMode.getHeight(), 0.1f, 100.0f);
  375. glMatrixMode(GL_MODELVIEW);
  376. glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
  377.  
  378. }
  379.  
  380.  
  381. public static void RebuildMesh(float startX, float startY, float startZ) {
  382.  
  383. VBOTextureHandle = glGenBuffers();
  384. VBOVertexHandle = glGenBuffers();
  385. VBONormalHandle = glGenBuffers();
  386.  
  387. FloatBuffer VertexTextureData = BufferUtils.createFloatBuffer((Chunk.CHUNK_SIZE* Chunk.CHUNK_SIZE * Chunk.CHUNK_SIZE)*6 * 8);
  388. FloatBuffer VertexPositionData = BufferUtils.createFloatBuffer((Chunk.CHUNK_SIZE * Chunk.CHUNK_SIZE * Chunk.CHUNK_SIZE) * 6 * 3 * 4);//6 faces, (3*4) 12 is made up of 4 points to a quad and 3 values xyz
  389. FloatBuffer VertexNormalData = BufferUtils.createFloatBuffer((Chunk.CHUNK_SIZE * Chunk.CHUNK_SIZE * Chunk.CHUNK_SIZE) * 6 * 3 * 4);
  390.  
  391.  
  392. for (float x = 0; x < Chunk.CHUNK_SIZE; x += 1) {
  393. for (float y = 0; y < Chunk.CHUNK_SIZE; y += 1) {
  394. for (float z = 0; z < Chunk.CHUNK_SIZE; z += 1) {
  395. VertexPositionData.put(createBlock((float) startX + x * CUBE_LENGTH, (float) startY + y * CUBE_LENGTH, (float) startZ + z * CUBE_LENGTH));
  396. VertexNormalData.put(createBlock((float) startX + x * CUBE_LENGTH, (float) startY + y * CUBE_LENGTH, (float) startZ + z * CUBE_LENGTH));
  397. VertexTextureData.put(getTexPosData());
  398. }
  399. }
  400. }
  401.  
  402. VertexTextureData.flip();
  403. VertexPositionData.flip();
  404. VertexNormalData.flip();
  405.  
  406. glBindBuffer(GL_ARRAY_BUFFER, VBOVertexHandle);
  407. glBufferData(GL_ARRAY_BUFFER, VertexPositionData, GL_STATIC_DRAW);
  408.  
  409. glBindBuffer(GL_ARRAY_BUFFER, 0);
  410. glBindBuffer(GL_ARRAY_BUFFER, VBONormalHandle);
  411. glBufferData(GL_ARRAY_BUFFER, VertexNormalData, GL_STATIC_DRAW);
  412.  
  413. glBindBuffer(GL_ARRAY_BUFFER, 0);
  414. glBindBuffer(GL_ARRAY_BUFFER, VBOTextureHandle);
  415. glBufferData(GL_ARRAY_BUFFER, VertexTextureData, GL_STATIC_DRAW);
  416.  
  417. glBindBuffer(GL_ARRAY_BUFFER, 0);
  418.  
  419. }
  420.  
  421.  
  422. private static float[] getTexPosData() {
  423.  
  424. return new float[]{
  425. 0,0, 0,1, 1,1, 1,0,// once for each face 6 faces
  426.  
  427. 0,0, 0,1, 1,1, 1,0,
  428.  
  429. 0,0, 0,1, 1,1, 1,0,
  430.  
  431. 0,0, 0,1, 1,1, 1,0,
  432.  
  433. 0,0, 0,1, 1,1, 1,0,
  434.  
  435. 0,0, 0,1, 1,1, 1,0
  436. };
  437. }
  438.  
  439. private float getTimeChange()
  440. {
  441. time=Sys.getTime() * 1000 / Sys.getTimerResolution();
  442. dt = (time - lastTime);
  443. lastTime = time;
  444. return dt;
  445.  
  446. }
  447.  
  448. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement