コード例 #1
0
  public void paintGL() {
    synchronized (PAINT_LOCK) {
      try {
        DisplaySystem.getDisplaySystem().setCurrentCanvas(this);

        if (updateInput) InputSystem.update();

        if (!impl.isSetup()) {
          impl.doSetup();

          if (DisplaySystem.getDisplaySystem().getMinSamples() != 0
              && GLContext.getCapabilities().GL_ARB_multisample) {
            GL11.glEnable(ARBMultisample.GL_MULTISAMPLE_ARB);
          }
        }

        GameTaskQueueManager.getManager().getQueue(GameTaskQueue.UPDATE).execute();

        impl.doUpdate();

        GameTaskQueueManager.getManager().getQueue(GameTaskQueue.RENDER).execute();

        impl.doRender();

        swapBuffers();
      } catch (LWJGLException e) {
        logger.log(Level.SEVERE, "Exception in paintGL()", e);
      }
    }
  }
コード例 #2
0
  /**
   * <code>verifyAndSaveCurrentSelection</code> first verifies that the display mode is valid for
   * this system, and then saves the current selection as a properties.cfg file.
   *
   * @return if the selection is valid
   */
  private boolean verifyAndSaveCurrentSelection() {
    String display = (String) displayResCombo.getSelectedItem();

    int width = Integer.parseInt(display.substring(0, display.indexOf(" x ")));
    display = display.substring(display.indexOf(" x ") + 3);
    int height = Integer.parseInt(display);

    String depthString = (String) colorDepthCombo.getSelectedItem();
    int depth = Integer.parseInt(depthString.substring(0, depthString.indexOf(' ')));

    String freqString = (String) displayFreqCombo.getSelectedItem();
    int freq = Integer.parseInt(freqString.substring(0, freqString.indexOf(' ')));

    boolean fullscreen = fullscreenBox.isSelected();
    if (!fullscreen) {
      // query the current bit depth of the desktop
      int curDepth =
          GraphicsEnvironment.getLocalGraphicsEnvironment()
              .getDefaultScreenDevice()
              .getDisplayMode()
              .getBitDepth();
      if (depth > curDepth) {
        showError(
            this,
            "Cannot choose a higher bit depth in windowed "
                + "mode than your current desktop bit depth");
        return false;
      }
    }

    String renderer = (String) rendererCombo.getSelectedItem();

    // test valid display mode
    DisplaySystem disp = DisplaySystem.getDisplaySystem(renderer);
    boolean valid = (disp != null) ? disp.isValidDisplayMode(width, height, depth, freq) : false;

    if (valid) {
      // use the GameSettings class to save it.
      source.setWidth(width);
      source.setHeight(height);
      source.setDepth(depth);
      source.setFrequency(freq);
      source.setFullscreen(fullscreen);
      source.setRenderer(renderer);
      try {
        source.save();
      } catch (IOException ioe) {
        logger.log(Level.WARNING, "Failed to save setting changes", ioe);
      }
    } else
      showError(
          this,
          "Your monitor claims to not support the display mode you've selected.\n"
              + "The combination of bit depth and refresh rate is not supported.");

    return valid;
  }
コード例 #3
0
ファイル: MainGameState.java プロジェクト: toloober/jme-demos
  /** render the scene, draw bounds or physics if needed. */
  @Override
  public void render(float tpf) {
    super.render(tpf);
    if (showPhysics) {
      PhysicsDebugger.drawPhysics(
          getPhysicsSpace(), DisplaySystem.getDisplaySystem().getRenderer());
    }

    if (showBounds) {
      Debugger.drawBounds(getRootNode(), DisplaySystem.getDisplaySystem().getRenderer());
    }
  }
コード例 #4
0
ファイル: TrailManager.java プロジェクト: toloober/jme-demos
 public void update(float tpf) {
   for (Map.Entry<Spatial, TrailMesh> t : trails.entrySet()) {
     t.getKey().updateWorldVectors();
     t.getValue().setTrailFront(t.getKey().getWorldTranslation(), 30, tpf);
     t.getValue().update(DisplaySystem.getDisplaySystem().getRenderer().getCamera().getLocation());
   }
 }
コード例 #5
0
ファイル: TrailManager.java プロジェクト: toloober/jme-demos
  private TrailManager(final Node root) {
    this.root = root;

    trails = new HashMap<Spatial, TrailMesh>();

    Renderer r = DisplaySystem.getDisplaySystem().getRenderer();
    ts = r.createTextureState();
    ts.setEnabled(true);
    Texture t1 =
        TextureManager.loadTexture(
            ResourceLocatorTool.locateResource(ResourceLocatorTool.TYPE_TEXTURE, "trail_y1.png"),
            Texture.MinificationFilter.Trilinear,
            Texture.MagnificationFilter.Bilinear);
    ts.setTexture(t1);

    bs = r.createBlendState();
    bs.setBlendEnabled(true);
    bs.setSourceFunction(BlendState.SourceFunction.SourceAlpha);
    bs.setDestinationFunction(BlendState.DestinationFunction.One);
    bs.setTestEnabled(true);

    zs = r.createZBufferState();
    zs.setWritable(false);

    cs = r.createCullState();
    cs.setCullFace(CullState.Face.None);
    cs.setEnabled(true);
  }
