private void setTransformation(Matrix4f transformation) {
    // Compute the modelview matrix by multiplying the camera matrix and
    // the transformation matrix of the object
    Matrix4f modelview = new Matrix4f(sceneManager.getCamera().getCameraMatrix());
    modelview.mul(transformation);

    // Set modelview and projection matrices in shader
    gl.glUniformMatrix4fv(
        gl.glGetUniformLocation(activeShaderID, "modelview"),
        1,
        false,
        transformationToFloat16(modelview),
        0);
    gl.glUniformMatrix4fv(
        gl.glGetUniformLocation(activeShaderID, "projection"),
        1,
        false,
        transformationToFloat16(sceneManager.getFrustum().getProjectionMatrix()),
        0);

    int id = gl.glGetUniformLocation(activeShaderID, "camera");
    if (id != -1) {
      Vector3f cop = sceneManager.getCamera().getCenterOfProjection();
      gl.glUniform4f(id, cop.x, cop.y, cop.z, 0);
    }
    // } else
    // System.out.println("Could not get location of uniform variable camera");
  }
示例#2
0
    public void keyPressed(KeyEvent e) {
      keyMove = new Matrix4f();
      keyMove.setIdentity();
      Vector3f keyMovement = new Vector3f();

      switch (e.getKeyChar()) {
        case 's':
          keyMovement.z = -1 * scale;
          keyMove.setTranslation(keyMovement);
          break;

        case 'w':
          keyMovement.z = 1 * scale;
          keyMove.setTranslation(keyMovement);
          break;

        case 'a':
          keyMovement.x = 1 * scale;
          keyMove.setTranslation(keyMovement);
          break;

        case 'd':
          keyMovement.x = -1 * scale;
          keyMove.setTranslation(keyMovement);
          break;
        default:
          System.out.println("invalid key");
          break;
      }
    }
示例#3
0
 /** Clear the framebuffer here. */
 private void beginFrame() {
   zBuffer = new float[width][height];
   mergedDisplayMatrix = new Matrix4f(viewPortMatrix);
   mergedDisplayMatrix.mul(sceneManager.getFrustum().getProjectionMatrix());
   mergedDisplayMatrix.mul(sceneManager.getCamera().getCameraMatrix());
   colorBuffer.getGraphics().clearRect(0, 0, width, height);
 }
示例#4
0
 public void setDirection(Vector3f direction) {
   Matrix4f initMat = new Matrix4f();
   float angle = new Vector3f(1, 0, 0).angle(direction);
   if (direction.z > 0) initMat.rotY(-angle);
   else initMat.rotY(angle);
   setTransformation(initMat);
 }
示例#5
0
  /**
   * Unprojects the screen coordinates into a ray in the 3D space. It creates a point and a
   * direction in the object space where the ray will pass through. This can be used if the user
   * should be able to interact with the 3D space.
   *
   * @param x the x-coordinate
   * @param y the y-coordinate
   * @return the ray in the object space
   */
  public Ray unproject(float x, float y) {

    Matrix4f staticMatrix = createMatrices();
    Matrix4f inverse;

    Vector3f origin = new Vector3f(x, y, 1);
    Vector3f direction = new Vector3f(x, y, -1);
    inverse = new Matrix4f(staticMatrix);
    try {
      inverse.invert();

    } catch (RuntimeException exc) {
      // Matrix not invertable, therefore no action.
      Log.e("UNPROJECT", "Matrix can't be inverted");
      return null;
    }

    Util.transform(inverse, origin);
    Util.transform(inverse, direction);

    direction.sub(origin);
    direction.normalize();

    return new Ray(origin, direction);
  }
示例#6
0
 /**
  * A wheel class, isn't that great? Does not move on its own, only rotate
  *
  * @param radius
  * @param direction
  * @param speed
  */
 public Wheel(float radius, float speed) {
   super(new Torus(radius, radius / 4, 60, 5));
   this.radius = radius;
   rotatePerStep.rotZ(0.01f * speed / radius);
   rotatePerStep.invert();
   rotate.setIdentity();
 }
示例#7
0
 void setDirectionVector(ServerElement element, Float x, Float y, Float z) {
   RigidBody rb = elementToRigidBody.get(element);
   rb.getOrientation(oriantation);
   rot.set(oriantation);
   directionVector.set(x, y, z);
   rot.transform(directionVector);
 }
