Author Topic: Black screen  (Read 2709 times)

Offline KOsmos

  • byte
  • *
  • Posts: 4
    • View Profile
Black screen
« on: May 18, 2009, 10:17:30 pm »
Hi
This is my first post so if i put this in a wrong place please move it somewhere else.

It's my second evening of struggle ;) with JPCT. I try to use the car example basic game framework and my own objects/game logic. However I can't even get a simple cube displayed. So far I copied the code that is responsible for drawing and initializing a scene. I tried to replace the original terrain with a cube, but I see only a black screen. Please tell me what i do wrong or what am i missing.
Code: [Select]
import java.io.*;

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;

import com.threed.jpct.*;
import com.threed.jpct.util.*;

public class Game1Test{
      /**
    * A flag that signals a change of the renderer (don't ask about the 35 here....)
    */
    private final static int SWITCH_RENDERER=35;

    /**
    * Should we try to do fullscreen?
    */
    private boolean fullscreen=false;

    /**
    * Are we using OpenGL?
    */
    private boolean openGL=false;

    /**
    * Are we rendering in wireframe mode?
    */
    private boolean wireframe=false;

    /**
    * Some jPCT related stuff
    */
    private FrameBuffer buffer=null;
    private World theWorld=null;
    private TextureManager texMan=null;
    private Camera camera=null;

    /**
    * Default size of the framebuffer
    */
    private int width=640;
    private int height=480;

    /**
    * Some AWT related stuff
    */
    private Frame frame=null;
    private Graphics gFrame=null;
    private BufferStrategy bufferStrategy=null;
    private GraphicsDevice device=null;
    private int titleBarHeight=0;
    private int leftBorderWidth=0;

    private int switchMode=0;

    private int fps;
    private int lastFps;
    private long totalFps;

    private int pps;
    private int lastPps;

    private boolean isIdle=false;
    private boolean exit=false;

     /**
    * Flags for the keys
    */
    private boolean left=false;
    private boolean right=false;
    private boolean forward=false;
    private boolean back=false;

    private float speed=0;

    private KeyMapper keyMapper=null;

    private Object3D terrain = null;

    public static void main(String[] args) {
        new Game1Test(args);
    }

    private Game1Test(String args[]){
        Config.maxPolysVisible = 10000;

        /**
        * Evaluate the commandline parameters
        */
        for (int i=0; i<args.length; i++) {
            if (args[i].equals("fullscreen")) {
               fullscreen=true;
               Config.glFullscreen=true;
            }
            if (args[i].equals("mipmap")) {
               Config.glMipmap=true;
            }
            if (args[i].equals("trilinear")) {
               Config.glTrilinear=true;
            }

            if (args[i].equals("16bit")) {
               Config.glColorDepth=16;
            }
            try {
                if (args[i].startsWith("width=")) {
                   width=Integer.parseInt(args[i].substring(6));
                }
                if (args[i].startsWith("height=")) {
                   height=Integer.parseInt(args[i].substring(7));
                }
                if (args[i].startsWith("refresh=")) {
                   Config.glRefresh=Integer.parseInt(args[i].substring(8));
                }
                if (args[i].startsWith("zbuffer=")) {
                   Config.glZBufferDepth=Integer.parseInt(args[i].substring(8));
                   if (Config.glZBufferDepth==16) {
                      Config.glFixedBlitting=true;
                   }
                }
            } catch (Exception e) {
              // We don't care
            }
        }
        isIdle=false;
        switchMode=0;
        totalFps=0;
        fps=0;
        lastFps=0;

        /**
        * Initialize the World instance and get the TextureManager (a singleton)
        */
        theWorld=new World();
        Config.fadeoutLight=false;
        theWorld.getLights().setOverbrightLighting(Lights.OVERBRIGHT_LIGHTING_DISABLED);
        theWorld.getLights().setRGBScale(Lights.RGB_SCALE_2X);
        theWorld.setAmbientLight(25, 30, 30);
        theWorld.addLight(new SimpleVector(0, -150, 0), 25, 22, 19);
        theWorld.addLight(new SimpleVector(-1000, -150, 1000), 22, 5, 4);
        theWorld.addLight(new SimpleVector(1000, -150, -1000), 4, 2, 22);

        texMan=TextureManager.getInstance();
        TextureManager.getInstance().addTexture("box", new Texture("box.jpg"));

        terrain = Primitives.getCube(100);
        terrain.setTexture("box");
        terrain.setEnvmapped(Object3D.ENVMAP_ENABLED);
        terrain.build();

        SimpleVector pos=terrain.getCenter();
        pos.scalarMul(-1f);
        terrain.translate(pos);
        terrain.rotateX((float)-Math.PI/2f);
        terrain.translateMesh();
        terrain.rotateMesh();
        terrain.setTranslationMatrix(new Matrix());
        terrain.setRotationMatrix(new Matrix());

        theWorld.addObject(terrain);
        theWorld.buildAllObjects();

        camera=theWorld.getCamera();
        camera.setPosition(50,-50,-5);
        camera.lookAt(terrain.getTransformedCenter());

        //Config.tuneForOutdoor();

        initializeFrame();

        gameLoop();
    }