コード例 #6
0
  /** Process and setup the <code>TextureState</code> and texture UV buffer. */
  private void processTexture() {
    FloatBuffer textureBuffer = BufferUtils.createVector2Buffer(this.vertices.length);
    float maxU = 1;
    float maxV = 1;
    float minU = 0;
    float minV = 0;
    int index = 0;
    for (IVertex vertex : this.vertices) {
      BufferUtils.setInBuffer(vertex.getTextureCoords(), textureBuffer, index);
      if (vertex.getTextureCoords().x > maxU) maxU = vertex.getTextureCoords().x;
      else if (vertex.getTextureCoords().x < minU) minU = vertex.getTextureCoords().x;
      if (vertex.getTextureCoords().y > maxV) maxV = vertex.getTextureCoords().y;
      else if (vertex.getTextureCoords().y < minV) minV = vertex.getTextureCoords().y;
      index++;
    }
    this.setTextureCoords(new TexCoords(textureBuffer));

    // Get texture state.
    TextureState state = (TextureState) this.getRenderState(StateType.Texture);
    if (state == null) {
      state = DisplaySystem.getDisplaySystem().getRenderer().createTextureState();
      this.setRenderState(state);
    }
    // Set color map.
    if (this.color != null) state.setTexture(this.loadTexture(this.color, maxU, maxV), 0);
    // Set normal map.
    if (this.normal != null) state.setTexture(this.loadTexture(this.normal, maxU, maxV), 1);
    // Set specular map.
    if (this.specular != null) state.setTexture(this.loadTexture(this.specular, maxU, maxV), 2);
  }
コード例 #7
0
  public UITextureContainer(String name, int sizeX, int sizeY, int posX, int posY, int zOrder) {

    super(name, posX, posY, zOrder, sizeX, sizeY);

    visibleQuad = new Quad(name + "UIQuad", sizeX, sizeY);
    visibleQuad.setRenderQueueMode(Renderer.QUEUE_ORTHO);
    visibleQuad.setZOrder(zPos);

    visibleQuad.setLocalTranslation((sizeX / 2.0f), (sizeY / 2.0f), 0);

    if (as == null) {
      as =
          DisplaySystem.getDisplaySystem()
              .getRenderer()
              .createBlendState(); // FIXME: Remove the hidden OpenGL call.
      as.setBlendEnabled(true);
      as.setSourceFunction(BlendState.SourceFunction.SourceAlpha);
      as.setDestinationFunction(BlendState.DestinationFunction.OneMinusSourceAlpha);
      as.setTestEnabled(true);
      as.setTestFunction(BlendState.TestFunction.GreaterThan);
    }
    visibleQuad.setRenderState(as);
    visibleQuad.updateRenderState();
    getDisplayNode().attachChild(visibleQuad);
  }
コード例 #8
0
  @Override
  protected void initGL() {

    if (glInitialized) {
      return;
    }
    glInitialized = true;

    try {
      LWJGLDisplaySystem display = (LWJGLDisplaySystem) DisplaySystem.getDisplaySystem();
      display.switchContext(this);

      // Complete canvas configuration.
      Dimension size = this.getSize();
      display.initForCanvas(size.width, size.height);

      impl.doSetup();

      if (display.getMinSamples() != 0 && GLContext.getCapabilities().GL_ARB_multisample) {
        GL11.glEnable(ARBMultisample.GL_MULTISAMPLE_ARB);
      }
    } catch (Exception e) {
      logger.log(Level.SEVERE, "Exception in initGL()", e);
    }
  }
コード例 #9
0
  public static void setTranslucent(Spatial spatial) {
    MaterialState rs = (MaterialState) doRemoveRenderState(spatial, StateType.Material);
    if (rs != null) {
      materials.put(spatial.getName(), rs);

      MaterialState newState = DisplaySystem.getDisplaySystem().getRenderer().createMaterialState();

      ColorRGBA ambient = rs.getAmbient();
      ambient.a = .5f;
      ColorRGBA diffuse = rs.getDiffuse();
      diffuse.a = .5f;
      ColorRGBA emissive = rs.getEmissive();
      emissive.a = .5f;
      ColorRGBA specular = rs.getSpecular();
      specular.a = .5f;

      newState.setAmbient(ambient);
      newState.setColorMaterial(rs.getColorMaterial());
      newState.setDiffuse(diffuse);
      newState.setEmissive(emissive);
      newState.setMaterialFace(rs.getMaterialFace());
      newState.setShininess(rs.getShininess());
      newState.setSpecular(specular);
    }
    spatial.updateRenderState();
    if (spatial instanceof Node && ((Node) spatial).getChildren() != null) {
      for (int i = 0; i < ((Node) spatial).getChildren().size(); i++) {
        colorStripper(((Node) spatial).getChildren().get(i));
      }
    }
  }
コード例 #10
0
 /** Must be constructed in the GL thread. */
 public AbstractStatGrapher(int width, int height) {
   this.gWidth = width;
   this.gHeight = height;
   // prepare our TextureRenderer
   texRenderer =
       DisplaySystem.getDisplaySystem().createTextureRenderer(width, height, Target.Texture2D);
   texRenderer.setBackgroundColor(ColorRGBA.black.clone());
 }