示例#8
0
  public void position(Vector3f vec) {
    activate();

    Matrix4f t = transform();
    t.setTranslation(vec);

    transform(t);
  }
 /**
  * Consolidated the array of transform elements into the argument matrix
  *
  * @param te The array of TransformElements
  */
 static void getMatrix(TransformElement[] te, Matrix4f matrix) {
   Matrix4f m = new Matrix4f();
   matrix.setIdentity();
   for (int i = 0; i < te.length; i++) {
     te[i].getMatrix(m);
     matrix.mul(m);
   }
 }
示例#10
0
    public void mouseDragged(MouseEvent e) {

      oldMoveVector = new Vector3f(fixOldX, oldY, oldZ);
      oldWorldZMoveVector = new Vector3f(oldX, oldY, oldZ);

      // get x,y
      newX = e.getX() / (adjustToScreenSize / 2) - 1; // used to be (float)jframe.getWidth()
      newY = 1 - e.getY() / (adjustToScreenSize / 2); // used to be (float)jframe.getWidth()
      newZ = calculateZ(newX, newY);

      newMoveVector = new Vector3f(fixNewX, newY, newZ);
      newWorldZMoveVector = new Vector3f(newX, newY, newZ);

      // now calculate the Camera movement
      Vector3f moveAxis = new Vector3f(); // moving around this axis
      moveAxis.cross(
          oldMoveVector,
          newMoveVector); // TODO identify, if the axis points down or upwards => adjust the angle
      float moveAngle = oldMoveVector.angle(newMoveVector); // moving by this angle

      // special Vector including the angle
      AxisAngle4f moveAxisAngle = new AxisAngle4f();
      moveAxisAngle.set(moveAxis, moveAngle);

      // calculate turning axis
      mouseTurn = new Matrix4f();
      mouseTurn.setIdentity();
      mouseTurn.set(moveAxisAngle); // the new Multiplication-Matrix

      // now calculate the World movement
      Vector3f worldMoveAxis = new Vector3f(); // moving around this axis
      worldMoveAxis.x = 0;
      worldMoveAxis.y = 0;
      worldMoveAxis.z = 1;
      float worldMoveAngle = oldWorldZMoveVector.angle(newWorldZMoveVector); // moving by this angle

      // adjust world Angle for turning back
      Vector3f worldMoveAxisTemp = new Vector3f();
      worldMoveAxisTemp.cross(oldWorldZMoveVector, newWorldZMoveVector);
      if (worldMoveAxisTemp.z < 0) {
        worldMoveAngle = -worldMoveAngle;
      }

      // special Vector including the angle
      AxisAngle4f worldMoveAxisAngle = new AxisAngle4f();
      worldMoveAxisAngle.set(worldMoveAxis, worldMoveAngle);

      // calculate turning axis
      mouseWorldTurn = new Matrix4f();
      mouseWorldTurn.setIdentity();
      mouseWorldTurn.set(worldMoveAxisAngle); // the new Multiplication-Matrix

      // override the initial starting values
      fixOldX = fixNewX;
      oldX = newX;
      oldY = newY;
      oldZ = newZ;
    }
示例#11
0
  /**
   * Creates the matrices that are used for the projection from the 3D-space onto a 2D-screen.
   * (Result=ViewMatrix*ProjectionMatrix*ViewportMatrix)
   *
   * @return the complete matrix
   */
  private Matrix4f createMatrices() {

    Matrix4f staticMatrix = new Matrix4f(mRenderer.getViewportMatrix());
    Matrix4f projMatrix = mRenderer.getSceneManager().getFrustum().getProjectionMatrix();
    staticMatrix.mul(projMatrix);
    Matrix4f cameraMatrix = mRenderer.getSceneManager().getCamera().getCameraMatrix();
    staticMatrix.mul(cameraMatrix);

    return staticMatrix;
  }
  @Override
  public void preRender(VertexType vt, Matrix4f worldMatrix, RenderManager rm) {
    auxMatrix.setIdentity();
    rm.getViewProjectionMatrix(auxMatrix);
    auxMatrix.mul(worldMatrix);
    RenderManager.matrixToBuffer(auxMatrix, fb);
    glUniformMatrix4(worldViewProj, false, fb);

    preRenderShortcut.preRender(vt, worldMatrix, rm);
  }
