@Override
  public void render(RenderManager rm) {
    if (!isEnabled() || listener == null) {
      return;
    }

    Vector3f lastLocation = listener.getLocation();
    Vector3f currentLocation = camera.getLocation();
    Vector3f velocity = listener.getVelocity();

    if (!lastLocation.equals(currentLocation)) {
      velocity.set(currentLocation).subtractLocal(lastLocation);
      velocity.multLocal(1f / lastTpf);
      listener.setLocation(currentLocation);
      listener.setVelocity(velocity);
    } else if (!velocity.equals(Vector3f.ZERO)) {
      listener.setVelocity(Vector3f.ZERO);
    }

    Quaternion lastRotation = listener.getRotation();
    Quaternion currentRotation = camera.getRotation();
    if (!lastRotation.equals(currentRotation)) {
      listener.setRotation(currentRotation);
    }
  }
 public void setCameras(List<Camera> cameras) {
   this.cameras = cameras;
   cameraLocations.clear();
   for (Camera c : cameras) {
     cameraLocations.add(c.getLocation());
   }
 }
예제 #3
0
  /**
   * renders a filter on a fullscreen quad
   *
   * @param r
   * @param buff
   * @param mat
   */
  private void renderProcessing(Renderer r, FrameBuffer buff, Material mat) {
    if (buff == outputBuffer) {
      fsQuad.setWidth(width);
      fsQuad.setHeight(height);
      filterCam.resize(originalWidth, originalHeight, true);
      fsQuad.setPosition(left * originalWidth, bottom * originalHeight);
    } else {
      fsQuad.setWidth(buff.getWidth());
      fsQuad.setHeight(buff.getHeight());
      filterCam.resize(buff.getWidth(), buff.getHeight(), true);
      fsQuad.setPosition(0, 0);
    }

    if (mat.getAdditionalRenderState().isDepthWrite()) {
      mat.getAdditionalRenderState().setDepthTest(false);
      mat.getAdditionalRenderState().setDepthWrite(false);
    }

    fsQuad.setMaterial(mat);
    fsQuad.updateGeometricState();

    renderManager.setCamera(filterCam, true);
    r.setFrameBuffer(buff);
    r.clearBuffers(false, true, true);
    renderManager.renderGeometry(fsQuad);
  }
예제 #4
0
  /**
   * <code>checkCulling</code> checks the spatial with the camera to see if it should be culled.
   *
   * <p>This method is called by the renderer. Usually it should not be called directly.
   *
   * @param cam The camera to check against.
   * @return true if inside or intersecting camera frustum (should be rendered), false if outside.
   */
  public boolean checkCulling(Camera cam) {
    if (refreshFlags != 0) {
      throw new IllegalStateException(
          "Scene graph is not properly updated for rendering.\n"
              + "State was changed after rootNode.updateGeometricState() call. \n"
              + "Make sure you do not modify the scene from another thread!\n"
              + "Problem spatial name: "
              + getName());
    }

    CullHint cm = getCullHint();
    assert cm != CullHint.Inherit;
    if (cm == Spatial.CullHint.Always) {
      setLastFrustumIntersection(Camera.FrustumIntersect.Outside);
      return false;
    } else if (cm == Spatial.CullHint.Never) {
      setLastFrustumIntersection(Camera.FrustumIntersect.Intersects);
      return true;
    }

    // check to see if we can cull this node
    frustrumIntersects =
        (parent != null ? parent.frustrumIntersects : Camera.FrustumIntersect.Intersects);

    if (frustrumIntersects == Camera.FrustumIntersect.Intersects) {
      if (getQueueBucket() == Bucket.Gui) {
        return cam.containsGui(getWorldBound());
      } else {
        frustrumIntersects = cam.contains(getWorldBound());
      }
    }

    return frustrumIntersects != Camera.FrustumIntersect.Outside;
  }
 /**
  * This computes the "C" value in the geomipmapping paper. See section "2.3.1.2 Pre-calculating d"
  *
  * @param cam
  * @param pixelLimit
  * @return
  */
 private float getCameraConstant(Camera cam, float pixelLimit) {
   float n = cam.getFrustumNear();
   float t = FastMath.abs(cam.getFrustumTop());
   float A = n / t;
   float v_res = cam.getHeight();
   float T = (2f * pixelLimit) / v_res;
   return A / T;
 }
예제 #6
0
 /**
  * Populates the outputGeometryList with the geometry of the inputGeomtryList that are in the
  * frustum of the given camera
  *
  * @param inputGeometryList The list containing all geometry to check against the camera frustum
  * @param camera the camera to check geometries against
  * @param outputGeometryList the list of all geometries that are in the camera frustum
  */
 public static void getGeometriesInCamFrustum(
     GeometryList inputGeometryList, Camera camera, GeometryList outputGeometryList) {
   for (int i = 0; i < inputGeometryList.size(); i++) {
     Geometry g = inputGeometryList.get(i);
     int planeState = camera.getPlaneState();
     camera.setPlaneState(0);
     if (camera.contains(g.getWorldBound()) != Camera.FrustumIntersect.Outside) {
       outputGeometryList.add(g);
     }
     camera.setPlaneState(planeState);
   }
 }