コード例 #11
0
 private void createFog() {
   FogState fs = display.getRenderer().createFogState();
   fs.setDensity(0.5f);
   fs.setEnabled(true);
   fs.setColor(new ColorRGBA(0.8f, 0.8f, 0.8f, 0.8f));
   fs.setStart(50);
   fs.setEnd(visibilityRadius);
   fs.setDensityFunction(FogState.DF_LINEAR);
   fs.setApplyFunction(FogState.AF_PER_VERTEX);
   root.setRenderState(fs);
 }
コード例 #12
0
  public void frameUpdate(float timePerFrame) {
    // TODO Auto-generated method stub
    // TODO Play Frame, when in the right time => Sync-Playback-rate
    /*
     *
    // Put A Frame according to its Framerate
     * TODO: Declare    private long controller;
      						private long frameWait;
      						private long starttime;
      						private int iteration;

      			 Initialize starttime = System.currentTimeMillis();
    					controller = System.currentTimeMillis();
    					frameWait = 1000 / perf.getFramerate();
    					iteration = 0;

    This one into the update function:

    if (System.currentTimeMillis() >= (controller + frameWait)){
    		controller = System.currentTimeMillis();
    		System.out.println("There you go: " + System.currentTimeMillis());
    		drawFrame();
    		iteration++;
    }

    if (System.currentTimeMillis() > (starttime + (iteration*frameWait)+frameWait)) {
    	// skip Frame

    	iteration += 2;
    	System.out.println("Look ma, no hands: " + iteration);
    }
     */
    // timer.getTimePerFrame();

    if (oggDecoder.isReady()) {
      oggDecoder.readBody();
      TextureManager.releaseTexture(texture.getTextureKey());

      texture =
          TextureManager.loadTexture(
              Toolkit.getDefaultToolkit().createImage(oggDecoder.getYUVBuffer()),
              MinificationFilter.BilinearNearestMipMap,
              MagnificationFilter.Bilinear,
              true);
      if (texture != null) {
        if (textureState != null)
          textureState = DisplaySystem.getDisplaySystem().getRenderer().createTextureState();
        textureState.setTexture(texture);
        quad.setRenderState(textureState);
        quad.updateRenderState();
      }
    }
  }
コード例 #13
0
ファイル: BattleState.java プロジェクト: snowgit/snowman
 /**
  * Initialize a chase camera with the given dynamic view as target.
  *
  * @param view The target <code>DynamicView</code> instance.
  */
 public void initializeCameraHandler(DynamicView view) {
   view.updateGeometricState(0, false);
   this.cameraHandler =
       new SnowmanCameraHandler(
           DisplaySystem.getDisplaySystem().getRenderer().getCamera(), view, this.game);
   Vector3f targetOffset = new Vector3f(0, 0, 0);
   targetOffset.setY(((BoundingBox) view.getWorldBound()).yExtent * 1.5f);
   this.cameraHandler.setTargetOffset(targetOffset);
   Vector3f dir = view.getLocalRotation().mult(new Vector3f(0, 0, -1));
   Vector3f store = new Vector3f();
   this.cameraHandler.setAzimuth(FastMath.cartesianToSpherical(dir, store).y);
 }
コード例 #14
0
  public static void warmup() {
    DisplaySystem display = DisplaySystem.getDisplaySystem();
    bs = display.getRenderer().createBlendState();
    bs.setBlendEnabled(true);
    bs.setSourceFunction(SourceFunction.SourceAlpha);
    bs.setDestinationFunction(DestinationFunction.One);
    bs.setTestEnabled(true);
    bs.setTestFunction(TestFunction.GreaterThan);

    ts = display.getRenderer().createTextureState();
    ts.setTexture(
        TextureManager.loadTexture(
            ExplosionFactory.class
                .getClassLoader()
                .getResource("jmetest/data/texture/flaresmall.jpg")));

    zstate = display.getRenderer().createZBufferState();
    zstate.setEnabled(false);

    for (int i = 0; i < 3; i++) createExplosion();
    for (int i = 0; i < 5; i++) createSmallExplosion();
  }
  public void apply() {
    if (isSupported()) {
      RenderContext context = DisplaySystem.getDisplaySystem().getCurrentContext();
      FragmentProgramStateRecord record =
          (FragmentProgramStateRecord) context.getStateRecord(RS_FRAGMENT_PROGRAM);

      context.currentStates[RS_FRAGMENT_PROGRAM] = this;

      if (!record.isValid() || record.getReference() != this) {
        record.setReference(this);
        if (isEnabled()) {
          // Fragment program not yet loaded
          if (programID == -1)
            if (program != null) create();
            else return;

          GL11.glEnable(ARBFragmentProgram.GL_FRAGMENT_PROGRAM_ARB);
          ARBProgram.glBindProgramARB(ARBFragmentProgram.GL_FRAGMENT_PROGRAM_ARB, programID);

          // load environmental parameters...
          // TODO: Reevaluate how this is done.
          /*
           * for (int i = 0; i < envparameters.length; i++) if
           * (envparameters[i] != null)
           * ARBFragmentProgram.glProgramEnvParameter4fARB(
           * ARBFragmentProgram.GL_FRAGMENT_PROGRAM_ARB, i,
           * envparameters[i][0], envparameters[i][1],
           * envparameters[i][2], envparameters[i][3]);
           */

          // load local parameters...
          if (usingParameters) // No sense checking array if we are sure
            // no parameters are used
            for (int i = 0; i < parameters.length; i++)
              if (parameters[i] != null)
                ARBProgram.glProgramLocalParameter4fARB(
                    ARBFragmentProgram.GL_FRAGMENT_PROGRAM_ARB,
                    i,
                    parameters[i][0],
                    parameters[i][1],
                    parameters[i][2],
                    parameters[i][3]);

        } else {
          GL11.glDisable(ARBFragmentProgram.GL_FRAGMENT_PROGRAM_ARB);
        }
      }

      if (!record.isValid()) record.validate();
    }
  }