示例#13
0
 /**
  * Set a new viewport size. The render context will also need to store a viewport matrix, which
  * you need to reset here.
  */
 public void setViewportSize(int width, int height) {
   this.width = width;
   this.height = height;
   viewPortMatrix = new Matrix4f();
   viewPortMatrix.setM00(width / 2f);
   viewPortMatrix.setM11(height / 2f);
   viewPortMatrix.setM22(1 / 2f);
   viewPortMatrix.setColumn(3, width / 2f, height / 2f, 1 / 2f, 1);
   colorBuffer = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
 }
    // TODO: This won't work in multiplayer
    public float distanceToPlayer() {
      Transform t = new Transform();
      getMotionState().getWorldTransform(t);
      Matrix4f tMatrix = new Matrix4f();
      t.getMatrix(tMatrix);

      Vector3f blockPlayer = new Vector3f();
      tMatrix.get(blockPlayer);
      blockPlayer.sub(new Vector3f(CoreRegistry.get(LocalPlayer.class).getPosition()));

      return blockPlayer.length();
    }
 // reuse untransformPointTemp to reduce memory use and speed up
 void unTransformPoint(Point3i screenPt, Point3f coordPt) {
   if (untransformPointTemp == null) untransformPointTemp = new Point3f();
   untransformPointTemp.set(
       screenPt.x - perspectiveOffset.x, screenPt.y - perspectiveOffset.y, screenPt.z);
   if (perspectiveDepth) {
     float inversePerspectiveFactor = 1.0f / perspectiveFactor(untransformPointTemp.z);
     untransformPointTemp.x *= inversePerspectiveFactor;
     untransformPointTemp.y *= inversePerspectiveFactor;
   }
   untransformPointTemp.z += perspectiveOffset.z;
   if (untransformMatrixTemp == null) untransformMatrixTemp = new Matrix4f();
   untransformMatrixTemp.invert(matrixTransform);
   untransformMatrixTemp.transform(untransformPointTemp, coordPt);
 }
    public float distanceToEntity(EntityRef target) {
      Transform t = new Transform();
      getMotionState().getWorldTransform(t);
      Matrix4f tMatrix = new Matrix4f();
      t.getMatrix(tMatrix);

      Vector3f blockPlayer = new Vector3f();
      tMatrix.get(blockPlayer);

      LocationComponent loc = target.getComponent(LocationComponent.class);
      if (loc != null) blockPlayer.sub(loc.getWorldPosition());
      else blockPlayer.sub(new Vector3f());

      return blockPlayer.length();
    }
示例#17
0
 private void init() {
   mBox = new BoundingBox(mVertexBuffers.getVertexBuffer());
   t = new Matrix4f();
   t.setIdentity();
   mZeroVector = new Vector3f(0, 0, 0);
   mEpsilon = 0.001f;
 }
示例#18
0
 /**
  * Draws only the vertices of the given shape in white. Normals and indices are ignored. TODO:
  * negative W are possible, fix plx?
  *
  * @param shape
  * @param t
  */
 private void drawDotty(Shape shape, Matrix4f t) {
   float[] points = null, colors = null;
   for (VertexElement ve : shape.getVertexData().getElements()) {
     switch (ve.getSemantic()) {
       case POSITION:
         points = ve.getData();
         break;
       case COLOR:
         colors = ve.getData();
         break;
       case NORMAL:
         // DO NOT WANT
         break;
       case TEXCOORD:
         // DO NOT WANT
         break;
     }
   }
   for (int i = 0; i < points.length; i += 3) {
     Point4f v = new Point4f(points[i], points[i + 1], points[i + 2], 1);
     Color3f c = new Color3f(colors[i], colors[i + 1], colors[i + 2]);
     t.transform(v);
     int x = Math.round(v.x / v.w);
     int y = Math.round(v.y / v.w);
     if (x >= 0 && y >= 0 && y < colorBuffer.getHeight() && x < colorBuffer.getWidth())
       drawPointAt(x, y, c.get().getRGB());
   }
 }
示例#19
0
 @Override
 public void setModelViewMatrix(Matrix4f value) {
   gl.uniformMatrix(getUniformLocation("matWorldView"), value);
   value.get(normalMatrix);
   normalMatrix.invert();
   normalMatrix.transpose();
   gl.uniformMatrix(getUniformLocation("uNormalMatrix"), normalMatrix);
 }
示例#20
0
 private void updateLocalTransform() {
   localTransform = parent.transform();
   Matrix4f ms = new Matrix4f();
   ms.setIdentity();
   Vector3f ps = parent.scale();
   ms.m00 = ps.x;
   ms.m11 = ps.y;
   ms.m22 = ps.z;
   localTransform.mul(ms);
   localTransform.invert();
   localTransform.mul(transform());
 }