    private void initializeFrame(){
        if (fullscreen) {
           GraphicsEnvironment env=GraphicsEnvironment.getLocalGraphicsEnvironment();
           device=env.getDefaultScreenDevice();
           GraphicsConfiguration gc=device.getDefaultConfiguration();
           frame=new Frame(gc);
           frame.setUndecorated(true);
           frame.setIgnoreRepaint(true);
           device.setFullScreenWindow(frame);
           if (device.isDisplayChangeSupported()) {
              device.setDisplayMode(new DisplayMode(width, height, 32, 0));
           }
           frame.createBufferStrategy(2);
           bufferStrategy=frame.getBufferStrategy();
           Graphics g=bufferStrategy.getDrawGraphics();
           bufferStrategy.show();
           g.dispose();
        }
        else{
            frame=new Frame();
            frame.setTitle("jPCT "+Config.getVersion());
            frame.pack();
            Insets insets = frame.getInsets();
            titleBarHeight=insets.top;
            leftBorderWidth=insets.left;
            frame.setSize(width+leftBorderWidth+insets.right, height+titleBarHeight+insets.bottom);
            frame.setResizable(false);
            frame.show();
            gFrame=frame.getGraphics();
        }

       /**
       * The listeners are bound to the AWT frame...they are useless in OpenGL mode.
       */
       frame.addWindowListener(new WindowEvents());
       keyMapper=new KeyMapper(frame);
   }

   private void gameLoop(){
      World.setDefaultThread(Thread.currentThread());

      buffer=new FrameBuffer(width, height, FrameBuffer.SAMPLINGMODE_NORMAL);
      buffer.enableRenderer(IRenderer.RENDERER_SOFTWARE);
      buffer.setBoundingBoxMode(FrameBuffer.BOUNDINGBOX_NOT_USED);

      buffer.optimizeBufferAccess();

      Timer timer=new Timer(25);
      timer.start();

      Timer fpsTimer=new Timer(1000);
      fpsTimer.start();

      while (!exit) {
            if (!isIdle) {

               long ticks=timer.getElapsedTicks();

               for (int i=0; i<ticks; i++) {
                //moveCar();
                //processProjectiles();
                    moveCamera();
               }

            poll();

            if (switchMode!=0) {
               switchOptions();
            }

            buffer.clear();
            theWorld.renderScene(buffer);

            if (!wireframe) {
               theWorld.draw(buffer);
            }
            else {
               theWorld.drawWireframe(buffer, Color.white);
            }
            buffer.update();
            display();

            fps++;
            pps+=theWorld.getVisibilityList().getSize();

            if (fpsTimer.getElapsedTicks()>0) {
               totalFps=(fps-lastFps);
               lastFps=fps;
               lastPps=pps;
               pps=0;
            }

            Thread.yield();

         } else {
            try {
               Thread.sleep(500);
            } catch (InterruptedException e) {}
         }
      }

      if (!openGL && fullscreen) {
         device.setFullScreenWindow(null);
      }

      System.exit(0);
   }

   private void moveCamera() {
      SimpleVector oldCamPos=camera.getPosition();
      SimpleVector oldestCamPos=new SimpleVector(oldCamPos);
      oldCamPos.scalarMul(9f);

      SimpleVector terrainCenter=terrain.getTransformedCenter();
      SimpleVector camPos=new SimpleVector(terrainCenter);
      SimpleVector zOffset=terrain.getZAxis();
      SimpleVector yOffset=new SimpleVector(0, -100, 0);
      zOffset.scalarMul(-250f);

      camPos.add(zOffset);
      camPos.add(yOffset);

      camPos.add(oldCamPos);
      camPos.scalarMul(0.1f);

      SimpleVector delta=camPos.calcSub(oldestCamPos);
      float len=delta.length();

      //if (len!=0) {
         /**
          * Do a collision detection between the camera and the ground to prevent the camera from
          * moving into the ground.
          */
         //theWorld.checkCameraCollisionEllipsoid(delta.normalize(), new SimpleVector(20, 20, 20), len, 3);
      //}

      /**
       * And finally: Look at the car
       */
      camera.lookAt(terrain.getTransformedCenter());
   }