コード例 #16
0
 private void createSky() {
   detachChildNamed("Skydome");
   float skyRadius = visibilityRadius * 1.1f;
   skydome = new Dome("Skydome", 5, 24, skyRadius);
   skyHeightOffset = skyRadius / 2;
   skydome.setModelBound(new BoundingSphere());
   skydome.updateModelBound();
   LightState lightState = display.getRenderer().createLightState();
   lightState.setEnabled(true);
   // lightState.setTwoSidedLighting(true);
   lightState.setGlobalAmbient(ColorRGBA.white);
   skydome.setRenderState(lightState);
   skydome.setLightCombineMode(LightState.REPLACE);
   Texture domeTexture =
       TextureManager.loadTexture(
           "../MBWSClient/data/images/wolken.jpg", Texture.MM_LINEAR, Texture.FM_LINEAR);
   TextureState ts = display.getRenderer().createTextureState();
   ts.setTexture(domeTexture);
   skydome.setRenderState(ts);
   // skydome.setTextureCombineMode(TextureState.REPLACE);
   attachChild(skydome);
   updateRenderState();
 }
コード例 #17
0
 /**
  * Applies color to a Spatial in the form of a <code>MaterialState</code>.
  *
  * @param spatial
  * @param diffuseColor
  * @param ambientColor
  * @see MaterialState
  */
 public static MaterialState applyColor(
     Spatial spatial, ColorRGBA diffuseColor, ColorRGBA ambientColor) {
   colorStripper(spatial);
   MaterialState targetMaterial =
       DisplaySystem.getDisplaySystem().getRenderer().createMaterialState();
   targetMaterial.setDiffuse(diffuseColor);
   targetMaterial.setAmbient(ambientColor);
   spatial.setRenderState(targetMaterial);
   spatial.updateRenderState();
   if (workingState != null) {
     MaterialState ms = (MaterialState) workingState;
     workingState = null;
     return ms;
   } else return null;
 }
コード例 #18
0
  /*
   * (non-Javadoc)
   *
   * @see org.rifidi.designer.entities.Entity#loaded()
   */
  @Override
  public void loaded() {
    if (msStopped == null) {
      msStopped = DisplaySystem.getDisplaySystem().getRenderer().createMaterialState();
      msStopped.setDiffuse(new ColorRGBA(1, 0, 0, .5f));
      msStopped.setEmissive(new ColorRGBA(1, 0, 0, .3f));
      msStopped.setShininess(1);
      msStopped.setSpecular(new ColorRGBA(1, 0, 0, .3f));
    }
    if (as == null) {
      as = DisplaySystem.getDisplaySystem().getRenderer().createAlphaState();
      as.setBlendEnabled(true);
      as.setSrcFunction(AlphaState.SB_SRC_ALPHA);
      as.setDstFunction(AlphaState.DB_ONE);
      as.setEnabled(true);
    }

    getNode().clearRenderState(RenderState.RS_ALPHA);
    getNode().clearRenderState(RenderState.RS_MATERIAL);
    getNode().setRenderState(as);
    getNode().updateRenderState();
    ((PhysicsNode) getNode()).setMaterial(Material.GHOST);
    if (msStarted == null) {
      msStarted = DisplaySystem.getDisplaySystem().getRenderer().createMaterialState();
      msStarted.setDiffuse(new ColorRGBA(0, 1, 0, .5f));
      msStarted.setEmissive(new ColorRGBA(0, 1, 0, .3f));
      msStarted.setShininess(1);
      msStarted.setSpecular(new ColorRGBA(0, 1, 0, .3f));
    }
    if (running) {
      turnOn();
    } else {
      turnOff();
    }
    fieldService.registerField(this);
  }
コード例 #19
0
  /** Reposition the camera if any motion keys are held down. */
  public void performCameraMotion() {

    float keyspeed = 0.5f;
    Camera cam = DisplaySystem.getDisplaySystem().getRenderer().getCamera();
    if (updownleftright[2]) {
      cam.setLocation(cam.getLocation().add(new Vector3f(-keyspeed, 0, 0)));
    }
    if (updownleftright[3]) {
      cam.setLocation(cam.getLocation().add(new Vector3f(keyspeed, 0, 0)));
    }
    if (updownleftright[0]) {
      cam.setLocation(cam.getLocation().add(new Vector3f(0, 0, -keyspeed)));
    }
    if (updownleftright[1]) {
      cam.setLocation(cam.getLocation().add(new Vector3f(0, 0, keyspeed)));
    }
  }