示例#21
0
  public void updateChildTransforms() {
    Matrix4f pt = transform();
    Matrix4f ct = new Matrix4f();
    Matrix4f ms = new Matrix4f();
    ms.setIdentity();
    Vector3f ps = scale();
    ms.m00 = ps.x;
    ms.m11 = ps.y;
    ms.m22 = ps.z;
    pt.mul(ms);

    for (GameObject c : children) {
      ct.mul(pt, c.localTransform);
      c.transform(ct, false);
    }
  }
  private void setTransformation(Matrix4f transformation) {
    // Compute the modelview matrix by multiplying the camera matrix and
    // the transformation matrix of the object
    Matrix4f modelview = new Matrix4f(sceneManager.getCamera().getCameraMatrix());
    modelview.mul(transformation);

    // Set modelview and projection matrices in shader
    gl.glUniformMatrix4fv(
        gl.glGetUniformLocation(activeShaderID, "modelview"),
        1,
        false,
        transformationToFloat16(modelview),
        0);
    gl.glUniformMatrix4fv(
        gl.glGetUniformLocation(activeShaderID, "projection"),
        1,
        false,
        transformationToFloat16(sceneManager.getFrustum().getProjectionMatrix()),
        0);
  }
示例#23
0
  public static Matrix4f convertMT4JMatrixToMatrix4f(Matrix matrix) {
    Matrix4f mat = new Matrix4f();
    for (int i = 0; i < 4; i++) {
      float[] col;
      try {
        col = matrix.getColumn(i);

        try {
          mat.setColumn(i, col);
        } catch (Exception e) {

          e.printStackTrace();
        }
      } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }
    }
    return mat;
  }
示例#24
0
  public static Matrix convertMatrix4fToMT4JMatrix(Matrix4f matrix) {
    Matrix mat = new Matrix();
    for (int i = 0; i < 4; i++) {
      float[] col = new float[4];
      matrix.getColumn(i, col);
      try {
        mat.setColumn(i, col);
      } catch (Exception e) {

        e.printStackTrace();
      }
    }
    return mat;
  }
示例#25
0
  public void scale(float x, float y, float z, boolean updateLocal) {
    activate();
    // Set unit scale
    Matrix4 t = modelInstance.transform;
    Matrix4 mat_scale = new Matrix4();
    Vector3 s = new Vector3();
    t.getScale(s);
    mat_scale.scl(1 / s.x, 1 / s.y, 1 / s.z);
    t.mul(mat_scale);

    // Set target scale
    mat_scale.idt();
    mat_scale.scl(x, y, z);
    t.mul(mat_scale);

    // Relevant bullet body update
    CollisionShape cs = body.getCollisionShape();
    cs.setLocalScaling(new Vector3f(x, y, z));
    if (body.isInWorld() && body.isStaticOrKinematicObject()) scene.world.updateSingleAabb(body);

    // Child propagation
    Vector3f ps = scale();
    Matrix4f pt = transform();
    Matrix4f ct = new Matrix4f();
    Matrix4f ms = new Matrix4f();
    ms.setIdentity();
    ms.m00 = ps.x;
    ms.m11 = ps.y;
    ms.m22 = ps.z;
    pt.mul(ms);

    for (GameObject c : children) {
      c.scale(scale().mul(c.localScale), false);
      ct.mul(pt, c.localTransform);
      c.transform(ct, false);
    }

    if (parent != null && updateLocal) {
      updateLocalScale();
    }
  }
示例#26
0
    public Vertex bake(Mesh mesh, Function<Node<?>, Matrix4f> animator) {
      // geometry
      Float totalWeight = 0f;
      Matrix4f t = new Matrix4f();
      if (mesh.getWeightMap().get(this).isEmpty()) {
        t.setIdentity();
      } else {
        for (Pair<Float, Node<Bone>> bone : mesh.getWeightMap().get(this)) {
          totalWeight += bone.getLeft();
          Matrix4f bm = animator.apply(bone.getRight());
          bm.mul(bone.getLeft());
          t.add(bm);
        }
        if (Math.abs(totalWeight) > 1e-4) t.mul(1f / totalWeight);
        else t.setIdentity();
      }

      // pos
      Vector4f pos = new Vector4f(this.pos), newPos = new Vector4f();
      pos.w = 1;
      t.transform(pos, newPos);
      Vector3f rPos = new Vector3f(newPos.x / newPos.w, newPos.y / newPos.w, newPos.z / newPos.w);

      // normal
      Vector3f rNormal = null;

      if (this.normal != null) {
        Matrix3f tm = new Matrix3f();
        t.getRotationScale(tm);
        tm.invert();
        tm.transpose();
        Vector3f normal = new Vector3f(this.normal);
        rNormal = new Vector3f();
        tm.transform(normal, rNormal);
        rNormal.normalize();
      }

      // texCoords TODO
      return new Vertex(rPos, rNormal, color, texCoords);
    }