예제 #7
0
  public void generateRenderSet(
      Geometry[] globalGeomList,
      Set<Geometry> renderSet,
      Camera cam,
      BoundingBox parentBox,
      boolean isRoot) {
    tempBox.setCenter(parentBox.getCenter());
    tempBox.setXExtent(parentBox.getXExtent());
    tempBox.setYExtent(parentBox.getYExtent());
    tempBox.setZExtent(parentBox.getZExtent());

    if (!isRoot) {
      findChildBound(tempBox, getSide());
    }

    tempBox.setCheckPlane(0);
    cam.setPlaneState(0);
    Camera.FrustumIntersect result = cam.contains(tempBox);
    if (result != Camera.FrustumIntersect.Outside) {
      if (length != 0) {
        int start = getOffset();
        int end = start + length;
        for (int i = start; i < end; i++) {
          renderSet.add(globalGeomList[i]);
        }
      }

      if (child == null) return;

      FastOctnode node = child;

      float x = tempBox.getCenter().x;
      float y = tempBox.getCenter().y;
      float z = tempBox.getCenter().z;
      float ext = tempBox.getXExtent();

      while (node != null) {
        if (result == Camera.FrustumIntersect.Inside) {
          node.generateRenderSetNoCheck(globalGeomList, renderSet, cam);
        } else {
          node.generateRenderSet(globalGeomList, renderSet, cam, tempBox, false);
        }

        tempBox.getCenter().set(x, y, z);
        tempBox.setXExtent(ext);
        tempBox.setYExtent(ext);
        tempBox.setZExtent(ext);

        node = node.next;
      }
    }
  }
  // debug only : displays maps
  protected void displayMap(Renderer r, Picture pic, int left) {
    Camera cam = vp.getCamera();
    rm.setCamera(cam, true);
    int h = cam.getHeight();

    pic.setPosition(left, h / 20f);

    pic.setWidth(128);
    pic.setHeight(128);
    pic.updateGeometricState();
    rm.renderGeometry(pic);
    rm.setCamera(cam, false);
  }
예제 #9
0
 // debug only : displays depth shadow maps
 protected void displayShadowMap(Renderer r) {
   Camera cam = viewPort.getCamera();
   renderManager.setCamera(cam, true);
   int h = cam.getHeight();
   for (int i = 0; i < dispPic.length; i++) {
     dispPic[i].setPosition((128 * i) + (150 + 64 * (i + 1)), h / 20f);
     dispPic[i].setWidth(128);
     dispPic[i].setHeight(128);
     dispPic[i].updateGeometricState();
     renderManager.renderGeometry(dispPic[i]);
   }
   renderManager.setCamera(cam, false);
 }
예제 #10
0
  private void refreshFont() {
    Camera cam = IsoCamera.getInstance().getCam();

    Vector3f start = from.getPlanet().getPosition();
    Vector3f end = to.getPlanet().getPosition();

    float width = label.getLineWidth();
    Random r = new Random();
    //        float height = r.nextFloat() * end.subtract(start).z;

    Vector3f position = new Vector3f(width / 2, .15f, 0);
    Vector3f fontPos = start.add(end.subtract(start).mult(0.4f + 0.75f * r.nextFloat()));
    position.addLocal(fontPos);

    Vector3f up = cam.getUp().clone();
    Vector3f dir = cam.getDirection().clone().negateLocal().normalizeLocal();
    Vector3f left = cam.getLeft().clone().normalizeLocal().negateLocal();

    Quaternion look = new Quaternion();
    look.fromAxes(left, up, dir);

    label.setLocalTransform(new Transform(position, look));

    //        Vector3f camPos = IsoCamera.getInstance().getCam().getLocation();
    //        Vector3f fontPos = to.getPlanet().getPosition().
    //                subtract(from.getPlanet().getPosition());
    //        Vector3f up = IsoCamera.getInstance().getCam().getUp().clone();
    //        Vector3f dir = camPos.subtract(fontPos);
    ////        Vector3f dir = Vector3f.UNIT_Y.clone().subtract(fontPos);
    //
    //        Vector3f left = IsoCamera.getInstance().getCam().getLeft().clone();
    //        dir.normalizeLocal();
    //        left.negateLocal();
    //        left.normalizeLocal();
    //        up.normalizeLocal();
    ////        dir.negateLocal();
    //
    //        Quaternion look = new Quaternion();
    //        look.fromAxes(left, up, dir);
    //
    //        Vector3f newPos = to.getPlanet().getPosition().
    //                subtract(from.getPlanet().getPosition());
    //
    //        newPos.x -= label.getLineWidth() / 2;
    //
    //        Transform t = new Transform(newPos, look);
    //
    //        label.setLocalTransform(t);
  }
  @Override
  public void cleanup() {
    localRootNode.removeLight(ai);
    localRootNode.removeLight(dl);

    this.app.getTimer().reset();
    rootNode.detachChild(localRootNode);
    viewPort.removeProcessor(niftyDisplay);
    audio.stop();
    nifty.exit();
    cam.setRotation(Quaternion.IDENTITY);
    cam.setLocation(Vector3f.ZERO);
    cam.setViewPort(0, 1, 0, 1);
    super.cleanup();
  }