コード例 #20
0
ファイル: MainGameState.java プロジェクト: toloober/jme-demos
  /** create some light sources to illuminate the scene. */
  private void setupLight() {
    LightState ls = DisplaySystem.getDisplaySystem().getRenderer().createLightState();

    DirectionalLight dr1 = new DirectionalLight();
    dr1.setEnabled(true);
    dr1.setAmbient(new ColorRGBA(0, 0, 0, 0.5f));
    dr1.setDiffuse(ColorRGBA.white.clone());
    dr1.setDirection(new Vector3f(-0.2f, -0.3f, -0.4f).normalizeLocal());
    dr1.setShadowCaster(true);

    ls.attach(dr1);
    ls.setEnabled(true);
    ls.setGlobalAmbient(new ColorRGBA(0.6f, 0.6f, 0.6f, 1.0f));
    ls.setTwoSidedLighting(false);

    rootNode.setRenderState(ls);
  }
コード例 #21
0
  /**
   * <code>set</code> sets the OpenGL fog values if the state is enabled.
   *
   * @see com.jme.scene.state.RenderState#apply()
   */
  public void apply() {
    final GL gl = GLU.getCurrentGL();

    // ask for the current state record
    RenderContext<?> context = DisplaySystem.getDisplaySystem().getCurrentContext();
    FogStateRecord record = (FogStateRecord) context.getStateRecord(RS_FOG);
    context.currentStates[RS_FOG] = this;

    if (isEnabled()) {
      enableFog(true, record);

      if (record.isValid()) {
        if (record.fogStart != start) {
          gl.glFogf(GL.GL_FOG_START, start);
          record.fogStart = start;
        }
        if (record.fogEnd != end) {
          gl.glFogf(GL.GL_FOG_END, end);
          record.fogEnd = end;
        }
        if (record.density != density) {
          gl.glFogf(GL.GL_FOG_DENSITY, density);
          record.density = density;
        }
      } else {
        gl.glFogf(GL.GL_FOG_START, start);
        record.fogStart = start;
        gl.glFogf(GL.GL_FOG_END, end);
        record.fogEnd = end;
        gl.glFogf(GL.GL_FOG_DENSITY, density);
        record.density = density;
      }

      applyFogColor(getColor(), record);
      applyFogMode(densityFunction, record);
      applyFogHint(quality, record);
      applyFogSource(source, record);
    } else {
      enableFog(false, record);
    }

    if (!record.isValid()) record.validate();
  }
コード例 #22
0
ファイル: LWJGLFont.java プロジェクト: jmecn/learnJME3
  /**
   * <code>print</code> renders the specified string to a given (x,y) location. The x, y location is
   * in terms of screen coordinates. There are currently two sets of fonts supported: NORMAL and
   * ITALICS.
   *
   * @param r
   * @param x the x screen location to start the string render.
   * @param y the y screen location to start the string render.
   * @param text the String to render.
   * @param set the mode of font: NORMAL or ITALICS.
   */
  public void print(Renderer r, float x, float y, Vector3f scale, StringBuffer text, int set) {
    RendererRecord matRecord =
        (RendererRecord) DisplaySystem.getDisplaySystem().getCurrentContext().getRendererRecord();
    if (set > 1) {
      set = 1;
    } else if (set < 0) {
      set = 0;
    }

    boolean alreadyOrtho = r.isInOrthoMode();
    if (!alreadyOrtho) r.setOrtho();
    else {
      matRecord.switchMode(GL11.GL_MODELVIEW);
      GL11.glPushMatrix();
      GL11.glLoadIdentity();
    }
    GL11.glTranslatef(x, y, 0);
    GL11.glScalef(scale.x, scale.y, scale.z);
    GL11.glListBase(base - 32 + (128 * set));

    // Put the string into a "pointer"
    if (text.length() > scratch.capacity()) {
      scratch = BufferUtils.createByteBuffer(text.length());
    } else {
      scratch.clear();
    }

    int charLen = text.length();
    for (int z = 0; z < charLen; z++) scratch.put((byte) text.charAt(z));
    scratch.flip();
    matRecord.setCurrentColor(fontColor);
    // call the list for each letter in the string.
    GL11.glCallLists(scratch);
    // set color back to white
    matRecord.setCurrentColor(1, 1, 1, 1);

    if (!alreadyOrtho) {
      r.unsetOrtho();
    } else {
      matRecord.switchMode(GL11.GL_MODELVIEW);
      GL11.glPopMatrix();
    }
  }
コード例 #23
0
ファイル: MainGameState.java プロジェクト: toloober/jme-demos
  /** creates the floor and two walls standing on the floor. */
  private void createFloor(float width, float length) {
    Texture tex =
        TextureManager.loadTexture(
            ResourceLocatorTool.locateResource(ResourceLocatorTool.TYPE_TEXTURE, "floor.png"),
            false);
    tex.setScale(new Vector3f(10, 10, 10));
    tex.setWrap(WrapMode.Repeat);
    TextureState tsCarpet = DisplaySystem.getDisplaySystem().getRenderer().createTextureState();
    tsCarpet.setTexture(tex);

    StaticPhysicsNode floor = makeWall("floor", width, 0.5f, length, new Vector3f(0, -1, 0), null);
    floor.setRenderState(tsCarpet);
    rootNode.attachChild(floor);

    rootNode.attachChild(
        makeWall(
            "back wall", width / 2, 5, 1, new Vector3f(0, 5, -width / 2), MaterialType.GRANITE));
    rootNode.attachChild(
        makeWall(
            "left wall", 1, 5, width / 2, new Vector3f(-width / 2, 5, 0), MaterialType.GRANITE));
  }