示例#27
0
    public void run() {
      adjustToScreenSize =
          (float)
              Math.min(
                  jframe.getWidth(),
                  jframe.getHeight()); // used here, since you can change the screen-Size

      Matrix4f newTranslation = new Matrix4f();
      newTranslation.setIdentity();

      Matrix4f oldcTranslation = new Matrix4f();
      oldcTranslation = camera.getCameraMatrix();

      // world z-Axis-turn
      if (mouseWorldTurn != null) {
        newTranslation.mul(mouseWorldTurn);
        mouseWorldTurn.setIdentity();
      }

      // camera x-Axis-turn
      if (mouseTurn != null) {
        newTranslation.mul(mouseTurn);
        mouseTurn.setIdentity();
      }

      // camera movement
      if (keyMove != null) {
        newTranslation.mul(keyMove);
        keyMove.setIdentity();
      }

      newTranslation.mul(oldcTranslation);

      camera.setCameraMatrix(newTranslation);
      // something still appears to be wrong while turning

      // Trigger redrawing of the render window
      renderPanel.getCanvas().repaint();
    }
示例#28
0
 /**
  * Draws all triangles given in <code>indices</code> of the given shape. Ignores normals.
  *
  * @param shape that is about to be drawn
  * @param t accumulated transformation matrix for this shape
  */
 private void drawTrianglesSeparately(Shape shape, Matrix4f t) {
   VertexData vertexData = shape.getVertexData();
   Point4f[] positions = new Point4f[3];
   Color3f[] colors = new Color3f[3];
   Point2f[] texCoords = new Point2f[3];
   int k = 0; // keeps track of triangle
   int[] indices = vertexData.getIndices();
   for (int i = 0; i < indices.length; i++) {
     for (VertexElement ve : vertexData.getElements()) {
       Point4f p;
       switch (ve.getSemantic()) {
         case POSITION:
           p = getPointAt(ve.getData(), indices[i]);
           t.transform(p);
           positions[k] = p;
           k++; // increment k here, bc color and normal might be missing
           break;
         case COLOR:
           colors[k] = getColorAt(ve.getData(), indices[i]);
           ;
           break;
         case NORMAL:
           // dont care
           // normals[k] = getPointAt(ve, indices[i]);;
           break;
         case TEXCOORD:
           texCoords[k] = getTexCoordAt(ve.getData(), indices[i]);
           break;
       }
     }
     if (k == 3) {
       rasterizeTriangle(positions, colors, texCoords, shape.getMaterial());
       k = 0;
     }
   }
 }
示例#29
0
 public Matrix4f computeViewMatrix(
     double lat, double lon, double hEllps, double az, double ha, Matrix4f mat) {
   if (mat == null) mat = new Matrix4f();
   if (globe != null)
     globe.getEllipsoid().computeSurfaceTransform(lat, lon, hEllps, az, ha, mat, origin);
   else mat.setIdentity();
   /*
   if (globe != null) {
     globe.getEllipsoid().toCartesian(lat, lon, hEllps, eye);
     eyeVector.set((float)(eye.x - origin.x),
                   (float)(eye.y - origin.y),
                   (float)(eye.z - origin.z));
   }
   else
     eyeVector.set(0,0,0);
   if (mat == null) mat = new Matrix4f();
   mat.set(eyeVector);
   workTrans.rotZ((float)(Math.PI/2.+lon)); mat.mul(workTrans);
   workTrans.rotX((float)(Math.PI/2.-lat)); mat.mul(workTrans);
   workTrans.rotZ((float)(-az));            mat.mul(workTrans);
   workTrans.rotX((float)(Math.PI/2.+ha));  mat.mul(workTrans);
    */
   return mat;
 }
示例#30
0
 /** The main rendering method. You will need to implement this to draw 3D objects. */
 private void draw(RenderItem renderItem) {
   Matrix4f t = new Matrix4f(mergedDisplayMatrix);
   t.mul(renderItem.getT());
   drawTrianglesSeparately(renderItem.getShape(), t);
   // drawDotty(renderItem.getShape(), t);
 }