예제 #12
0
  public void postQueue(RenderQueue rq) {
    GeometryList occluders = rq.getShadowQueueContent(ShadowMode.Cast);
    if (occluders.size() == 0) {
      noOccluders = true;
      return;
    } else {
      noOccluders = false;
    }

    GeometryList receivers = rq.getShadowQueueContent(ShadowMode.Receive);

    // update frustum points based on current camera
    Camera viewCam = viewPort.getCamera();
    ShadowUtil.updateFrustumPoints(
        viewCam, viewCam.getFrustumNear(), viewCam.getFrustumFar(), 1.0f, points);

    Vector3f frustaCenter = new Vector3f();
    for (Vector3f point : points) {
      frustaCenter.addLocal(point);
    }
    frustaCenter.multLocal(1f / 8f);

    // update light direction
    shadowCam.setProjectionMatrix(null);
    shadowCam.setParallelProjection(true);
    //        shadowCam.setFrustumPerspective(45, 1, 1, 20);

    shadowCam.lookAtDirection(direction, Vector3f.UNIT_Y);
    shadowCam.update();
    shadowCam.setLocation(frustaCenter);
    shadowCam.update();
    shadowCam.updateViewProjection();

    // render shadow casters to shadow map
    ShadowUtil.updateShadowCamera(occluders, receivers, shadowCam, points);

    Renderer r = renderManager.getRenderer();
    renderManager.setCamera(shadowCam, false);
    renderManager.setForcedMaterial(preshadowMat);

    r.setFrameBuffer(shadowFB);
    r.clearBuffers(false, true, false);
    viewPort.getQueue().renderShadowQueue(ShadowMode.Cast, renderManager, shadowCam, true);
    r.setFrameBuffer(viewPort.getOutputFrameBuffer());

    renderManager.setForcedMaterial(null);
    renderManager.setCamera(viewCam, false);
  }
예제 #13
0
  protected void renderShadowMap(
      int shadowMapIndex, GeometryList occluders, GeometryList receivers) {
    shadowMapOccluders =
        getOccludersToRender(shadowMapIndex, occluders, receivers, shadowMapOccluders);
    Camera shadowCam = getShadowCam(shadowMapIndex);

    // saving light view projection matrix for this split
    lightViewProjectionsMatrices[shadowMapIndex].set(shadowCam.getViewProjectionMatrix());
    renderManager.setCamera(shadowCam, false);

    renderManager.getRenderer().setFrameBuffer(shadowFB[shadowMapIndex]);
    renderManager.getRenderer().clearBuffers(false, true, false);

    // render shadow casters to shadow map
    viewPort.getQueue().renderShadowQueue(shadowMapOccluders, renderManager, shadowCam, true);
  }
예제 #14
0
 /**
  * Populates the outputGeometryList with the geometry of the inputGeomtryList that are in the
  * radius of a light. The array of camera must be an array of 6 cameara initialized so they
  * represent the light viewspace of a pointlight
  *
  * @param inputGeometryList The list containing all geometry to check against the camera frustum
  * @param cameras the camera array to check geometries against
  * @param outputGeometryList the list of all geometries that are in the camera frustum
  */
 public static void getGeometriesInLightRadius(
     GeometryList inputGeometryList, Camera[] cameras, GeometryList outputGeometryList) {
   for (int i = 0; i < inputGeometryList.size(); i++) {
     Geometry g = inputGeometryList.get(i);
     boolean inFrustum = false;
     for (int j = 0; j < cameras.length && inFrustum == false; j++) {
       Camera camera = cameras[j];
       int planeState = camera.getPlaneState();
       camera.setPlaneState(0);
       inFrustum = camera.contains(g.getWorldBound()) != Camera.FrustumIntersect.Outside;
       camera.setPlaneState(planeState);
     }
     if (inFrustum) {
       outputGeometryList.add(g);
     }
   }
 }
예제 #15
0
 public void postFrame(FrameBuffer out) {
   if (!noOccluders) {
     postshadowMat.setMatrix4("LightViewProjectionMatrix", shadowCam.getViewProjectionMatrix());
     renderManager.setForcedMaterial(postshadowMat);
     viewPort
         .getQueue()
         .renderShadowQueue(ShadowMode.Receive, renderManager, viewPort.getCamera(), true);
     renderManager.setForcedMaterial(null);
   }
 }
예제 #16
0
  public static void HighlightModel(Camera cam, InputManager inputManager) {
    CollisionResults results = new CollisionResults();
    Vector2f mouseCoords = new Vector2f(inputManager.getCursorPosition());

    Ray mouseRay =
        new Ray(
            cam.getWorldCoordinates(mouseCoords, 0),
            cam.getWorldCoordinates(mouseCoords, 1)
                .subtractLocal(cam.getWorldCoordinates(mouseCoords, 0))
                .normalizeLocal());
    Main.s_TreeNode.collideWith(mouseRay, results);

    if (results.size() > 0) {
      Spatial target = results.getClosestCollision().getGeometry();
      AmbientLight light = new AmbientLight();
      light.setColor(ColorRGBA.Blue);
      Main.s_TreeNode.addLight(light);
      target.addLight(light);
    }
  }
  public void setupOffscreenView() {
    offCamera = new Camera(width, height);

    // create a pre-view. a view that is rendered before the main view
    offView = renderManager.createPreView("Offscreen View", offCamera);
    offView.setBackgroundColor(ColorRGBA.DarkGray);
    offView.setClearFlags(true, true, true);

    // this will let us know when the scene has been rendered to the
    // frame buffer
    offView.addProcessor(this);

    // create offscreen framebuffer
    offBuffer = new FrameBuffer(width, height, 1);

    // setup framebuffer's cam
    offCamera.setFrustumPerspective(45f, 1f, 1f, 1000f);
    offCamera.setLocation(new Vector3f(0f, 0f, -5f));
    offCamera.lookAt(new Vector3f(0f, 0f, 0f), Vector3f.UNIT_Y);

    // setup framebuffer's texture
    //        offTex = new Texture2D(width, height, Format.RGBA8);

    // setup framebuffer to use renderbuffer
    // this is faster for gpu -> cpu copies
    offBuffer.setDepthBuffer(Format.Depth);
    offBuffer.setColorBuffer(Format.RGBA8);
    //        offBuffer.setColorTexture(offTex);

    // set viewport to render to offscreen framebuffer
    offView.setOutputFrameBuffer(offBuffer);

    // setup framebuffer's scene
    Box boxMesh = new Box(Vector3f.ZERO, 1, 1, 1);
    Material material = assetManager.loadMaterial("Interface/Logo/Logo.j3m");
    offBox = new Geometry("box", boxMesh);
    offBox.setMaterial(material);

    // attach the scene to the viewport to be rendered
    offView.attachScene(offBox);
  }