   private void switchOptions() {
        switch (switchMode) {
            case (SWITCH_RENDERER): {
                 isIdle=true;
                 if (buffer.usesRenderer(IRenderer.RENDERER_OPENGL)) {
                    keyMapper.destroy();
                    buffer.disableRenderer(IRenderer.RENDERER_OPENGL);
                    buffer.enableRenderer(IRenderer.RENDERER_SOFTWARE, IRenderer.MODE_OPENGL);
                    openGL=false;
                    if (fullscreen) {
                       device.setFullScreenWindow(null);
                    }
                    frame.hide();
                    frame.dispose();
                    initializeFrame();
                 }
                 else {
                    frame.hide();
                    buffer.enableRenderer(IRenderer.RENDERER_OPENGL, IRenderer.MODE_OPENGL);
                    buffer.disableRenderer(IRenderer.RENDERER_SOFTWARE);
                    openGL=true;
                    keyMapper.destroy();
                    keyMapper=new KeyMapper();
                 }
                 isIdle=false;
                 break;
            }
        }
        switchMode=0;
   }

   private void poll() {
        KeyState state=null;
        do {
           state=keyMapper.poll();
           if (state!=KeyState.NONE) {
              keyAffected(state);
           }
        } while (state!=KeyState.NONE);
   }

   private void display() {

        //blitNumber((int) totalFps, 5, 2);
        //blitNumber((int) lastPps, 5, 12);

        //plantMan.drawRadar(buffer, car);

        if (!openGL) {
             if (!fullscreen) {
                buffer.display(gFrame, leftBorderWidth, titleBarHeight);
             }
             else {
                Graphics g=bufferStrategy.getDrawGraphics();
                g.drawImage(buffer.getOutputBuffer(), 0, 0, null);
                bufferStrategy.show();
                g.dispose();
             }
        }
        else {
             buffer.displayGLOnly();
        }
    }

   private void keyAffected(KeyState state) {
        int code=state.getKeyCode();
        boolean event=state.getState();

        switch (code) {
            case (KeyEvent.VK_ESCAPE): {
                exit=event;
                break;
            }
            /*case (KeyEvent.VK_LEFT): {
                left=event;
                break;
            }
            case (KeyEvent.VK_RIGHT): {
                 right=event;
                 break;
            }
            case (KeyEvent.VK_UP): {
                 forward=event;
                 break;
            }
            case (KeyEvent.VK_SPACE): {
                 fire=event;
                 break;
            }
            case (KeyEvent.VK_DOWN): {
                 back=event;
                 break;
            }*/
            case (KeyEvent.VK_W): {
                 if (event) {
                     wireframe=!wireframe;
                 }
                 break;
            }
            case (KeyEvent.VK_X): {
                 if (event) {
                    switchMode=SWITCH_RENDERER;
                }
                break;
            }
        }
   }

   private class WindowEvents extends WindowAdapter {

        public void windowIconified(WindowEvent e) {
            isIdle=true;
        }

        public void windowDeiconified(WindowEvent e) {
            isIdle=false;
        }
    }

    private class Timer {

        private long ticks=0;
        private long granularity=0;

        public Timer(int granularity) {
            this.granularity=granularity;
        }

        public void start() {
            ticks=System.currentTimeMillis();
        }

        public void reset() {
            start();
        }

        public long getElapsedTicks() {
            long cur=System.currentTimeMillis();
            long l=cur-ticks;

            if (l>=granularity) {
               ticks=cur-(l%granularity);
               return l/granularity;
            }
         return 0;
      }
   }
}




Offline EgonOlsen

  • Administrator
  • quad
  • *****
  • Posts: 12295
    • View Profile
    • http://www.jpct.net
Re: Black screen
« Reply #1 on: May 18, 2009, 10:39:01 pm »
You are standing inside the cube in this case. And because of this, you are seeing its back faces only, which will be culled...so you see nothing at all. Try a smaller scaling value for the cube like 10.
After all, i don't think that the car example is good starting point for displaying a cube. Maybe the HelloWorld-example is more suitable... ???

Offline KOsmos

  • byte
  • *
  • Posts: 4
    • View Profile
Re: Black screen
« Reply #2 on: May 18, 2009, 11:03:47 pm »
Thank You for quick reply. It works!

I always skip 'hello world' programs when learning new languages or libraries in this case. I believe that creating my own game framework starting from HelloWorld would be difficult. In my opinion car example is a good point to start from. I don't want to reinvent double buffering or struggle with display options. I need a game framework so that I can put my own game logic to it. Thank You once again.