コード例 #24
0
  private void createShape() {
    quad = new Quad("texturedQuad", Scale.fromMeter(25), Scale.fromMeter(25));
    // quad = new Box("", new Vector3f(), Scale.fromMeter(25), Scale.fromMeter(25),
    // Scale.fromMeter(25));

    // quad.setLocalTranslation(new Vector3f(0,0,-400));

    texture =
        TextureManager.loadTexture(
            "data/foliage/A_Bush_1.png",
            MinificationFilter.BilinearNearestMipMap,
            MagnificationFilter.Bilinear);

    if (texture != null) {
      textureState = DisplaySystem.getDisplaySystem().getRenderer().createTextureState();
      textureState.setTexture(texture);
      quad.setRenderState(textureState);
    }

    // rootNode.attachChild(quad);
  }
コード例 #25
0
ファイル: MainGameState.java プロジェクト: toloober/jme-demos
  /** Initializes the rootNodes RenderStates, initializes the Camera and */
  private void init() {
    // we attach transparent objects to this node, so it must be
    // rendered in the transparent bucket
    objectsNode.setRenderQueueMode(Renderer.QUEUE_TRANSPARENT);

    CullState cs = DisplaySystem.getDisplaySystem().getRenderer().createCullState();
    cs.setCullFace(Face.Back);
    cs.setEnabled(true);
    rootNode.setRenderState(cs);

    // create a first person controller to move the Camera with W,A,S,D and mouse look
    movementInput = new FirstPersonHandler(cam, 15.0f, 0.5f);
    // move the camera a bit backwards and up
    cam.setLocation(new Vector3f(2, 10, 15));

    // create a Physics update callback, to simulate basic wind force
    wind =
        new PhysicsWindCallback(
            SceneSettings.get().getWindVariation(), SceneSettings.get().getWindForce());
    getPhysicsSpace().addToUpdateCallbacks(wind);
  }
コード例 #26
0
  @Override
  protected void paintGL() {

    try {
      ((LWJGLDisplaySystem) DisplaySystem.getDisplaySystem()).switchContext(this);

      if (updateInput) {
        InputSystem.update();
      }

      GameTaskQueueManager.getManager().getQueue(GameTaskQueue.UPDATE).execute();

      impl.doUpdate();

      if (!drawWhenDirty || dirty) {
        GameTaskQueueManager.getManager().getQueue(GameTaskQueue.RENDER).execute();

        impl.doRender();

        swapBuffers();
        dirty = false;
      }
    } catch (LWJGLException e) {
      logger.log(Level.SEVERE, "Exception in paintGL()", e);
    }

    // sync
    if (syncRate > 0) {
      long sinceLast = System.nanoTime() - lastRender;
      if (sinceLast < syncNS) {
        try {
          Thread.sleep((Math.round((syncNS - sinceLast) / 1000000L)));
        } catch (InterruptedException e) {
        }
      }
      lastRender = System.nanoTime();
    }

    repaint();
  }
コード例 #27
0
  /**
   * Creates display, sets up camera, and binds keys. Called in BaseGame.start() directly after the
   * dialog box.
   *
   * @see AbstractGame#initSystem()
   */
  protected final void initSystem() {
    try {
      /** Get a DisplaySystem acording to the renderer selected in the startup box. */
      display = DisplaySystem.getDisplaySystem(settings.getRenderer());
      /** Create a window with the startup box's information. */
      display.createWindow(
          settings.getWidth(),
          settings.getHeight(),
          settings.getDepth(),
          settings.getFrequency(),
          settings.isFullscreen());
      /**
       * Create a camera specific to the DisplaySystem that works with the display's width and
       * height
       */
    } catch (JmeException e) {
      /** If the displaysystem can't be initialized correctly, exit instantly. */
      logger.log(Level.SEVERE, "Could not create displaySystem", e);
      System.exit(1);
    }

    /** Get a high resolution timer for FPS updates. */
    timer = Timer.getTimer();
  }
コード例 #28
0
 public static void applyWireframe(Spatial s) {
   WireframeState ws = DisplaySystem.getDisplaySystem().getRenderer().createWireframeState();
   colorStripper(s);
   doWireframeApplication(s, true, ws);
   s.updateRenderState();
 }
コード例 #29
0
 /**
  * <code>setUpRendererChooser</code> sets the list of available renderers. Data is obtained from
  * the <code>DisplaySystem</code> class. The renderer specified by GameSettings is used as the
  * default value.
  *
  * @return the list of renderers.
  */
 private JComboBox setUpRendererChooser() {
   String modes[] = DisplaySystem.getSystemProviderIdentifiers();
   JComboBox nameBox = new JComboBox(modes);
   nameBox.setSelectedItem(source.getRenderer());
   return nameBox;
 }
コード例 #30
0
ファイル: MainGameState.java プロジェクト: toloober/jme-demos
/**
 * The main GameState. Creates the Physics Playground.
 *
 * @author Christoph Luder
 */
public class MainGameState extends PhysicsGameState {
  /** reference to the camera */
  private Camera cam = DisplaySystem.getDisplaySystem().getRenderer().getCamera();
  /** we want to move the camera first person style */
  private FirstPersonHandler movementInput = null;
  /** InputHandler for the physics picker and basic command */
  private InputHandler input = new InputHandler();
  /** the static floor */
  private StaticPhysicsNode floor = null;
  /** The Node where newly created objects are attached to. */
  private Node objectsNode = null;