예제 #18
0
  public void addPoint() {
    Point p = new Point();
    p.position = cam.getLocation().clone();
    p.direction = cam.getDirection().clone();
    p.rotation = cam.getRotation().clone();
    p.speed = currentSpeed;
    LOG.info("point added: " + p.position + "  " + p.rotation);

    p.sphere = new Geometry("point", sphereMesh);
    p.sphere.setMaterial(sphereMat);
    p.sphere.setLocalTranslation(p.position);
    sceneNode.attachChild(p.sphere);
    p.arrow =
        new Geometry("arrow", new Arrow(p.direction.mult(TerrainHeighmapCreator.TERRAIN_SCALE)));
    p.arrow.getMesh().setLineWidth(4);
    p.arrow.setMaterial(arrowMat);
    p.arrow.setLocalTranslation(p.position);
    sceneNode.attachChild(p.arrow);

    points.add(p);
  }
  public void showCar() {
    for (int i = 0; i < 4; i++) {
      cars[i] = factory.getCar(car_names[i], assetManager);
      car_con[i] = cars[i].getControl(VehicleControl.class);
    }
    Camera camera = cam.clone();

    camera.setViewPort(.25f, .9f, .1f, .75f);
    carView = this.app.getRenderManager().createPostView("carview", camera);

    space.add(car_con[index]);
    dl = new DirectionalLight();
    localRootNode.addLight(dl);
    ai = new AmbientLight();
    localRootNode.addLight(ai);
    car_con[index].setPhysicsLocation(new Vector3f(0, 1, 0));
    localRootNode.attachChild(cars[index]);
    floor = assetManager.loadModel("Models/garage/garage.mesh.j3o");
    control = new RigidBodyControl(0);
    floor.addControl(control);
    control.setPhysicsLocation(Vector3f.ZERO);
    space.add(control);
    localRootNode.attachChild(floor);

    camera.setLocation(car_con[index].getPhysicsLocation().add(new Vector3f(3, 1f, 0)));
    camera.lookAt(car_con[index].getPhysicsLocation().add(new Vector3f(0, -1, 0)), Vector3f.UNIT_Y);
    dl.setDirection(camera.getDirection());

    carView.attachScene(localRootNode);
  }
예제 #20
0
  public void initialize(RenderManager rm, ViewPort vp) {
    renderManager = rm;
    renderer = rm.getRenderer();
    viewPort = vp;
    fsQuad = new Picture("filter full screen quad");

    Camera cam = vp.getCamera();

    // save view port diensions
    left = cam.getViewPortLeft();
    right = cam.getViewPortRight();
    top = cam.getViewPortTop();
    bottom = cam.getViewPortBottom();
    originalWidth = cam.getWidth();
    originalHeight = cam.getHeight();
    // first call to reshape
    reshape(vp, cam.getWidth(), cam.getHeight());
  }
예제 #21
0
  /**
   * Updates a points arrays with the frustum corners of the provided camera.
   *
   * @param viewCam
   * @param points
   */
  public static void updateFrustumPoints2(Camera viewCam, Vector3f[] points) {
    int w = viewCam.getWidth();
    int h = viewCam.getHeight();
    float n = viewCam.getFrustumNear();
    float f = viewCam.getFrustumFar();

    points[0].set(viewCam.getWorldCoordinates(new Vector2f(0, 0), n));
    points[1].set(viewCam.getWorldCoordinates(new Vector2f(0, h), n));
    points[2].set(viewCam.getWorldCoordinates(new Vector2f(w, h), n));
    points[3].set(viewCam.getWorldCoordinates(new Vector2f(w, 0), n));

    points[4].set(viewCam.getWorldCoordinates(new Vector2f(0, 0), f));
    points[5].set(viewCam.getWorldCoordinates(new Vector2f(0, h), f));
    points[6].set(viewCam.getWorldCoordinates(new Vector2f(w, h), f));
    points[7].set(viewCam.getWorldCoordinates(new Vector2f(w, 0), f));
  }
예제 #22
0
  public static void MoveModel(Camera cam, InputManager inputManager, Spatial scene) {
    if (Statics.s_PlayerSettingModel == true) {
      CollisionResults results = new CollisionResults();
      Ray ray = new Ray();
      Vector2f click2d = inputManager.getCursorPosition();
      Vector3f click3d = cam.getWorldCoordinates(new Vector2f(click2d.getX(), click2d.getY()), 0f);
      Vector3f dir =
          cam.getWorldCoordinates(new Vector2f(click2d.getX(), click2d.getY()), 1f)
              .subtractLocal(click3d)
              .normalizeLocal();
      ray.setOrigin(click3d);
      ray.setDirection(dir);
      ray = new Ray(click3d, dir);
      scene.collideWith(ray, results);

      if (results.size() > 0) {
        CollisionResult point = results.getClosestCollision();
        Vector3f destination = point.getContactPoint();
        ObjectHelper.s_Model.setMaterial(ObjectHelper.greenTrans);
        SetModel(destination);
      }
    }
  }
  @Override
  protected void controlUpdate(float tpf) {
    // list of cameras for when terrain supports multiple cameras (ie split screen)

    if (lodCalculator == null) return;

    if (!enabled) {
      if (!hasResetLod) {
        // this will get run once
        hasResetLod = true;
        lodCalculator.turnOffLod();
      }
    }

    if (cameras != null) {
      if (cameraLocations.isEmpty() && !cameras.isEmpty()) {
        for (Camera c : cameras) // populate them
        {
          cameraLocations.add(c.getLocation());
        }
      }
      updateLOD(cameraLocations, lodCalculator);
    }
  }
예제 #24
0
  @Override
  protected void initialize(Application app) {

    ed = getState(EntityDataState.class).getEntityData();
    entities = ed.getEntities(Position.class, ModelType.class);

    // Calculate how big min/max needs to be to incorporate
    // the full view + margin at z = 0
    Camera cam = app.getCamera();
    float z = cam.getViewToProjectionZ(cam.getLocation().z);
    Vector3f worldMin = cam.getWorldCoordinates(new Vector2f(0, 0), z);
    Vector3f worldMax = cam.getWorldCoordinates(new Vector2f(cam.getWidth(), cam.getHeight()), z);
    min = worldMin.addLocal(-margin, -margin, 0);
    max = worldMax.addLocal(margin, margin, 0);
  }
예제 #25
0
  private void onUpdateClientConfig(ClientConfigChangedEvent event) {
    String key = event.getKey();

    if (key.startsWith("r_")) {
      updateGraphicSettings();

      if (key.equals(ClientConfigConstants.r_resolution)) {
        String resolutionString = ClientConfig.getString(ClientConfigConstants.r_resolution);
        String[] resParts = resolutionString.split("x");
        Integer width = Integer.valueOf(resParts[0]);
        Integer height = Integer.valueOf(resParts[1]);

        cam.resize(width, height, true);

        ScreenUtils.reset();

        eventBus.fireEvent(new UpdateGraphicsConfigEvent(key, event.getValue()));
      }
    }
  }