  /** should the physics debug view be rendereed */
  private boolean showPhysics = false;
  /** should the bounding boxes be rendered */
  private boolean showBounds = false;

  /** the physics picker */
  private PhysicsPicker picker = null;
  /** The physics Wind. */
  private PhysicsWindCallback wind = null;

  /** A Wall built with physics objects. */
  private Wall wall = null;
  /** a physics swing. */
  private Swing swing = null;
  /** a physics seesaw. */
  private Seesaw seesaw = null;

  /**
   * Constructs the MainGameState. Creates the scene and add the different objects to the
   * Scenegraph.
   *
   * @param name name of the GameState
   */
  public MainGameState(String name) {
    super(name);

    // the node where newly created objects get attached to
    objectsNode = new Node("object Node");
    rootNode.attachChild(objectsNode);

    // create the scene
    picker = new PhysicsPicker(input, rootNode, getPhysicsSpace(), true);
    picker.getInputHandler().setEnabled(false);

    init();
    setupInput();
    setupLight();

    // add a few objects to the scene
    ObjectFactory.createObjectFactory(getPhysicsSpace());

    createFloor(50, 50);
    createOuterWalls(75);

    wall =
        new Wall(
            getPhysicsSpace(),
            SceneSettings.get().getWallWidth(),
            SceneSettings.get().getWallHeigth(),
            SceneSettings.get().getWallElementSize());

    wall.setLocalTranslation(0, 0, -3);
    rootNode.attachChild(wall);

    seesaw = new Seesaw(getPhysicsSpace());
    seesaw.setLocalTranslation(-13, -1, 5);
    rootNode.attachChild(seesaw);

    //        swing = new Swing(getPhysicsSpace());
    //        swing.setLocalTranslation(15, 3f, 4);
    //        rootNode.attachChild(swing);

    rootNode.updateGeometricState(0, true);
    rootNode.updateRenderState();
  }

  /** creates the floor and two walls standing on the floor. */
  private void createFloor(float width, float length) {
    Texture tex =
        TextureManager.loadTexture(
            ResourceLocatorTool.locateResource(ResourceLocatorTool.TYPE_TEXTURE, "floor.png"),
            false);
    tex.setScale(new Vector3f(10, 10, 10));
    tex.setWrap(WrapMode.Repeat);
    TextureState tsCarpet = DisplaySystem.getDisplaySystem().getRenderer().createTextureState();
    tsCarpet.setTexture(tex);

    StaticPhysicsNode floor = makeWall("floor", width, 0.5f, length, new Vector3f(0, -1, 0), null);
    floor.setRenderState(tsCarpet);
    rootNode.attachChild(floor);

    rootNode.attachChild(
        makeWall(
            "back wall", width / 2, 5, 1, new Vector3f(0, 5, -width / 2), MaterialType.GRANITE));
    rootNode.attachChild(
        makeWall(
            "left wall", 1, 5, width / 2, new Vector3f(-width / 2, 5, 0), MaterialType.GRANITE));
  }

  /**
   * create the outer boundaries of the scene. 6 walls prevent object from falling endlessly thourgh
   * the world.
   */
  public void createOuterWalls(float size) {
    rootNode.attachChild(
        makeWall("top", size, 1, size, new Vector3f(0, size, 0), MaterialType.GLASS));
    rootNode.attachChild(
        makeWall("bottom", size, 1, size, new Vector3f(0, -size / 2, 0), MaterialType.GLASS));
    rootNode.attachChild(
        makeWall("left", 1, size, size, new Vector3f(-size, 0, 0), MaterialType.GLASS));
    rootNode.attachChild(
        makeWall("right", 1, size, size, new Vector3f(size, 0, 0), MaterialType.GLASS));
    rootNode.attachChild(
        makeWall("back", size, size, 1, new Vector3f(0, 0, -size), MaterialType.GLASS));
    rootNode.attachChild(
        makeWall("front", size, size, 1, new Vector3f(0, 0, size), MaterialType.GLASS));
  }

  /**
   * a simple helper method to create a static physic wall.
   *
   * @param name node name
   * @param x x extent
   * @param y y extent
   * @param z z extent
   * @param loc location
   * @param type type of material/texture
   * @return staticPhysicNode with the attached box
   */
  public StaticPhysicsNode makeWall(
      String name, float x, float y, float z, Vector3f loc, MaterialType type) {
    Box box = new Box(name, new Vector3f(), x, y, z);
    box.setModelBound(new BoundingBox());
    box.updateModelBound();
    if (type != null) ObjectFactory.get().applyRenderStates(box, type);
    StaticPhysicsNode physicWall = getPhysicsSpace().createStaticNode();
    physicWall.attachChild(box);
    physicWall.setLocalTranslation(loc);
    physicWall.generatePhysicsGeometry();
    return physicWall;
  }

  /** Initializes the rootNodes RenderStates, initializes the Camera and */
  private void init() {
    // we attach transparent objects to this node, so it must be
    // rendered in the transparent bucket
    objectsNode.setRenderQueueMode(Renderer.QUEUE_TRANSPARENT);

    CullState cs = DisplaySystem.getDisplaySystem().getRenderer().createCullState();
    cs.setCullFace(Face.Back);
    cs.setEnabled(true);
    rootNode.setRenderState(cs);

    // create a first person controller to move the Camera with W,A,S,D and mouse look
    movementInput = new FirstPersonHandler(cam, 15.0f, 0.5f);
    // move the camera a bit backwards and up
    cam.setLocation(new Vector3f(2, 10, 15));

    // create a Physics update callback, to simulate basic wind force
    wind =
        new PhysicsWindCallback(
            SceneSettings.get().getWindVariation(), SceneSettings.get().getWindForce());
    getPhysicsSpace().addToUpdateCallbacks(wind);
  }

  /**
   * set up some key actions. - SPACE to release a new object, - ESC to quit the game - TAB to
   * enable / disable the GUI GameState
   */
  private void setupInput() {
    input.addAction(
        new InputAction() {
          public void performAction(InputActionEvent evt) {
            if (evt.getTriggerPressed()) {
              PhysicsGame.get().getGame().finish();
            }
          }
        },
        InputHandler.DEVICE_KEYBOARD,
        KeyInput.KEY_ESCAPE,
        InputHandler.AXIS_NONE,
        false);

    input.addAction(
        new InputAction() {
          public void performAction(InputActionEvent evt) {
            if (evt.getTriggerPressed()) {
              spawnObject();
            }
          }
        },
        InputHandler.DEVICE_KEYBOARD,
        KeyInput.KEY_SPACE,
        InputHandler.AXIS_NONE,
        false);

    input.addAction(
        new InputAction() {
          public void performAction(InputActionEvent evt) {
            if (evt.getTriggerPressed()) {
              if (GameStateManager.getInstance().getChild("gui").isActive()) {
                movementInput.setEnabled(true);
                GameStateManager.getInstance().getChild("gui").setActive(false);
              } else {
                movementInput.setEnabled(false);
                GameStateManager.getInstance().getChild("gui").setActive(true);
              }
            }
          }
        },
        InputHandler.DEVICE_KEYBOARD,
        KeyInput.KEY_TAB,
        InputHandler.AXIS_NONE,
        false);
  }

  /** create some light sources to illuminate the scene. */
  private void setupLight() {
    LightState ls = DisplaySystem.getDisplaySystem().getRenderer().createLightState();

    DirectionalLight dr1 = new DirectionalLight();
    dr1.setEnabled(true);
    dr1.setAmbient(new ColorRGBA(0, 0, 0, 0.5f));
    dr1.setDiffuse(ColorRGBA.white.clone());
    dr1.setDirection(new Vector3f(-0.2f, -0.3f, -0.4f).normalizeLocal());
    dr1.setShadowCaster(true);

    ls.attach(dr1);
    ls.setEnabled(true);
    ls.setGlobalAmbient(new ColorRGBA(0.6f, 0.6f, 0.6f, 1.0f));
    ls.setTwoSidedLighting(false);

    rootNode.setRenderState(ls);
  }

  /**
   * create a new Object. The ObjectFactory create an object depending on what we selected in the
   * GUI GameState. - the new Object gets attached to the objectNode, - is moved a bit in front of
   * the camera - and finally we add force to it.
   */
  private void spawnObject() {
    DynamicPhysicsNode node = ObjectFactory.get().createObject();
    node.setName("physics node");
    node.getLocalTranslation().set(cam.getLocation());
    node.getLocalTranslation()
        .addLocal(cam.getDirection().mult(new Vector3f(2, 2, 2).add(node.getLocalScale())));
    node.addForce(cam.getDirection().mult(ObjectFactory.get().getForce()));
    objectsNode.attachChild(node);
    objectsNode.updateRenderState();
    objectsNode.updateGeometricState(0, false);
  }

  /**
   * we update the input controllers and some physic object if needed, then we update the physics
   * world and call updateGeometricstate() which happens in super.update().
   */
  @Override
  public void update(float tpf) {
    input.update(tpf);
    //		swing.update();

    if (movementInput.isEnabled()) {
      movementInput.update(tpf);
    }
    super.update(tpf);
  }

  /** render the scene, draw bounds or physics if needed. */
  @Override
  public void render(float tpf) {
    super.render(tpf);
    if (showPhysics) {
      PhysicsDebugger.drawPhysics(
          getPhysicsSpace(), DisplaySystem.getDisplaySystem().getRenderer());
    }

    if (showBounds) {
      Debugger.drawBounds(getRootNode(), DisplaySystem.getDisplaySystem().getRenderer());
    }
  }

  public Wall getWall() {
    return wall;
  }

  public StaticPhysicsNode getFloor() {
    return floor;
  }

  public Node getBallNode() {
    return objectsNode;
  }

  public boolean isShowPhysics() {
    return showPhysics;
  }

  public void setShowPhysics(boolean showPhysics) {
    this.showPhysics = showPhysics;
  }

  public void setWall(Wall wall) {
    this.wall = wall;
  }

  public PhysicsPicker getPicker() {
    return picker;
  }

  public Swing getSwing() {
    return swing;
  }

  public Seesaw getSeesaw() {
    return seesaw;
  }

  public PhysicsWindCallback getWind() {
    return wind;
  }

  public void setShowBounds(boolean showBounds) {
    this.showBounds = showBounds;
  }
}