예제 #26
0
  /**
   * Updates the shadow camera to properly contain the given points (which contain the eye camera
   * frustum corners)
   *
   * @param shadowCam
   * @param points
   */
  public static void updateShadowCamera(Camera shadowCam, Vector3f[] points) {
    boolean ortho = shadowCam.isParallelProjection();
    shadowCam.setProjectionMatrix(null);

    if (ortho) {
      shadowCam.setFrustum(-1, 1, -1, 1, 1, -1);
    } else {
      shadowCam.setFrustumPerspective(45, 1, 1, 150);
    }

    Matrix4f viewProjMatrix = shadowCam.getViewProjectionMatrix();
    Matrix4f projMatrix = shadowCam.getProjectionMatrix();

    BoundingBox splitBB = computeBoundForPoints(points, viewProjMatrix);

    TempVars vars = TempVars.get();

    Vector3f splitMin = splitBB.getMin(vars.vect1);
    Vector3f splitMax = splitBB.getMax(vars.vect2);

    //        splitMin.z = 0;

    // Create the crop matrix.
    float scaleX, scaleY, scaleZ;
    float offsetX, offsetY, offsetZ;

    scaleX = 2.0f / (splitMax.x - splitMin.x);
    scaleY = 2.0f / (splitMax.y - splitMin.y);
    offsetX = -0.5f * (splitMax.x + splitMin.x) * scaleX;
    offsetY = -0.5f * (splitMax.y + splitMin.y) * scaleY;
    scaleZ = 1.0f / (splitMax.z - splitMin.z);
    offsetZ = -splitMin.z * scaleZ;

    Matrix4f cropMatrix = vars.tempMat4;
    cropMatrix.set(
        scaleX, 0f, 0f, offsetX, 0f, scaleY, 0f, offsetY, 0f, 0f, scaleZ, offsetZ, 0f, 0f, 0f, 1f);

    Matrix4f result = new Matrix4f();
    result.set(cropMatrix);
    result.multLocal(projMatrix);

    vars.release();
    shadowCam.setProjectionMatrix(result);
  }
  @Override
  public void updateParticleData(ParticleData[] particles, Camera cam, Matrix3f inverseRotation) {

    for (int i = 0; i < particles.length; i++) {
      ParticleData p = particles[i];
      int offset = templateVerts.capacity() * i;
      int colorOffset = templateColors.capacity() * i;
      if (p.life == 0 || !p.active) {
        for (int x = 0; x < templateVerts.capacity(); x += 3) {
          finVerts.put(offset + x, 0);
          finVerts.put(offset + x + 1, 0);
          finVerts.put(offset + x + 2, 0);
        }
        continue;
      }

      for (int x = 0; x < templateVerts.capacity(); x += 3) {
        switch (emitter.getBillboardMode()) {
          case Velocity:
            if (p.velocity.x != Vector3f.UNIT_Y.x
                && p.velocity.y != Vector3f.UNIT_Y.y
                && p.velocity.z != Vector3f.UNIT_Y.z)
              up.set(p.velocity).crossLocal(Vector3f.UNIT_Y).normalizeLocal();
            else up.set(p.velocity).crossLocal(lock).normalizeLocal();
            left.set(p.velocity).crossLocal(up).normalizeLocal();
            dir.set(p.velocity);
            break;
          case Velocity_Z_Up:
            if (p.velocity.x != Vector3f.UNIT_Y.x
                && p.velocity.y != Vector3f.UNIT_Y.y
                && p.velocity.z != Vector3f.UNIT_Y.z)
              up.set(p.velocity).crossLocal(Vector3f.UNIT_Y).normalizeLocal();
            else up.set(p.velocity).crossLocal(lock).normalizeLocal();
            left.set(p.velocity).crossLocal(up).normalizeLocal();
            dir.set(p.velocity);
            rotStore = tempQ.fromAngleAxis(-90 * FastMath.DEG_TO_RAD, left);
            left = rotStore.mult(left);
            up = rotStore.mult(up);
            break;
          case Velocity_Z_Up_Y_Left:
            up.set(p.velocity).crossLocal(Vector3f.UNIT_Y).normalizeLocal();
            left.set(p.velocity).crossLocal(up).normalizeLocal();
            dir.set(p.velocity);
            tempV3.set(left).crossLocal(up).normalizeLocal();
            rotStore = tempQ.fromAngleAxis(90 * FastMath.DEG_TO_RAD, p.velocity);
            left = rotStore.mult(left);
            up = rotStore.mult(up);
            rotStore = tempQ.fromAngleAxis(-90 * FastMath.DEG_TO_RAD, left);
            up = rotStore.mult(up);
            break;
          case Normal:
            emitter.getShape().setNext(p.triangleIndex);
            tempV3.set(emitter.getShape().getNormal());
            if (tempV3 == Vector3f.UNIT_Y) tempV3.set(p.velocity);

            up.set(tempV3).crossLocal(Vector3f.UNIT_Y).normalizeLocal();
            left.set(tempV3).crossLocal(up).normalizeLocal();
            dir.set(tempV3);
            break;
          case Normal_Y_Up:
            emitter.getShape().setNext(p.triangleIndex);
            tempV3.set(p.velocity);
            if (tempV3 == Vector3f.UNIT_Y) tempV3.set(Vector3f.UNIT_X);

            up.set(Vector3f.UNIT_Y);
            left.set(tempV3).crossLocal(up).normalizeLocal();
            dir.set(tempV3);
            break;
          case Camera:
            up.set(cam.getUp());
            left.set(cam.getLeft());
            dir.set(cam.getDirection());
            break;
          case UNIT_X:
            up.set(Vector3f.UNIT_Y);
            left.set(Vector3f.UNIT_Z);
            dir.set(Vector3f.UNIT_X);
            break;
          case UNIT_Y:
            up.set(Vector3f.UNIT_Z);
            left.set(Vector3f.UNIT_X);
            dir.set(Vector3f.UNIT_Y);
            break;
          case UNIT_Z:
            up.set(Vector3f.UNIT_X);
            left.set(Vector3f.UNIT_Y);
            dir.set(Vector3f.UNIT_Z);
            break;
        }

        tempV3.set(templateVerts.get(x), templateVerts.get(x + 1), templateVerts.get(x + 2));
        tempV3 = rotStore.mult(tempV3);
        tempV3.multLocal(p.size);

        rotStore.fromAngles(p.angles.x, p.angles.y, p.angles.z);
        tempV3 = rotStore.mult(tempV3);

        tempV3.addLocal(p.position);
        if (!emitter.getParticlesFollowEmitter()) {
          tempV3.subtractLocal(
              emitter
                  .getEmitterNode()
                  .getWorldTranslation()
                  .subtract(p.initialPosition)); // .divide(8f));
        }

        finVerts.put(offset + x, tempV3.getX());
        finVerts.put(offset + x + 1, tempV3.getY());
        finVerts.put(offset + x + 2, tempV3.getZ());
      }
      if (p.emitter.getApplyLightingTransform()) {
        for (int v = 0; v < templateNormals.capacity(); v += 3) {
          tempV3.set(
              templateNormals.get(v), templateNormals.get(v + 1), templateNormals.get(v + 2));

          rotStore.fromAngles(p.angles.x, p.angles.y, p.angles.z);
          mat3.set(rotStore.toRotationMatrix());
          float vx = tempV3.x, vy = tempV3.y, vz = tempV3.z;
          tempV3.x = mat3.get(0, 0) * vx + mat3.get(0, 1) * vy + mat3.get(0, 2) * vz;
          tempV3.y = mat3.get(1, 0) * vx + mat3.get(1, 1) * vy + mat3.get(1, 2) * vz;
          tempV3.z = mat3.get(2, 0) * vx + mat3.get(2, 1) * vy + mat3.get(2, 2) * vz;

          finNormals.put(offset + v, tempV3.getX());
          finNormals.put(offset + v + 1, tempV3.getY());
          finNormals.put(offset + v + 2, tempV3.getZ());
        }
      }
      for (int v = 0; v < templateColors.capacity(); v += 4) {
        finColors
            .put(colorOffset + v, p.color.r)
            .put(colorOffset + v + 1, p.color.g)
            .put(colorOffset + v + 2, p.color.b)
            .put(colorOffset + v + 3, p.color.a * p.alpha);
      }
    }

    this.setBuffer(VertexBuffer.Type.Position, 3, finVerts);
    if (particles[0].emitter.getApplyLightingTransform())
      this.setBuffer(VertexBuffer.Type.Normal, 3, finNormals);
    this.setBuffer(VertexBuffer.Type.Color, 4, finColors);

    updateBound();
  }
예제 #28
0
  /**
   * @param panel
   * @param id
   * @param pictureFile
   * @param width
   * @param height
   */
  public TextField(
      Panel panel, String id, String pictureFile, float width, float height, boolean lockScale) {
    super(panel.getWindow(), panel, pictureFile, width, height, lockScale);
    this.id = id;
    setName(id);

    // Init the text
    float xP = -getWidth() * 0.5f;
    float yP = getHeight() * 0.5f;
    float recWidth = getWidth();
    float factor = 1f;
    float recHeight = (getHeight() * 0.5f) * factor;
    float padding = 0f;

    bitmapText = window.getBitmapFont().createLabel(id);
    bitmapText.setText(" ");
    bitmapText.setBox(new Rectangle(xP + padding, yP, recWidth + padding, recHeight));
    bitmapText.setSize(fontSize * window.getScaleFactorHeight()); // font size
    bitmapText.setColor(ColorRGBA.DarkGray); // font color
    bitmapText.setAlignment(BitmapFont.Align.Left);
    bitmapText.setVerticalAlignment(BitmapFont.VAlign.Center);
    bitmapText.setLineWrapMode(LineWrapMode.NoWrap);
    widgetNode.attachChild(bitmapText);

    this.inputManager = window.getInputManager();
    this.cam = window.getApplication().getCamera();
    this.results = new CollisionResults();
    this.ray = new Ray(cam.getLocation(), cam.getDirection());

    actionListener =
        new ActionListener() {
          public void onAction(String name, boolean isPressed, float tpf) {
            results.clear();

            if (isVisible() && isEnabled()) {

              if ((TextField.this.id + "MOUSE").equals(name)) {

                // 1. calc direction
                Vector3f origin =
                    new Vector3f(
                        inputManager.getCursorPosition().x, inputManager.getCursorPosition().y, 1f);
                Vector3f direction = new Vector3f(0, 0, -1);

                // 2. Aim the ray from cam loc to cam direction.
                ray.setOrigin(origin);
                ray.setDirection(direction);

                // 3. Collect intersections between Ray and Shootables in results list.
                window.getWindowNode().collideWith(ray, results);

                // 5. Use the results (we mark the hit object)
                if (results.size() > 0) {

                  for (int i = 0; i < results.size(); i++) {
                    CollisionResult cr = results.getCollision(i);
                    //                                System.out.println("\t-> Hit: " +
                    // cr.getGeometry().getParent().getName());

                    if (widgetNode.hasChild(cr.getGeometry())) {
                      //                                    System.out.println("\t\t\tCollision -> "
                      // + TouchButton.this.id);
                      if (isPressed) {
                        wasDown = true;
                        getWindow().removeFocusFromFields();
                        focus = true;
                        fireFocusListener(TextField.this.id);
                      }
                    }
                  }
                }
              }
            }
          }
        };

    inputManager.addRawInputListener(
        new RawInputListener() {

          public void beginInput() {}

          public void endInput() {}

          public void onJoyAxisEvent(JoyAxisEvent evt) {}

          public void onJoyButtonEvent(JoyButtonEvent evt) {}

          public void onMouseMotionEvent(MouseMotionEvent evt) {}

          public void onMouseButtonEvent(MouseButtonEvent evt) {}

          public void onKeyEvent(KeyInputEvent evt) {
            //                System.out.println("Keyinput ***************** Key = " +
            // evt.getKeyCode());

            if (enabled && focus && evt.isReleased()) {
              String keyChar = keyNames.getName(evt.getKeyCode());
              //                    System.out.println("Keyinput ***************** Char = " +
              // keyChar);

              if (evt.getKeyCode() == 14) {
                if (getText().length() > 0) {
                  setText(getText().substring(0, getText().length() - 1));
                }
              } else if (evt.getKeyCode() == 15) {
                focus = false;

              } else if (keyChar != null && evt.getKeyCode() == 57) {
                setText(getText() + " ");

              } else if (keyChar != null && evt.getKeyCode() == 58) {
                caps = !caps;

              } else if (keyChar != null && keyChar.length() == 1) {
                if (!caps) {
                  keyChar = keyChar.toLowerCase();
                }
                setText(getText() + keyChar);
              }

              if (getText().length() > maxLength) {
                setText(getText().substring(0, maxLength));
              }

              fireKeyboardListener(evt);
            }
          }

          public void onTouchEvent(TouchEvent evt) {
            //                System.out.println("Touchinput ***************** Keycode = " +
            // evt.getKeyCode());

            if (enabled && focus && evt.getType().equals(TouchEvent.Type.KEY_DOWN)) {
              String keyChar = touchKeyNames.getName(evt.getKeyCode());
              System.out.println(
                  "\n\n\nTouchinput ***************** KeyCode = " + evt.getKeyCode());

              if (evt.getKeyCode() == 67) { // backspace
                if (getText().length() > 0) {
                  setText(getText().substring(0, getText().length() - 1));
                }

              } else if (keyChar != null && evt.getKeyCode() == 62) { // space
                setText(getText() + " ");

              } else if (keyChar != null && evt.getKeyCode() == 59) { // shift
                caps = !caps;

              } else if (keyChar != null && keyChar.length() == 1) {
                // TODO:
                //                        if (!caps) {
                keyChar = keyChar.toLowerCase();
                //                        }
                setText(getText() + keyChar);
              }

              if (getText().length() > maxLength) {
                setText(getText().substring(0, maxLength));
              }

              //                    if (evt.getKeyCode() == 67) {
              //                        if (getText().length() > 0) {
              //                            setText(getText().substring(0, getText().length()-1));
              //                        }
              //
              //                    } else if (evt.getKeyCode() == 59) {
              //                        if (getText().length() > 0) {
              //                            setText(getText().substring(0, getText().length()-1));
              //                        }
              //
              //                    } else if (keyChar != null && keyChar.length() == 1) {
              //                        setText(getText() + keyChar);
              //                    }
              //
              //                    if (getText().length() > maxLength) {
              //                        setText(getText().substring(0, maxLength));
              //                    }

            }
          }
        });

    // NICKI
    panel.add(this);

    //        bitmapText.setLocalTranslation(bitmapText.getLocalTranslation().x,
    // bitmapText.getLocalTranslation().y, 0.001f);
  }
  public void postQueue(RenderQueue rq) {
    Camera sceneCam = rm.getCurrentCamera();

    // update refraction cam
    refractionCam.setLocation(sceneCam.getLocation());
    refractionCam.setRotation(sceneCam.getRotation());
    refractionCam.setFrustum(
        sceneCam.getFrustumNear(),
        sceneCam.getFrustumFar(),
        sceneCam.getFrustumLeft(),
        sceneCam.getFrustumRight(),
        sceneCam.getFrustumTop(),
        sceneCam.getFrustumBottom());
    refractionCam.setParallelProjection(sceneCam.isParallelProjection());

    // update reflection cam
    WaterUtils.updateReflectionCam(reflectionCam, plane, sceneCam);

    // Rendering reflection and refraction
    rm.renderViewPort(reflectionView, savedTpf);
    rm.renderViewPort(refractionView, savedTpf);
    rm.getRenderer().setFrameBuffer(vp.getOutputFrameBuffer());
    rm.setCamera(sceneCam, false);
  }
예제 #30
0
  /**
   * Updates the points array to contain the frustum corners of the given camera. The nearOverride
   * and farOverride variables can be used to override the camera's near/far values with own values.
   *
   * <p>TODO: Reduce creation of new vectors
   *
   * @param viewCam
   * @param nearOverride
   * @param farOverride
   */
  public static void updateFrustumPoints(
      Camera viewCam, float nearOverride, float farOverride, float scale, Vector3f[] points) {

    Vector3f pos = viewCam.getLocation();
    Vector3f dir = viewCam.getDirection();
    Vector3f up = viewCam.getUp();

    float depthHeightRatio = viewCam.getFrustumTop() / viewCam.getFrustumNear();
    float near = nearOverride;
    float far = farOverride;
    float ftop = viewCam.getFrustumTop();
    float fright = viewCam.getFrustumRight();
    float ratio = fright / ftop;

    float near_height;
    float near_width;
    float far_height;
    float far_width;

    if (viewCam.isParallelProjection()) {
      near_height = ftop;
      near_width = near_height * ratio;
      far_height = ftop;
      far_width = far_height * ratio;
    } else {
      near_height = depthHeightRatio * near;
      near_width = near_height * ratio;
      far_height = depthHeightRatio * far;
      far_width = far_height * ratio;
    }

    Vector3f right = dir.cross(up).normalizeLocal();

    Vector3f temp = new Vector3f();
    temp.set(dir).multLocal(far).addLocal(pos);
    Vector3f farCenter = temp.clone();
    temp.set(dir).multLocal(near).addLocal(pos);
    Vector3f nearCenter = temp.clone();

    Vector3f nearUp = temp.set(up).multLocal(near_height).clone();
    Vector3f farUp = temp.set(up).multLocal(far_height).clone();
    Vector3f nearRight = temp.set(right).multLocal(near_width).clone();
    Vector3f farRight = temp.set(right).multLocal(far_width).clone();

    points[0].set(nearCenter).subtractLocal(nearUp).subtractLocal(nearRight);
    points[1].set(nearCenter).addLocal(nearUp).subtractLocal(nearRight);
    points[2].set(nearCenter).addLocal(nearUp).addLocal(nearRight);
    points[3].set(nearCenter).subtractLocal(nearUp).addLocal(nearRight);

    points[4].set(farCenter).subtractLocal(farUp).subtractLocal(farRight);
    points[5].set(farCenter).addLocal(farUp).subtractLocal(farRight);
    points[6].set(farCenter).addLocal(farUp).addLocal(farRight);
    points[7].set(farCenter).subtractLocal(farUp).addLocal(farRight);

    if (scale != 1.0f) {
      // find center of frustum
      Vector3f center = new Vector3f();
      for (int i = 0; i < 8; i++) {
        center.addLocal(points[i]);
      }
      center.divideLocal(8f);

      Vector3f cDir = new Vector3f();
      for (int i = 0; i < 8; i++) {
        cDir.set(points[i]).subtractLocal(center);
        cDir.multLocal(scale - 1.0f);
        points[i].addLocal(cDir);
      }
    }
  }