// segment coordinations of this ellipse
  private float[] segments() {
    float a = M_PI / 2;
    int segs = (int) ((rx + ry) / 60 * 20);
    if (segs < 20) segs = 20;
    float coef = 2.0f * M_PI / segs;

    float vertices[] = new float[2 * (segs + 1 + (super.isSolid() ? 1 : 0))];

    float rads, distance, angle, j, k;
    for (int i = 0; i <= segs; ++i) {
      rads = i * coef;
      float xd = FloatMath.sin(rads) * rx;
      float yd = FloatMath.cos(rads) * ry;
      distance = FloatMath.sqrt(xd * xd + yd * yd);
      angle = (float) Math.atan2(FloatMath.sin(rads) * rx, FloatMath.cos(rads) * ry);
      j = distance * FloatMath.cos(angle + a) + center.x;
      k = distance * FloatMath.sin(angle + a) + center.y;

      vertices[i * 2] = j;
      vertices[i * 2 + 1] = k;
    }
    if (super.isSolid()) {
      vertices[(segs + 1) * 2] = center.x;
      vertices[(segs + 1) * 2 + 1] = center.y;
    }
    return vertices;
  }
 /**
  * Rotates p1 around p2 by angle degrees.
  *
  * @param p1
  * @param p2
  * @param angle
  */
 public void rotate(PointF p1, PointF p2, float angle) {
   float px = p1.x;
   float py = p1.y;
   float ox = p2.x;
   float oy = p2.y;
   p1.x = (FloatMath.cos(angle) * (px - ox) - FloatMath.sin(angle) * (py - oy) + ox);
   p1.y = (FloatMath.sin(angle) * (px - ox) + FloatMath.cos(angle) * (py - oy) + oy);
 }
  private void updateFromRaDec(float ra, float dec) {
    float raRadians = ra * Geometry.DEGREES_TO_RADIANS;
    float decRadians = dec * Geometry.DEGREES_TO_RADIANS;

    this.x = FloatMath.cos(raRadians) * FloatMath.cos(decRadians);
    this.y = FloatMath.sin(raRadians) * FloatMath.cos(decRadians);
    this.z = FloatMath.sin(decRadians);
  }
Esempio n. 4
0
  private float[] getRotationMatrixFromOrientation(float[] o) {
    float[] xM = new float[9];
    float[] yM = new float[9];
    float[] zM = new float[9];

    float sinX = FloatMath.sin(o[1]);
    float cosX = FloatMath.cos(o[1]);
    float sinY = FloatMath.sin(o[2]);
    float cosY = FloatMath.cos(o[2]);
    float sinZ = FloatMath.sin(o[0]);
    float cosZ = FloatMath.cos(o[0]);

    // rotation about x-axis (pitch)
    xM[0] = 1.0f;
    xM[1] = 0.0f;
    xM[2] = 0.0f;
    xM[3] = 0.0f;
    xM[4] = cosX;
    xM[5] = sinX;
    xM[6] = 0.0f;
    xM[7] = -sinX;
    xM[8] = cosX;

    // rotation about y-axis (roll)
    yM[0] = cosY;
    yM[1] = 0.0f;
    yM[2] = sinY;
    yM[3] = 0.0f;
    yM[4] = 1.0f;
    yM[5] = 0.0f;
    yM[6] = -sinY;
    yM[7] = 0.0f;
    yM[8] = cosY;

    // rotation about z-axis (azimuth)
    zM[0] = cosZ;
    zM[1] = sinZ;
    zM[2] = 0.0f;
    zM[3] = -sinZ;
    zM[4] = cosZ;
    zM[5] = 0.0f;
    zM[6] = 0.0f;
    zM[7] = 0.0f;
    zM[8] = 1.0f;

    // rotation order is y, x, z (roll, pitch, azimuth)
    float[] resultMatrix = matrixMultiplication(xM, yM);
    resultMatrix = matrixMultiplication(zM, resultMatrix);
    return resultMatrix;
  }
Esempio n. 5
0
 /** Call this onStart */
 public void onStart() {
   // Counter-clockwise rotation at -90 degrees around the x-axis
   float angleX = -90 * toRadians;
   xAxisRotation.set(
       1f,
       0f,
       0f,
       0f,
       FloatMath.cos(angleX),
       -FloatMath.sin(angleX),
       0f,
       FloatMath.sin(angleX),
       FloatMath.cos(angleX));
 }
Esempio n. 6
0
  /**
   * Calculate3 d position.
   *
   * @param child the child
   * @param diameter the diameter
   * @param angleOffset the angle offset
   */
  private void Calculate3DPosition(CarouselItemView child, int diameter, float angleOffset) {

    angleOffset = angleOffset * (float) (Math.PI / 180.0f);

    float x =
        -(float) (diameter / 2 * android.util.FloatMath.sin(angleOffset))
            + diameter / 2
            - child.getWidth() / 2;
    float z = diameter / 2 * (1.0f - (float) android.util.FloatMath.cos(angleOffset));
    float y = -getHeight() / 2 + (float) (z * android.util.FloatMath.sin(mTheta));

    child.setItemX(x);
    child.setItemZ(z);
    child.setItemY(y);
  }
Esempio n. 7
0
  /**
   * This function is borrowed from the Android reference at
   * http://developer.android.com/reference/android/hardware/SensorEvent.html#values It calculates a
   * rotation vector from the gyroscope angular speed values.
   */
  private void getRotationVectorFromGyro(
      float[] gyroValues, float[] deltaRotationVector, float timeFactor) {
    float[] normValues = new float[3];

    // Calculate the angular speed of the sample
    float omegaMagnitude =
        FloatMath.sqrt(
            gyroValues[0] * gyroValues[0]
                + gyroValues[1] * gyroValues[1]
                + gyroValues[2] * gyroValues[2]);

    // Normalize the rotation vector if it's big enough to get the axis
    if (omegaMagnitude > EPSILON) {
      normValues[0] = gyroValues[0] / omegaMagnitude;
      normValues[1] = gyroValues[1] / omegaMagnitude;
      normValues[2] = gyroValues[2] / omegaMagnitude;
    }

    // Integrate around this axis with the angular speed by the timestep
    // in order to get a delta rotation from this sample over the timestep
    // We will convert this axis-angle representation of the delta rotation
    // into a quaternion before turning it into the rotation matrix.
    float thetaOverTwo = omegaMagnitude * timeFactor;
    float sinThetaOverTwo = (float) FloatMath.sin(thetaOverTwo);
    float cosThetaOverTwo = (float) FloatMath.cos(thetaOverTwo);
    deltaRotationVector[0] = sinThetaOverTwo * normValues[0];
    deltaRotationVector[1] = sinThetaOverTwo * normValues[1];
    deltaRotationVector[2] = sinThetaOverTwo * normValues[2];
    deltaRotationVector[3] = cosThetaOverTwo;
  }
 @Override
 public float getPercentageDone(
     float pSecondsElapsed, final float pDuration, final float pMinValue, final float pMaxValue) {
   float s;
   float p = 0.0f;
   float a = 0.0f;
   if (pSecondsElapsed == 0) {
     return pMinValue;
   }
   if ((pSecondsElapsed /= pDuration) == 1) {
     return pMinValue + pMaxValue;
   }
   if (p == 0) {
     p = pDuration * 0.3f;
   }
   if (a == 0 || (pMaxValue > 0 && a < pMaxValue) || (pMaxValue < 0 && a < -pMaxValue)) {
     a = pMaxValue;
     s = p / 4;
   } else {
     s = (float) (p / PI_TWICE * Math.asin(pMaxValue / a));
   }
   return (float)
       (-(a
               * Math.pow(2, 10 * (pSecondsElapsed -= 1))
               * FloatMath.sin((pSecondsElapsed * pDuration - s) * PI_TWICE / p))
           + pMinValue);
 }
Esempio n. 9
0
 public void makePointCloud(float innerRadius, float outerRadius) {
   if (innerRadius == 0) {
     Log.w(TAG, "Must specify an inner radius");
     return;
   }
   mOuterRadius = outerRadius;
   mPointCloud.clear();
   final float pointAreaRadius = (outerRadius - innerRadius);
   final float ds = (2.0f * PI * innerRadius / INNER_POINTS);
   final int bands = (int) Math.round(pointAreaRadius / ds);
   final float dr = pointAreaRadius / bands;
   float r = innerRadius;
   for (int b = 0; b <= bands; b++, r += dr) {
     float circumference = 2.0f * PI * r;
     final int pointsInBand = (int) (circumference / ds);
     float eta = PI / 2.0f;
     float dEta = 2.0f * PI / pointsInBand;
     for (int i = 0; i < pointsInBand; i++) {
       float x = r * FloatMath.cos(eta);
       float y = r * FloatMath.sin(eta);
       eta += dEta;
       mPointCloud.add(new Point(x, y, r));
     }
   }
 }
Esempio n. 10
0
    @Override
    protected void onDraw(Canvas canvas) {
      if (bitmap != null) {
        canvas.drawBitmap(bitmap, null, rect, null);
        float hueInPiInterval = colorHsv[0] / 180f * (float) Math.PI;

        selectedPoint.x =
            rect.left
                + (int)
                    (-FloatMath.cos(hueInPiInterval) * colorHsv[1] * innerRadius + middleSize / 2);
        selectedPoint.y =
            rect.top
                + (int)
                    (-FloatMath.sin(hueInPiInterval) * colorHsv[1] * innerRadius + middleSize / 2);

        canvas.drawLine(
            selectedPoint.x - pointerLength,
            selectedPoint.y,
            selectedPoint.x + pointerLength,
            selectedPoint.y,
            pointerPaint);
        canvas.drawLine(
            selectedPoint.x,
            selectedPoint.y - pointerLength,
            selectedPoint.x,
            selectedPoint.y + pointerLength,
            pointerPaint);
      }
    }
Esempio n. 11
0
  public void rotateZ(float angle) {
    float cosRY = FloatMath.cos(angle);
    float sinRY = FloatMath.sin(angle);

    _temp.setAll(this.x, this.y, this.z);

    this.x = (_temp.x * cosRY) - (_temp.y * sinRY);
    this.y = (_temp.x * sinRY) + (_temp.y * cosRY);
  }
Esempio n. 12
0
  /* update our player position and the camera position */
  public void updatePlayer() {
    this.theta = this.theta + WallOffEngine.accelerometer.getYTheta();
    this.x_pos = this.x_pos - FloatMath.cos(this.theta) * WallOffEngine.player_speed;
    this.z_pos = this.z_pos - FloatMath.sin(this.theta) * WallOffEngine.player_speed;

    if (this.theta >= WallOffEngine.PI * 2) this.theta = this.theta - WallOffEngine.PI * 2;
    else if (this.theta < 0) this.theta = this.theta + WallOffEngine.PI * 2;

    this.m_tail.addNewPoint(this.x_pos, this.z_pos);
  }
 private static float transformAngle(Matrix paramMatrix, float paramFloat) {
   float[] arrayOfFloat = new float[2];
   arrayOfFloat[0] = FloatMath.sin(paramFloat);
   arrayOfFloat[1] = (-FloatMath.cos(paramFloat));
   paramMatrix.mapVectors(arrayOfFloat);
   float f = (float) Math.atan2(arrayOfFloat[0], -arrayOfFloat[1]);
   if (f < -1.570796326794897D) f = (float) (3.141592653589793D + f);
   do return f;
   while (f <= 1.570796326794897D);
   return (float) (f - 3.141592653589793D);
 }
Esempio n. 14
0
  public Vector2 rotate(float angle) {
    float rad = angle * TO_RADIANS;
    float cos = FloatMath.cos(rad);
    float sin = FloatMath.sin(rad);

    float newX = this.x * cos - this.y * sin;
    float newY = this.x * sin + this.y * cos;

    this.x = newX;
    this.y = newY;

    return this;
  }
Esempio n. 15
0
  boolean intersects(RectF tRect, float tRot, RectF sRect, float sRot) {
    if (Math.abs(tRot) < Math.PI / 15 && Math.abs(sRot) < Math.PI / 15) {
      return RectF.intersects(tRect, sRect);
    }
    float dist =
        FloatMath.sqrt(
            sqr(tRect.centerX() - sRect.centerX()) + sqr(tRect.centerY() - sRect.centerY()));
    if (dist < 3) {
      return true;
    }

    // difference close to 90/270 degrees
    if (Math.abs(Math.cos(tRot - sRot)) < 0.3) {
      // rotate one rectangle to 90 degrees
      tRot += Math.PI / 2;
      float l = tRect.centerX() - tRect.height() / 2;
      float t = tRect.centerY() - tRect.width() / 2;
      tRect = new RectF(l, t, l + tRect.height(), t + tRect.width());
    }

    // determine difference close to 180/0 degrees
    if (Math.abs(FloatMath.sin(tRot - sRot)) < 0.3) {
      // rotate t box
      // (calculate offset for t center suppose we rotate around s center)
      float diff =
          (float)
              (-Math.atan2(tRect.centerX() - sRect.centerX(), tRect.centerY() - sRect.centerY())
                  + Math.PI / 2);
      diff -= sRot;
      float left = sRect.centerX() + dist * FloatMath.cos(diff) - tRect.width() / 2;
      float top = sRect.centerY() - dist * FloatMath.sin(diff) - tRect.height() / 2;
      RectF nRect = new RectF(left, top, left + tRect.width(), top + tRect.height());
      return RectF.intersects(nRect, sRect);
    }

    // TODO other cases not covered
    return RectF.intersects(tRect, sRect);
  }
Esempio n. 16
0
 public static float[] rotateAroundCenter(
     final float[] array, final float n, final float n2, final float n3) {
   if (n != 0.0f) {
     final float degToRad = degToRad(n);
     final float sin = FloatMath.sin(degToRad);
     final float cos = FloatMath.cos(degToRad);
     for (int i = -2 + array.length; i >= 0; i -= 2) {
       final float n4 = array[i];
       final float n5 = array[i + 1];
       array[i] = n2 + (cos * (n4 - n2) - sin * (n5 - n3));
       array[i + 1] = n3 + (sin * (n4 - n2) + cos * (n5 - n3));
     }
   }
   return array;
 }
Esempio n. 17
0
    @Override
    public void update(float deltaTime) {
      List<TouchEvent> touchEvents = game.getInput().getTouchEvents();
      game.getInput().getKeyEvents();

      int len = touchEvents.size();
      for (int i = 0; i < len; i++) {
        TouchEvent event = touchEvents.get(i);

        camera.touchToWorld(touchPos.set(event.x, event.y));

        cannon.angle = touchPos.sub(cannon.position).angle();

        if (event.type == TouchEvent.TOUCH_UP) {
          float radians = cannon.angle * Vector2.TO_RADIANS;
          float ballSpeed = touchPos.len() * 2;
          ball.position.set(cannon.position);

          ball.velocity.x = FloatMath.cos(radians) * ballSpeed;
          ball.velocity.y = FloatMath.sin(radians) * ballSpeed;

          ball.bounds.lowerLeft.set(ball.position.x - 0.1f, ball.position.y - 0.1f);
        }
      }

      ball.velocity.add(gravity.x * deltaTime, gravity.y * deltaTime);
      ball.position.add(ball.velocity.x * deltaTime, ball.velocity.y * deltaTime);
      ball.bounds.lowerLeft.add(ball.velocity.x * deltaTime, ball.velocity.y * deltaTime);

      List<GameObject> colliders = grid.getPotentialColliders(ball);
      len = colliders.size();

      for (int i = 0; i < len; i++) {
        GameObject collider = colliders.get(i);
        if (OverlapTester.overlapRectangle(ball.bounds, collider.bounds)) {
          grid.removeObject(collider);
          targets.remove(collider);
        }
      }

      if (ball.position.y > 0) {
        camera.position.set(ball.position);
        camera.zoom = 1 + ball.position.y / WORLD_HEIGHT;
      } else {
        camera.position.set(WORLD_WIDTH / 2, WORLD_HEIGHT / 2);
        camera.zoom = 1;
      }
    }
Esempio n. 18
0
  /** @return if map could be replaced */
  public void generateNewBitmapNative(
      RenderingContext rc,
      NativeOsmandLibrary library,
      NativeSearchResult searchResultHandler,
      Bitmap bmp,
      RenderingRuleSearchRequest render,
      final List<IMapDownloaderCallback> notifyList) {
    long now = System.currentTimeMillis();
    if (rc.width > 0 && rc.height > 0 && searchResultHandler != null) {
      // init rendering context
      rc.tileDivisor = (int) (1 << (31 - rc.zoom));
      rc.cosRotateTileSize = FloatMath.cos((float) Math.toRadians(rc.rotate)) * TILE_SIZE;
      rc.sinRotateTileSize = FloatMath.sin((float) Math.toRadians(rc.rotate)) * TILE_SIZE;
      try {
        if (Looper.getMainLooper() != null && library.useDirectRendering()) {
          final Handler h = new Handler(Looper.getMainLooper());
          notifyListenersWithDelay(rc, notifyList, h);
        }

        // Native library will decide on it's own best way of rendering
        // If res.bitmapBuffer is null, it indicates that rendering was done directly to
        // memory of passed bitmap, but this is supported only on Android >= 2.2
        final NativeLibrary.RenderingGenerationResult res =
            library.generateRendering(rc, searchResultHandler, bmp, bmp.hasAlpha(), render);
        rc.ended = true;
        notifyListeners(notifyList);
        long time = System.currentTimeMillis() - now;
        rc.renderingDebugInfo =
            String.format(
                "Rendering: %s ms  (%s text)\n"
                    + "(%s points, %s points inside, %s of %s objects visible)\n", //$NON-NLS-1$
                time,
                rc.textRenderingTime,
                rc.pointCount,
                rc.pointInsideCount,
                rc.visible,
                rc.allObjects);

        // See upper note
        if (res.bitmapBuffer != null) {
          bmp.copyPixelsFromBuffer(res.bitmapBuffer);
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
Esempio n. 19
0
  @Override
  public void update(float deltaTime) {

    angle += wheelAngle;

    if (angle > 2 * Math.PI) angle = 0;
    if (angle < -2 * Math.PI) angle = 0;

    resultantForce = engineForce * 10 + roadResistence + airResistence * getSpeed() * getSpeed();

    acc = resultantForce / weight;

    this.setSpeed(this.getSpeed() + acc * deltaTime);

    this.position.x += FloatMath.cos(angle) * getSpeed();
    this.position.y += FloatMath.sin(angle) * getSpeed();
  }
 void setVolume(float vol) {
   volume = vol;
   // calculates left/right volumes from pan-value (constant panning law)
   // see: Curtis Roads: Computer Music Tutorial p 460
   // thanks to jasch
   float angle = pan * 0.7853981633974483f; // in radians from -45. to +45.
   float cosAngle = FloatMath.cos(angle);
   float sinAngle = FloatMath.sin(angle);
   leftVolume =
       (float) ((cosAngle - sinAngle) * 0.7071067811865475) * vol; // multiplied by sqrt(2)/2
   rightVolume =
       (float) ((cosAngle + sinAngle) * 0.7071067811865475) * vol; // multiplied by sqrt(2)/2
   if (stream) {
     if (player != null) player.setVolume(leftVolume, rightVolume);
   } else if (streamID != -1) {
     pool.setVolume(streamID, leftVolume, rightVolume);
   }
 }
Esempio n. 21
0
File: Unit.java Progetto: talah/BBTH
 protected void onDead() {
   for (int i = 0; i < 10 * getRadius(); ++i) {
     float angle = MathUtils.randInRange(0, 2 * MathUtils.PI);
     float sin = FloatMath.sin(angle);
     float cos = FloatMath.cos(angle);
     float xVel = MathUtils.randInRange(25.f, 50.f) * cos;
     float yVel = MathUtils.randInRange(25.f, 50.f) * sin;
     particleSystem
         .createParticle()
         .line()
         .velocity(xVel * getRadius() * .25f, yVel * getRadius() * .25f)
         .angle(angle)
         .shrink(0.1f, 0.15f)
         .radius(getRadius() * 1.5f)
         .width(getRadius() / 2f)
         .position(getX() + sin * 2f, getY() + cos * 2f)
         .color(team.getRandomShade());
   }
 }
Esempio n. 22
0
 MyLocationCircle() {
   // Create circle vertex array for later use in drawing
   ByteBuffer byteBuffer =
       ByteBuffer.allocateDirect((NR_OF_CIRCLE_VERTS + 2) * 3 * Float.SIZE / 8);
   byteBuffer.order(ByteOrder.nativeOrder());
   circleVertBuf = byteBuffer.asFloatBuffer();
   float degreesPerVert = 360.0f / NR_OF_CIRCLE_VERTS;
   circleVertBuf.put(0);
   circleVertBuf.put(0);
   circleVertBuf.put(0);
   for (float tsj = 0; tsj < 360; tsj += degreesPerVert) {
     circleVertBuf.put(android.util.FloatMath.cos(tsj * Const.DEG_TO_RAD));
     circleVertBuf.put(android.util.FloatMath.sin(tsj * Const.DEG_TO_RAD));
     circleVertBuf.put(0);
   }
   circleVertBuf.put(1);
   circleVertBuf.put(0);
   circleVertBuf.put(0);
   circleVertBuf.position(0);
 }
Esempio n. 23
0
 @Override
 public float calc(float t, final float b, final float c, final float d) {
   float s;
   float p = 0.0f;
   float a = 0.0f;
   if (t == 0) {
     return b;
   }
   if ((t /= d) == 1) {
     return b + c;
   }
   if (p == 0) {
     p = d * 0.3f;
   }
   if (a == 0 || (c > 0 && a < c) || (c < 0 && a < -c)) {
     a = c;
     s = p / 4;
   } else {
     s = (float) (p / _2PI * Math.asin(c / a));
   }
   return (float) (-(a * Math.pow(2, 10 * (t -= 1)) * FloatMath.sin((t * d - s) * _2PI / p)) + b);
 }
Esempio n. 24
0
 // We want the duration of the page snap animation to be influenced by the distance that
 // the screen has to travel, however, we don't want this duration to be effected in a
 // purely linear fashion. Instead, we use this method to moderate the effect that the distance
 // of travel has on the overall snap duration.
 float distanceInfluenceForSnapDuration(float f) {
   f -= 0.5f; // center the values about 0.
   f *= 0.3f * Math.PI / 2.0f;
   return (float) FloatMath.sin(f);
 }
Esempio n. 25
0
  // draw path 96x96
  public static void calcTurnPath(Path pathForTurn, TurnType turnType, Matrix transform) {
    if (turnType == null) {
      return;
    }
    pathForTurn.reset();

    int c = 48;
    int w = 16;
    pathForTurn.moveTo(c, 94);
    float sarrowL = 30; // side of arrow
    float harrowL = (float) Math.sqrt(2) * sarrowL; // hypotenuse of arrow
    float spartArrowL = (float) ((sarrowL - w / Math.sqrt(2)) / 2);
    float hpartArrowL = (float) (harrowL - w) / 2;

    if (TurnType.C.equals(turnType.getValue())) {
      int h = 65;

      pathForTurn.rMoveTo(w / 2, 0);
      pathForTurn.rLineTo(0, -h);
      pathForTurn.rLineTo(hpartArrowL, 0);
      pathForTurn.rLineTo(-harrowL / 2, -harrowL / 2); // center
      pathForTurn.rLineTo(-harrowL / 2, harrowL / 2);
      pathForTurn.rLineTo(hpartArrowL, 0);
      pathForTurn.rLineTo(0, h);
    } else if (TurnType.TR.equals(turnType.getValue()) || TurnType.TL.equals(turnType.getValue())) {
      int b = TurnType.TR.equals(turnType.getValue()) ? 1 : -1;
      int h = 36;
      float quadShiftX = 22;
      float quadShiftY = 22;

      pathForTurn.rMoveTo(-b * 8, 0);
      pathForTurn.rLineTo(0, -h);
      pathForTurn.rQuadTo(0, -quadShiftY, b * quadShiftX, -quadShiftY);
      pathForTurn.rLineTo(0, hpartArrowL);
      pathForTurn.rLineTo(b * harrowL / 2, -harrowL / 2); // center
      pathForTurn.rLineTo(-b * harrowL / 2, -harrowL / 2);
      pathForTurn.rLineTo(0, hpartArrowL);
      pathForTurn.rQuadTo(-b * (quadShiftX + w), 0, -b * (quadShiftX + w), quadShiftY + w);
      pathForTurn.rLineTo(0, h);
    } else if (TurnType.TSLR.equals(turnType.getValue())
        || TurnType.TSLL.equals(turnType.getValue())) {
      int b = TurnType.TSLR.equals(turnType.getValue()) ? 1 : -1;
      int h = 40;
      int quadShiftY = 22;
      float quadShiftX = (float) (quadShiftY / (1 + Math.sqrt(2)));
      float nQuadShiftX = (sarrowL - 2 * spartArrowL) - quadShiftX - w;
      float nQuadShifty = quadShiftY + (sarrowL - 2 * spartArrowL);

      pathForTurn.rMoveTo(-b * 4, 0);
      pathForTurn.rLineTo(0, -h /* + partArrowL */);
      pathForTurn.rQuadTo(
          0,
          -quadShiftY + quadShiftX /*- partArrowL*/,
          b * quadShiftX,
          -quadShiftY /*- partArrowL*/);
      pathForTurn.rLineTo(b * spartArrowL, spartArrowL);
      pathForTurn.rLineTo(0, -sarrowL); // center
      pathForTurn.rLineTo(-b * sarrowL, 0);
      pathForTurn.rLineTo(b * spartArrowL, spartArrowL);
      pathForTurn.rQuadTo(b * nQuadShiftX, -nQuadShiftX, b * nQuadShiftX, nQuadShifty);
      pathForTurn.rLineTo(0, h);
    } else if (TurnType.TSHR.equals(turnType.getValue())
        || TurnType.TSHL.equals(turnType.getValue())) {
      int b = TurnType.TSHR.equals(turnType.getValue()) ? 1 : -1;
      int h = 45;
      float quadShiftX = 22;
      float quadShiftY = -(float) (quadShiftX / (1 + Math.sqrt(2)));
      float nQuadShiftX = -(sarrowL - 2 * spartArrowL) - quadShiftX - w;
      float nQuadShiftY = -quadShiftY + (sarrowL - 2 * spartArrowL);

      pathForTurn.rMoveTo(-b * 8, 0);
      pathForTurn.rLineTo(0, -h);
      pathForTurn.rQuadTo(0, -(quadShiftX - quadShiftY), b * quadShiftX, quadShiftY);
      pathForTurn.rLineTo(-b * spartArrowL, spartArrowL);
      pathForTurn.rLineTo(b * sarrowL, 0); // center
      pathForTurn.rLineTo(0, -sarrowL);
      pathForTurn.rLineTo(-b * spartArrowL, spartArrowL);
      pathForTurn.rCubicTo(
          b * nQuadShiftX / 2,
          nQuadShiftX / 2,
          b * nQuadShiftX,
          nQuadShiftX / 2,
          b * nQuadShiftX,
          nQuadShiftY);
      pathForTurn.rLineTo(0, h);
    } else if (TurnType.TU.equals(turnType.getValue())) {
      int h = 54;
      float quadShiftX = 13;
      float quadShiftY = 13;

      pathForTurn.rMoveTo(28, 0);
      pathForTurn.rLineTo(0, -h);
      pathForTurn.rQuadTo(0, -(quadShiftY + w), -(quadShiftX + w), -(quadShiftY + w));
      pathForTurn.rQuadTo(-(quadShiftX + w), 0, -(quadShiftX + w), (quadShiftY + w));
      pathForTurn.rLineTo(-hpartArrowL, 0);
      pathForTurn.rLineTo(harrowL / 2, harrowL / 2); // center
      pathForTurn.rLineTo(harrowL / 2, -harrowL / 2);
      pathForTurn.rLineTo(-hpartArrowL, 0);
      pathForTurn.rQuadTo(0, -quadShiftX, quadShiftX, -quadShiftY);
      pathForTurn.rQuadTo(quadShiftX, 0, quadShiftX, quadShiftY);
      pathForTurn.rLineTo(0, h);
    } else if (turnType != null && turnType.isRoundAbout()) {
      float t = turnType.getTurnAngle();
      if (t >= 170 && t < 220) {
        t = 220;
      } else if (t > 160 && t < 170) {
        t = 160;
      }
      float sweepAngle = (t - 360) - 180;
      if (sweepAngle < -360) {
        sweepAngle += 360;
      }
      float r1 = 32f;
      float r2 = 24f;
      float angleToRot = 0.3f;

      pathForTurn.moveTo(48, 48 + r1 + 8);
      pathForTurn.lineTo(48, 48 + r1);
      RectF r = new RectF(48 - r1, 48 - r1, 48 + r1, 48 + r1);
      pathForTurn.arcTo(r, 90, sweepAngle);
      float angleRad = (float) ((180 + sweepAngle) * Math.PI / 180f);

      pathForTurn.lineTo(
          48 + (r1 + 4) * FloatMath.sin(angleRad), 48 - (r1 + 4) * FloatMath.cos(angleRad));
      pathForTurn.lineTo(
          48 + (r1 + 6) * FloatMath.sin(angleRad + angleToRot / 2),
          48 - (r1 + 6) * FloatMath.cos(angleRad + angleToRot / 2));
      pathForTurn.lineTo(
          48 + (r1 + 12) * FloatMath.sin(angleRad - angleToRot / 2),
          48 - (r1 + 12) * FloatMath.cos(angleRad - angleToRot / 2));
      pathForTurn.lineTo(
          48 + (r1 + 6) * FloatMath.sin(angleRad - 3 * angleToRot / 2),
          48 - (r1 + 6) * FloatMath.cos(angleRad - 3 * angleToRot / 2));
      pathForTurn.lineTo(
          48 + (r1 + 4) * FloatMath.sin(angleRad - angleToRot),
          48 - (r1 + 4) * FloatMath.cos(angleRad - angleToRot));
      pathForTurn.lineTo(
          48 + r2 * FloatMath.sin(angleRad - angleToRot),
          48 - r2 * FloatMath.cos(angleRad - angleToRot));

      r.set(48 - r2, 48 - r2, 48 + r2, 48 + r2);
      pathForTurn.arcTo(r, 360 + sweepAngle + 90, -sweepAngle);
      pathForTurn.lineTo(40, 48 + r2);
      pathForTurn.lineTo(40, 48 + r1 + 8);
      pathForTurn.close();
    }
    pathForTurn.close();
    if (transform != null) {
      pathForTurn.transform(transform);
    }
  }
Esempio n. 26
0
  static void write(BufferedWriter out, DistoXNum num, DrawingCommandManager plot, long type) {
    VERSION = TDSetting.mAcadVersion;

    float scale = TDSetting.mDxfScale;
    int handle = 0;
    float xmin = 10000f, xmax = -10000f, ymin = 10000f, ymax = -10000f;
    // compute BBox
    for (ICanvasCommand cmd : plot.getCommands()) {
      if (cmd.commandType() != 0) continue;
      DrawingPath p = (DrawingPath) cmd;

      if (p.mType == DrawingPath.DRAWING_PATH_LINE) {
        DrawingLinePath lp = (DrawingLinePath) p;
        if (lp.lineType() == DrawingBrushPaths.mLineLib.mLineWallIndex) {
          // ArrayList< LinePoint > pts = lp.mPoints;
          // for ( LinePoint pt : pts )
          for (LinePoint pt = lp.mFirst; pt != null; pt = pt.mNext) {
            if (pt.mX < xmin) xmin = pt.mX;
            if (pt.mX > xmax) xmax = pt.mX;
            if (pt.mY < ymin) ymin = pt.mY;
            if (pt.mY > ymax) ymax = pt.mY;
          }
        }
      } else if (p.mType == DrawingPath.DRAWING_PATH_POINT) {
        DrawingPointPath pp = (DrawingPointPath) p;
        if (pp.cx < xmin) xmin = pp.cx;
        if (pp.cx > xmax) xmax = pp.cx;
        if (pp.cy < ymin) ymin = pp.cy;
        if (pp.cy > ymax) ymax = pp.cy;
      } else if (p.mType == DrawingPath.DRAWING_PATH_STATION) {
        DrawingStationPath st = (DrawingStationPath) p;
        if (st.cx < xmin) xmin = st.cx;
        if (st.cx > xmax) xmax = st.cx;
        if (st.cy < ymin) ymin = st.cy;
        if (st.cy > ymax) ymax = st.cy;
      }
    }
    xmin *= scale;
    xmax *= scale;
    ymin *= scale;
    ymax *= scale;

    // Log.v("DistoX", "DXF X " + xmin + " " + xmax + " Y " + ymin + " " + ymax );

    try {
      // header
      writeComment(out, "DXF created by TopoDroid v. " + TopoDroidApp.VERSION);
      writeSection(out, "HEADER");

      xmin -= 2f;
      ymax += 2f;

      writeString(out, 9, "$ACADVER");
      String ACAD_VERSION = (VERSION == 13) ? "AC1012" : "AC1009";
      writeString(out, 1, ACAD_VERSION);

      if (VERSION >= 13) {
        writeString(out, 9, "$DWGCODEPAGE");
        writeString(out, 3, "ANSI_1251");
      }

      writeString(out, 9, "$INSBASE");
      {
        StringWriter sw1 = new StringWriter();
        PrintWriter pw1 = new PrintWriter(sw1);
        printXYZ(pw1, 0.0f, 0.0f, 0.0f); // FIXME (0,0,0)
        printString(pw1, 9, "$EXTMIN");
        printXYZ(pw1, xmin, -ymax, 0.0f);
        printString(pw1, 9, "$EXTMAX");
        printXYZ(pw1, xmax * scale, -ymin * scale, 0.0f);
        out.write(sw1.getBuffer().toString());
      }
      writeEndSection(out);

      String lt_continuous = "CONTINUOUS";
      writeSection(out, "TABLES");
      {
        if (VERSION >= 13) {
          ++handle;
          writeBeginTable(out, "VPORT", handle, 1);
          {
            writeString(out, 0, "VPORT");
            ++handle;
            writeAcDb(out, handle, "AcDbSymbolTableRecord", "AcDbViewportTableRecord");
            writeString(out, 2, "MyViewport");
            writeInt(out, 70, 0);
            writeString(out, 10, zero);
            writeString(out, 20, zero);
            writeString(out, 11, one);
            writeString(out, 21, one);
            writeString(out, 12, zero);
            writeString(out, 22, zero);
            writeString(out, 13, zero);
            writeString(out, 23, zero);
            writeString(out, 14, half);
            writeString(out, 24, half);
            writeString(out, 15, half);
            writeString(out, 25, half);
            writeString(out, 16, zero);
            writeString(out, 26, zero);
            writeString(out, 36, one);
            writeString(out, 17, zero);
            writeString(out, 27, zero);
            writeString(out, 37, zero);
            writeString(out, 40, zero);
            writeString(out, 41, "2.0");
            writeString(out, 42, "50.0");
          }
          writeEndTable(out);
        }

        ++handle;
        writeBeginTable(out, "LTYPE", handle, 1);
        {
          // int flag = 64;
          writeString(out, 0, "LTYPE");
          ++handle;
          writeAcDb(out, handle, "AcDbSymbolTableRecord", "AcDbLinetypeTableRecord");
          writeString(out, 2, lt_continuous);
          writeInt(out, 70, 64);
          writeString(out, 3, "Solid line");
          writeInt(out, 72, 65);
          writeInt(out, 73, 0);
          writeString(out, 40, zero);
        }
        writeEndTable(out);

        SymbolLineLibrary linelib = DrawingBrushPaths.mLineLib;
        SymbolAreaLibrary arealib = DrawingBrushPaths.mAreaLib;
        int nr_layers = 6 + linelib.mSymbolNr + arealib.mSymbolNr;
        ++handle;
        writeBeginTable(out, "LAYER", handle, nr_layers);
        {
          StringWriter sw2 = new StringWriter();
          PrintWriter pw2 = new PrintWriter(sw2);

          // 2 layer name, 70 flag (64), 62 color code, 6 line type
          int flag = 0;
          int color = 1;
          ++handle;
          printLayer(pw2, handle, "LEG", flag, color, lt_continuous);
          ++color;
          ++handle;
          printLayer(pw2, handle, "SPLAY", flag, color, lt_continuous);
          ++color;
          ++handle;
          printLayer(pw2, handle, "STATION", flag, color, lt_continuous);
          ++color;
          ++handle;
          printLayer(pw2, handle, "LINE", flag, color, lt_continuous);
          ++color;
          ++handle;
          printLayer(pw2, handle, "POINT", flag, color, lt_continuous);
          ++color;
          // ++handle; printLayer( pw2, handle, "AREA",    flag, color, lt_continuous ); ++color;
          ++handle;
          printLayer(pw2, handle, "REF", flag, color, lt_continuous);
          ++color;

          if (linelib != null) {
            for (Symbol line : linelib.getSymbols()) {
              String lname = "L_" + line.getThName().replace(':', '-');
              ++handle;
              printLayer(pw2, handle, lname, flag, color, lt_continuous);
              ++color;
            }
          }

          if (arealib != null) {
            for (Symbol s : arealib.getSymbols()) {
              String aname = "A_" + s.getThName().replace(':', '-');
              ++handle;
              printLayer(pw2, handle, aname, flag, color, lt_continuous);
              ++color;
            }
          }
          out.write(sw2.getBuffer().toString());
        }
        writeEndTable(out);

        if (VERSION >= 13) {
          ++handle;
          writeBeginTable(out, "STYLE", handle, 1);
          {
            writeString(out, 0, "STYLE");
            ++handle;
            writeAcDb(out, handle, "AcDbSymbolTableRecord", "AcDbTextStyleTableRecord");
            writeString(out, 2, "MyStyle"); // name
            writeInt(out, 70, 0); // flag
            writeString(out, 40, zero);
            writeString(out, 41, one);
            writeString(out, 42, one);
            writeString(out, 3, "arial.ttf"); // fonts
          }
          writeEndTable(out);
        }

        ++handle;
        writeBeginTable(out, "VIEW", handle, 0);
        writeEndTable(out);

        ++handle;
        writeBeginTable(out, "UCS", handle, 0);
        writeEndTable(out);

        if (VERSION >= 13) {
          ++handle;
          writeBeginTable(out, "STYLE", handle, 0);
          writeEndTable(out);
        }

        ++handle;
        writeBeginTable(out, "APPID", handle, 1);
        {
          writeString(out, 0, "APPID");
          ++handle;
          writeAcDb(out, handle, "AcDbSymbolTableRecord", "AcDbRegAppTableRecord");
          writeString(out, 2, "ACAD"); // applic. name
          writeInt(out, 70, 0); // flag
        }
        writeEndTable(out);

        if (VERSION >= 13) {
          ++handle;
          writeBeginTable(out, "DIMSTYLE", handle, -1);
          writeString(out, 100, "AcDbDimStyleTable");
          writeInt(out, 70, 1);
          writeEndTable(out);

          ++handle;
          writeBeginTable(out, "BLOCK_RECORD", handle, DrawingBrushPaths.mPointLib.mSymbolNr);
          {
            for (int n = 0; n < DrawingBrushPaths.mPointLib.mSymbolNr; ++n) {
              String block =
                  "P_" + DrawingBrushPaths.mPointLib.getSymbolThName(n).replace(':', '-');
              writeString(out, 0, "BLOCK_RECORD");
              ++handle;
              writeAcDb(out, handle, "AcDbSymbolTableRecord", "AcDbBlockTableRecord");
              writeString(out, 2, block);
              writeInt(out, 70, 0); // flag
            }
          }
          writeEndTable(out);
        }
      }
      writeEndSection(out);
      out.flush();

      writeSection(out, "BLOCKS");
      {
        // // 8 layer (0), 2 block name,
        for (int n = 0; n < DrawingBrushPaths.mPointLib.mSymbolNr; ++n) {
          SymbolPoint pt = (SymbolPoint) DrawingBrushPaths.mPointLib.getSymbolByIndex(n);
          String block = "P_" + pt.getThName().replace(':', '-');

          writeString(out, 0, "BLOCK");
          ++handle;
          writeAcDb(out, handle, "AcDbEntity", "AcDbBlockBegin");
          writeString(out, 8, "POINT");
          writeString(out, 2, block);
          writeInt(out, 70, 64); // flag 64 = this definition is referenced
          writeString(out, 10, "0.0");
          writeString(out, 20, "0.0");
          writeString(out, 30, "0.0");

          out.write(pt.getDxf());
          // out.write( DrawingBrushPaths.mPointLib.getPoint(n).getDxf() );

          writeString(out, 0, "ENDBLK");
          if (VERSION >= 13) {
            ++handle;
            writeAcDb(out, handle, "AcDbEntity", "AcDbBlockEnd");
            writeString(out, 8, "POINT");
          }
        }
      }
      writeEndSection(out);
      out.flush();

      writeSection(out, "ENTITIES");
      {
        float SCALE_FIX = DrawingUtil.SCALE_FIX;

        // reference
        {
          StringWriter sw9 = new StringWriter();
          PrintWriter pw9 = new PrintWriter(sw9);
          printString(pw9, 0, "LINE");
          ++handle;
          printAcDb(pw9, handle, "AcDbEntity", "AcDbLine");
          printString(pw9, 8, "REF");
          // printInt(  pw9, 39, 0 );         // line thickness
          printXYZ(pw9, xmin, -ymax, 0.0f);
          printXYZ1(pw9, (xmin + 10 * SCALE_FIX), -ymax, 0.0f);
          out.write(sw9.getBuffer().toString());
        }
        {
          StringWriter sw8 = new StringWriter();
          PrintWriter pw8 = new PrintWriter(sw8);
          printString(pw8, 0, "LINE");
          ++handle;
          printAcDb(pw8, handle, "AcDbEntity", "AcDbLine");
          printString(pw8, 8, "REF");
          // printInt(  pw8, 39, 0 );         // line thickness
          printXYZ(pw8, xmin, -ymax, 0.0f);
          printXYZ1(pw8, xmin, -ymax + 10 * SCALE_FIX, 0.0f);
          out.write(sw8.getBuffer().toString());
        }
        {
          StringWriter sw7 = new StringWriter();
          PrintWriter pw7 = new PrintWriter(sw7);
          printString(pw7, 0, "TEXT");
          ++handle;
          printAcDb(pw7, handle, "AcDbEntity", "AcDbText");
          printString(pw7, 8, "REF");
          // pw7.printf("%s\n  0\n", "\"10\"" );
          printXYZ(pw7, (xmin + 10 * SCALE_FIX + 1), -ymax, 0.0f);
          printFloat(pw7, 40, 0.3f);
          printString(pw7, 1, "\"10\"");
          out.write(sw7.getBuffer().toString());
        }
        {
          StringWriter sw6 = new StringWriter();
          PrintWriter pw6 = new PrintWriter(sw6);
          printString(pw6, 0, "TEXT");
          ++handle;
          printAcDb(pw6, handle, "AcDbEntity", "AcDbText");
          printString(pw6, 8, "REF");
          // pw6.printf("%s\n  0\n", "\"10\"" );
          printXYZ(pw6, xmin, -ymax + 10 * SCALE_FIX + 1, 0.0f);
          printFloat(pw6, 40, 0.3f);
          // printFloat( pw6, 50, 90.0f ); // rotation
          printString(pw6, 1, "\"10\"");
          out.write(sw6.getBuffer().toString());
        }
        out.flush();

        // centerline data
        if (type == PlotInfo.PLOT_PLAN || type == PlotInfo.PLOT_EXTENDED) {
          for (DrawingPath sh : plot.getLegs()) {
            DistoXDBlock blk = sh.mBlock;
            if (blk == null) continue;

            StringWriter sw4 = new StringWriter();
            PrintWriter pw4 = new PrintWriter(sw4);
            // if ( sh.mType == DrawingPath.DRAWING_PATH_FIXED ) {
            NumStation f = num.getStation(blk.mFrom);
            NumStation t = num.getStation(blk.mTo);

            printString(pw4, 0, "LINE");
            ++handle;
            printAcDb(pw4, handle, "AcDbEntity", "AcDbLine");
            printString(pw4, 8, "LEG");
            // printInt( pw4, 39, 2 );         // line thickness

            if (type == PlotInfo.PLOT_PLAN) {
              float x = scale * DrawingUtil.toSceneX(f.e);
              float y = scale * DrawingUtil.toSceneY(f.s);
              float x1 = scale * DrawingUtil.toSceneX(t.e);
              float y1 = scale * DrawingUtil.toSceneY(t.s);
              printXYZ(pw4, x, -y, 0.0f);
              printXYZ1(pw4, x1, -y1, 0.0f);
            } else if (type == PlotInfo.PLOT_EXTENDED) {
              float x = scale * DrawingUtil.toSceneX(f.h);
              float y = scale * DrawingUtil.toSceneY(f.v);
              float x1 = scale * DrawingUtil.toSceneX(t.h);
              float y1 = scale * DrawingUtil.toSceneY(t.v);
              printXYZ(pw4, x, -y, 0.0f);
              printXYZ1(pw4, x1, -y1, 0.0f);
            } else if (type == PlotInfo.PLOT_SECTION) {
              // nothing
            }
            // }
            out.write(sw4.getBuffer().toString());
            out.flush();
          }
          for (DrawingPath sh : plot.getSplays()) {
            DistoXDBlock blk = sh.mBlock;
            if (blk == null) continue;

            StringWriter sw41 = new StringWriter();
            PrintWriter pw41 = new PrintWriter(sw41);
            // if ( sh.mType == DrawingPath.DRAWING_PATH_SPLAY ) {
            NumStation f = num.getStation(blk.mFrom);

            printString(pw41, 0, "LINE");
            ++handle;
            printAcDb(pw41, handle, "AcDbEntity", "AcDbLine");
            printString(pw41, 8, "SPLAY");
            // printInt( pw41, 39, 1 );         // line thickness

            float dhs =
                scale * blk.mLength * FloatMath.cos(blk.mClino * grad2rad) * SCALE_FIX; // scaled dh
            if (type == PlotInfo.PLOT_PLAN) {
              float x = scale * DrawingUtil.toSceneX(f.e);
              float y = scale * DrawingUtil.toSceneY(f.s);
              float de = dhs * FloatMath.sin(blk.mBearing * grad2rad);
              float ds = -dhs * FloatMath.cos(blk.mBearing * grad2rad);
              printXYZ(pw41, x, -y, 0.0f);
              printXYZ1(pw41, x + de, -(y + ds), 0.0f);
            } else if (type == PlotInfo.PLOT_EXTENDED) {
              float x = scale * DrawingUtil.toSceneX(f.h);
              float y = scale * DrawingUtil.toSceneY(f.v);
              float dv = -blk.mLength * FloatMath.sin(blk.mClino * grad2rad) * SCALE_FIX;
              printXYZ(pw41, x, -y, 0.0f);
              printXYZ1(pw41, x + dhs * blk.mExtend, -(y + dv), 0.0f);
            } else if (type == PlotInfo.PLOT_SECTION) {
              // nothing
            }
            // }
            out.write(sw41.getBuffer().toString());
            out.flush();
          }
        }

        // FIXME station scale is 0.3
        float POINT_SCALE = 10.0f;
        for (ICanvasCommand cmd : plot.getCommands()) {
          if (cmd.commandType() != 0) continue;
          DrawingPath path = (DrawingPath) cmd;

          StringWriter sw5 = new StringWriter();
          PrintWriter pw5 = new PrintWriter(sw5);
          if (path.mType == DrawingPath.DRAWING_PATH_STATION) {
            DrawingStationPath st = (DrawingStationPath) path;

            printString(pw5, 0, "TEXT");
            printString(pw5, 8, "STATION");
            if (VERSION >= 13) {
              ++handle;
              printAcDb(pw5, handle, "AcDbEntity", "AcDbText");
              pw5.printf("%s\n  0\n", st.mName);
            }
            printXYZ(pw5, st.cx * scale, -st.cy * scale, 0.0f);
            printFloat(pw5, 40, POINT_SCALE);
            printString(pw5, 1, st.mName);
          } else if (path.mType == DrawingPath.DRAWING_PATH_LINE) {
            DrawingLinePath line = (DrawingLinePath) path;
            String layer =
                "L_"
                    + DrawingBrushPaths.mLineLib.getSymbolThName(line.lineType()).replace(':', '-');
            // String layer = "LINE";
            int flag = 0;
            boolean use_spline = false;
            if (VERSION >= 13) {
              for (LinePoint p = line.mFirst; p != null; p = p.mNext) {
                if (p.has_cp) {
                  use_spline = true;
                  break;
                }
              }
            }
            if (use_spline) {
              printString(pw5, 0, "SPLINE");
              ++handle;
              printAcDb(pw5, handle, "AcDbEntity", "AcDbSpline");
              printString(pw5, 8, layer);
              printString(pw5, 6, lt_continuous);
              printFloat(pw5, 48, 1.0f); // scale
              printInt(pw5, 60, 0); // visibilty (0: visible, 1: invisible)
              printInt(pw5, 66, 1); // group 1
              // printInt( pw5, 67, 0 ); // in model space [default]
              printInt(pw5, 210, 0);
              printInt(pw5, 220, 0);
              printInt(pw5, 230, 1);

              float xt = 0, yt = 0;
              int np = 2;
              LinePoint p = line.mFirst;
              LinePoint pn = p.mNext;
              if (pn != null) {
                if (pn.has_cp) {
                  xt = pn.mX1 - p.mX;
                  yt = pn.mY1 - p.mY;
                } else {
                  xt = pn.mX - p.mX;
                  yt = pn.mY - p.mY;
                }
                float d = FloatMath.sqrt(xt * xt + yt * yt);
                printFloat(pw5, 12, xt / d);
                printFloat(pw5, 22, -yt / d);
                printFloat(pw5, 32, 0);

                while (pn.mNext != null) {
                  p = pn;
                  pn = pn.mNext;
                  ++np;
                }
                if (pn.has_cp) {
                  xt = pn.mX - pn.mX2;
                  yt = pn.mY - pn.mY2;
                } else {
                  xt = pn.mX - p.mX;
                  yt = pn.mY - p.mY;
                }
                d = FloatMath.sqrt(xt * xt + yt * yt);
                printFloat(pw5, 13, xt / d);
                printFloat(pw5, 23, -yt / d);
                printFloat(pw5, 33, 0);
              }

              int ncp = np + 3 * (np - 1) - 1;
              int nk = ncp + 4 - (np - 2);
              printInt(pw5, 70, 1064);
              printInt(pw5, 71, 3); // degree
              printInt(pw5, 72, nk); // nr. of knots
              printInt(pw5, 73, ncp); // nr. of control pts
              printInt(pw5, 74, np); // nr. of fix points

              printInt(pw5, 40, 0);
              for (int k = 0; k < np; ++k) {
                for (int j = 0; j < 3; ++j) printInt(pw5, 40, k);
              }
              printInt(pw5, 40, np - 1);

              p = line.mFirst;
              xt = p.mX;
              yt = p.mY;
              printXYZ(pw5, p.mX * scale, -p.mY * scale, 0.0f);
              for (p = p.mNext; p != null; p = p.mNext) {
                if (p.has_cp) {
                  printXYZ(pw5, p.mX1 * scale, -p.mY1 * scale, 0.0f);
                  printXYZ(pw5, p.mX2 * scale, -p.mY2 * scale, 0.0f);
                } else {
                  printXYZ(pw5, xt * scale, -yt * scale, 0.0f);
                  printXYZ(pw5, p.mX * scale, -p.mY * scale, 0.0f);
                }
                printXYZ(pw5, p.mX * scale, -p.mY * scale, 0.0f);
                xt = p.mX;
                yt = p.mY;
              }
              for (p = line.mFirst; p != null; p = p.mNext) {
                printXYZ1(pw5, p.mX * scale, -p.mY * scale, 0.0f);
              }
            } else {
              printString(pw5, 0, "POLYLINE");
              ++handle;
              printAcDb(pw5, handle, "AcDbEntity", "AcDbPolyline");
              printString(pw5, 8, layer);
              // printInt(  pw5, 39, 1 );         // line thickness
              printInt(pw5, 66, 1); // group 1
              printInt(pw5, 70, 0); // flag
              for (LinePoint p = line.mFirst; p != null; p = p.mNext) {
                printString(pw5, 0, "VERTEX");
                if (VERSION >= 13) {
                  ++handle;
                  printAcDb(pw5, handle, "AcDbVertex", "AcDb3dPolylineVertex");
                  printInt(pw5, 70, 32);
                }
                printString(pw5, 8, layer);
                printXYZ(pw5, p.mX * scale, -p.mY * scale, 0.0f);
              }
            }
            pw5.printf("  0\nSEQEND\n");
            if (VERSION >= 13) {
              ++handle;
              printHex(pw5, 5, handle);
            }
          } else if (path.mType == DrawingPath.DRAWING_PATH_AREA) {
            DrawingAreaPath area = (DrawingAreaPath) path;
            String layer =
                "A_"
                    + DrawingBrushPaths.mAreaLib.getSymbolThName(area.areaType()).replace(':', '-');
            printString(pw5, 0, "HATCH"); // entity type HATCH
            // ++handle; printAcDb( pw5, handle, "AcDbEntity", "AcDbHatch" );
            // printString( pw5, 8, "AREA" );  // layer (color BYLAYER)
            printString(pw5, 8, layer); // layer (color BYLAYER)

            // printXYZ( pw5, 0f, 0f, 0f );
            printFloat(pw5, 210, 0f); // extrusion direction
            printFloat(pw5, 220, 0f);
            printFloat(pw5, 230, 1f);
            printInt(pw5, 70, 1); // solid fill
            printInt(pw5, 71, 1); // associative
            printInt(pw5, 91, 1); // nr. boundary paths: 1
            printInt(pw5, 92, 3); // flag: external (bit-0) polyline (bit-1)
            printInt(pw5, 93, area.size()); // nr. of edges /  vertices
            printInt(pw5, 72, 0); // edge type (0: default)
            printInt(pw5, 73, 1); // is-closed flag
            for (LinePoint p = area.mFirst; p != null; p = p.mNext) {
              printXY(pw5, p.mX * scale, -p.mY * scale);
            }

            // printInt( pw5, 97, 0 );            // nr. source boundary objects

            // printInt( pw5, 75, 1 );            // hatch style (normal)
            // printInt( pw5, 76, 1 );
            // printFloat( pw5, 52, 1.5708f );    // hatch pattern angle
            // printFloat( pw5, 41, 3f );         // hatch pattern scale
            // printInt( pw5, 77, 0 );            // hatch pattern double flag (0: not double)
            // printInt( pw5, 78, 1 );            // nr. pattern lines

            // printFloat( pw5, 53, 1.5708f );    // pattern line angle
            // printFloat( pw5, 43, 0f );         // pattern base point
            // printFloat( pw5, 44, 0f );
            // printFloat( pw5, 45, 1f );         // pattern line offset
            // printFloat( pw5, 46, 1f );
            // printInt( pw5, 79, 0 );            // nr. dash length items
            // // printFloat( pw5, 49, 3f );         // dash length (repeated nr. times)

            // printFloat( pw5, 47, 1f );         // pixel size
            // printInt( pw5, 98, 2 );            // nr. seed points
            // printXYZ( pw5, 0f, 0f, 0f );
            // printXYZ( pw5, 0f, 0f, 0f );
            // printInt( pw5, 451, 0 );
            // printFloat( pw5, 460, 0f );
            // printFloat( pw5, 461, 0f );
            // printInt( pw5, 452, 1 );
            // printFloat( pw5, 462, 1f );
            // printInt( pw5, 453, 2 );
            // printFloat( pw5, 463, 0f );
            // printFloat( pw5, 463, 1f );
            // printString( pw5, 470, "LINEAR" );
          } else if (path.mType == DrawingPath.DRAWING_PATH_POINT) {
            // FIXME point scale factor is 0.3
            DrawingPointPath point = (DrawingPointPath) path;
            String block =
                "P_"
                    + DrawingBrushPaths.mPointLib
                        .getSymbolThName(point.mPointType)
                        .replace(':', '-');
            // int idx = 1 + point.mPointType;
            printString(pw5, 0, "INSERT");
            ++handle;
            printAcDb(pw5, handle, "AcDbBlockReference");
            printString(pw5, 8, "POINT");
            printString(pw5, 2, block);
            printFloat(pw5, 41, POINT_SCALE);
            printFloat(pw5, 42, POINT_SCALE);
            printFloat(pw5, 50, 360 - (float) (point.mOrientation));
            printXYZ(pw5, point.cx * scale, -point.cy * scale, 0.0f);
          }
          out.write(sw5.getBuffer().toString());
          out.flush();
        }
      }
      writeEndSection(out);

      writeString(out, 0, "EOF");
      out.flush();
    } catch (IOException e) {
      // FIXME
      TDLog.Error("DXF io-exception " + e.toString());
    }
  }
Esempio n. 27
0
  public void draw(GL10 gl) {
    if (dirty) updateVertices();

    if (cardVertices == null) return;

    gl.glFrontFace(GL_CCW);

    gl.glEnable(GL_CULL_FACE);
    gl.glCullFace(GL_BACK);

    gl.glEnableClientState(GL_VERTEX_ARRAY);

    gl.glEnable(GL_BLEND);
    gl.glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    gl.glColor4f(1f, 1.0f, 1f, 1.0f);

    if (isValidTexture(texture)) {
      gl.glEnable(GL_TEXTURE_2D);
      gl.glEnableClientState(GL_TEXTURE_COORD_ARRAY);
      gl.glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
      gl.glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
      gl.glTexCoordPointer(2, GL_FLOAT, 0, textureBuffer);
      gl.glBindTexture(GL_TEXTURE_2D, texture.getId()[0]);
    }

    checkError(gl);

    gl.glPushMatrix();

    if (angle > 0) {
      if (axis == AXIS_TOP) {
        gl.glTranslatef(0, cardVertices[1], 0f);
        gl.glRotatef(-angle, 1f, 0f, 0f);
        gl.glTranslatef(0, -cardVertices[1], 0f);
      } else {
        gl.glTranslatef(0, cardVertices[7], 0f);
        gl.glRotatef(angle, 1f, 0f, 0f);
        gl.glTranslatef(0, -cardVertices[7], 0f);
      }
    }

    gl.glVertexPointer(3, GL_FLOAT, 0, vertexBuffer);
    gl.glDrawElements(GL_TRIANGLES, indices.length, GL_UNSIGNED_SHORT, indexBuffer);

    checkError(gl);

    gl.glPopMatrix();

    if (isValidTexture(texture)) {
      gl.glDisableClientState(GL_TEXTURE_COORD_ARRAY);
      gl.glDisable(GL_TEXTURE_2D);
    }

    if (angle > 0) {
      gl.glDisable(GL_LIGHTING);
      gl.glDisable(GL_DEPTH_TEST);

      if (axis == AXIS_TOP) {
        float w = cardVertices[9] - cardVertices[0];
        float h = (cardVertices[1] - cardVertices[4]) * (1f - FloatMath.cos(d2r(angle)));
        float z = (cardVertices[1] - cardVertices[4]) * FloatMath.sin(d2r(angle));
        float[] shadowVertices =
            new float[] {
              cardVertices[0],
              h + cardVertices[4],
              z,
              cardVertices[3],
              cardVertices[4],
              0f,
              w,
              cardVertices[7],
              0f,
              w,
              h + cardVertices[4],
              z
            };

        float alpha = 1f * (90f - angle) / 90f;

        gl.glColor4f(0f, 0.0f, 0f, alpha);
        gl.glVertexPointer(3, GL_FLOAT, 0, toFloatBuffer(shadowVertices));
        gl.glDrawElements(GL_TRIANGLES, indices.length, GL_UNSIGNED_SHORT, indexBuffer);
      } else {
        float w = cardVertices[9] - cardVertices[0];
        float h = (cardVertices[1] - cardVertices[4]) * (1f - FloatMath.cos(d2r(angle)));
        float z = (cardVertices[1] - cardVertices[4]) * FloatMath.sin(d2r(angle));
        float[] shadowVertices =
            new float[] {
              cardVertices[0],
              cardVertices[1],
              0f,
              cardVertices[3],
              cardVertices[1] - h,
              z,
              w,
              cardVertices[1] - h,
              z,
              w,
              cardVertices[1],
              0f
            };

        float alpha = 1f * (90f - angle) / 90f;

        gl.glColor4f(0f, 0.0f, 0f, alpha);
        gl.glVertexPointer(3, GL_FLOAT, 0, toFloatBuffer(shadowVertices));
        gl.glDrawElements(GL_TRIANGLES, indices.length, GL_UNSIGNED_SHORT, indexBuffer);
      }
      gl.glEnable(GL_DEPTH_TEST);
      gl.glEnable(GL_LIGHTING);
    }

    checkError(gl);

    gl.glDisable(GL_BLEND);
    gl.glDisableClientState(GL_VERTEX_ARRAY);
    gl.glDisable(GL_CULL_FACE);
  }
Esempio n. 28
0
 public void calculateEndPoint() {
   end.x = FloatMath.cos(angle) * length + start.x;
   end.y = FloatMath.sin(angle) * length + start.y;
 }
  /** This function does some fancy drawing, could be shortened a lot. */
  @Override
  public void draw(final Canvas canvas, final MapView mapView, final boolean shadow) {
    try {
      /* DEBUG Output */
      //		final long startMs = System.currentTimeMillis();
      //		long routedrawStartMs = 0, routedrawEndMs = 0;
      /* END DEBUG Output */

      /* Get the width/height of the underlying MapView.*/
      final int mapViewWidth = this.myDDMapActivity.getMapViewWidth();
      final int mapViewHeight = this.myDDMapActivity.getMapViewHeight();
      //		final GeoPoint curMapCenter = mapView.getMapCenter();

      /* Will hold various screen-coordinates. */
      final Point screenCoords = new Point();

      final Navigator nav = this.myDDMapActivity.getNavigator();

      /* Method in our custom map view
       * to return the DrivingDirection object. */
      this.mRoute = this.myDDMapActivity.getRoute();
      if (this.mRoute != null && this.mStaticNavCurrentTurnPointIndex != Constants.NOT_SET) {
        final int currentZoomLevel = this.myDDMapActivity.getZoomLevel();

        final int nextRouteIndex;
        final int nextTurnPointIndex;
        final int nextTurnIndexInRoute;
        final int turnAngle;

        final GeoPoint myProjectedLocationGeoPoint;

        final List<RouteInstruction> turnPointsRaw = this.mRoute.getRouteInstructions();
        if (!this.mRealtimeNav) {
          final RouteInstruction currentRouteInstruction =
              turnPointsRaw.get(this.mStaticNavCurrentTurnPointIndex);
          final GeoPoint liteVersionCurrentTurnPoint = currentRouteInstruction.getTurnPoint();
          nextRouteIndex = currentRouteInstruction.getFirstMotherPolylineIndex();

          nextTurnPointIndex =
              Math.min(this.mStaticNavCurrentTurnPointIndex + 1, turnPointsRaw.size() - 1);
          final RouteInstruction nextTurnPoint = turnPointsRaw.get(nextTurnPointIndex);
          nextTurnIndexInRoute = nextTurnPoint.getFirstMotherPolylineIndex();

          myProjectedLocationGeoPoint = liteVersionCurrentTurnPoint;

          turnAngle = (int) nextTurnPoint.getAngle();
        } else {
          nextRouteIndex = nav.getNextRoutePointIndex();
          nextTurnPointIndex = nav.getNextTurnPointIndex();
          nextTurnIndexInRoute = Math.max(0, nav.getNextTurnPointIndexInRoute());

          turnAngle = (int) nav.getTurnAngle();

          myProjectedLocationGeoPoint = nav.getLastKnownLocationProjectedGeoPoint();
        }

        final GeoPoint myCurrentLocationGeoPoint =
            this.myDDMapActivity.getLastKnownLocationAsGeoPoint(true);

        /* First get Start end End Point of the route. */
        final GeoPoint startPoint = this.mRoute.getStart();
        final GeoPoint endPoint = this.mRoute.getDestination();

        final Projection pj = mapView.getProjection();

        final ManagedLinePath pathDone = new ManagedLinePath();
        final ManagedLinePath pathCurrentSegment = new ManagedLinePath();
        final ArrayList<Path> pathTurnSegments = new ArrayList<Path>();
        final ArrayList<Path> pathTurnSegmentsPeaks = new ArrayList<Path>();
        final ManagedLinePath pathUpcoming = new ManagedLinePath();

        /* DEBUG Output */
        {
          //				routedrawStartMs = routedrawEndMs = System.currentTimeMillis();
        }
        /* END DEBUG Output */

        /* Check to see if the route is too long. */
        if (nav.isReady()) {
          /* Retrieve all (Map)Points of the route Found. */
          final List<GeoPoint> polyLine = this.mRoute.getPolyLine();

          //				final long startTransform = System.currentTimeMillis();

          //				canvas.drawText("nri: " + nextRouteIndex, 2, 40, this.pathDonePaint);
          //				canvas.drawText("nti: " + nextTurnPointIndex, 2, 50, this.pathDonePaint);
          //				canvas.drawText("ntiir: " + nextTurnIndexInRoute, 2, 60, this.pathDonePaint);

          if (nextRouteIndex != Constants.NOT_SET && polyLine != null) {
            /* Loop through all MapPoints returned. */

            final int increment = (int) (Math.max(1, Math.pow(2, 14 - currentZoomLevel)));

            final int lastIndexPathDone =
                Math.max(
                    0,
                    (myProjectedLocationGeoPoint != null)
                        ? nextRouteIndex - 1
                        : nextRouteIndex); // -1 when there is the projection in between
            final int firstIndexPathDone = Math.max(0, lastIndexPathDone - 100 * increment);

            final int firstIndexPathCurrent = nextRouteIndex;
            final int lastIndexPathCurrent = nextTurnIndexInRoute;

            final int firstIndexPathUpcoming = lastIndexPathCurrent;
            final int lastIndexPathUPcoming =
                Math.min(firstIndexPathUpcoming + 100 * increment, polyLine.size() - 1);

            if (firstIndexPathDone != lastIndexPathDone) {
              for (int i = firstIndexPathDone; i <= lastIndexPathDone; i += increment) {
                pathDone.lineTo(pj.toMapPixels(polyLine.get(i), screenCoords));
              }
            }
            pathDone.lineTo(
                pj.toMapPixels(
                    polyLine.get(lastIndexPathDone),
                    screenCoords)); // Ensures, that the this path and the next are connected.

            if (myProjectedLocationGeoPoint != null) {
              pj.toMapPixels(myProjectedLocationGeoPoint, screenCoords);
              pathDone.lineTo(screenCoords);
              pathCurrentSegment.lineTo(screenCoords);
            }

            if (firstIndexPathCurrent != lastIndexPathCurrent) {
              for (int i = firstIndexPathCurrent; i <= lastIndexPathCurrent; i += increment) {
                pathCurrentSegment.lineTo(pj.toMapPixels(polyLine.get(i), screenCoords));
              }
            }
            pathCurrentSegment.lineTo(
                pj.toMapPixels(
                    polyLine.get(lastIndexPathCurrent),
                    screenCoords)); // Ensures, that the this path and the next are connected.

            if (firstIndexPathUpcoming != lastIndexPathUPcoming) {
              for (int i = firstIndexPathUpcoming; i <= lastIndexPathUPcoming; i += increment) {
                pathUpcoming.lineTo(pj.toMapPixels(polyLine.get(i), screenCoords));
              }
            }

            //				final long endTransform = System.currentTimeMillis();
            //
            //				Log.d(Constants.DEBUGTAG, "Transform: " + (endTransform - startTransform) + "
            // ms");

            /* Used for transforming all paths. */
            final float scaleFactor =
                (this.mapRotationDegree == Constants.NOT_SET)
                    ? 1.0f
                    : FloatMath.sqrt(mapViewHeight * mapViewHeight + mapViewWidth * mapViewWidth)
                        / Math.min(mapViewHeight, mapViewWidth);

            /* Calculate the turn-segment-arrow. */
            if (currentZoomLevel >= MIN_ZOOMLEVEL_FOR_ARROWS) {
              {
                  /* next Arrow */
                final Path arrowPath = new Path();
                final Path arrowPeakPath = new Path();
                try {
                  ArrowPathCreator.createArrowOverIndex(
                      pj,
                      nextTurnIndexInRoute,
                      polyLine,
                      arrowPath,
                      arrowPeakPath,
                      scaleFactor,
                      currentZoomLevel,
                      turnAngle);
                  pathTurnSegments.add(arrowPath);
                  pathTurnSegmentsPeaks.add(arrowPeakPath);
                } catch (final IndexOutOfBoundsException ioobe) {
                  //							Log.e(DEBUGTAG, "Error drawing arrow. index=" + nextTurnIndexInRoute + "
                  // polyline length = " + polyLine.size());
                }

                { // TODO Remove on release
                  //							final int ARROW_RENDER_ZOOMLEVEL = 15;
                  //
                  //							Projection pj2 = mapView.new Projection(ARROW_RENDER_ZOOMLEVEL, 0, 0);
                  //
                  //							final Path arrowPathDummy = new Path();
                  //							final Path arrowPeakPathDummy = new Path();
                  //							ArrowPathCreator.createArrowOverIndex(pj2, nextTurnIndexInRoute,
                  // polyLine, arrowPathDummy, arrowPeakPathDummy, 1, ARROW_RENDER_ZOOMLEVEL,
                  // turnAngle);
                  //
                  //							final Bitmap b = ArrowPathCreator.drawToBitmap(arrowPathDummy,
                  // arrowPeakPathDummy);
                  //							canvas.drawBitmap(b, 250,250, new Paint());
                }
              }

              final int between = nav.getDistanceBetweenNextAndUpperNextTurnPoint();
              if (between < 1500 && nextTurnPointIndex != Constants.NOT_SET) {
                  /* upperNext Arrow */
                final int upperNextTurnPointIndex = nextTurnPointIndex + 1;
                if (upperNextTurnPointIndex > 0
                    && upperNextTurnPointIndex < this.mRoute.getRouteInstructions().size()) {
                  final Path arrowPath = new Path();
                  final Path arrowPeakPath = new Path();

                  final RouteInstruction upperNextTurnPoint =
                      turnPointsRaw.get(upperNextTurnPointIndex);
                  final float upperNextTurnAngle = upperNextTurnPoint.getAngle();
                  final int upperNextTurnIndexInRoute =
                      upperNextTurnPoint.getFirstMotherPolylineIndex();

                  try {
                    ArrowPathCreator.createArrowOverIndex(
                        pj,
                        upperNextTurnIndexInRoute,
                        polyLine,
                        arrowPath,
                        arrowPeakPath,
                        scaleFactor,
                        currentZoomLevel,
                        upperNextTurnAngle);
                    pathTurnSegments.add(arrowPath);
                    pathTurnSegmentsPeaks.add(arrowPeakPath);
                  } catch (final IndexOutOfBoundsException ioobe) {
                    //							Log.e(DEBUGTAG, "Error drawing arrow. index=" +
                    // upperNextTurnIndexInRoute + " polyline length = " + polyLine.size());
                  }
                }
              }
            }
          }

          /* Draw the already driven route to the canvas. */
          //				if(!canvas.quickReject(pathDone, EdgeType.BW))
          canvas.drawPath(pathDone, this.mPathDonePaint);

          /* Draw the rest Route to the canvas. */
          //				if(!canvas.quickReject(pathUpcoming, EdgeType.BW))
          canvas.drawPath(pathUpcoming, this.mPathUpcomingPaint);

          /* Draw the current Route Segment to the canvas. */
          //				if(!canvas.quickReject(pathCurrentSegment, EdgeType.AA))
          canvas.drawPath(pathCurrentSegment, this.mPathCurrentSegmentPaint);

          /* Draw the Turn Segment to the canvas. */
          for (int j = pathTurnSegments.size() - 1; j >= 0; j--) {
            canvas.drawPath(pathTurnSegments.get(j), this.mPathTurnSegmentOutlinePaint);
            canvas.drawPath(pathTurnSegments.get(j), this.mPathTurnSegmentPaint);

            canvas.drawPath(pathTurnSegmentsPeaks.get(j), this.mPathTurnSegmentPeakOutlinePaint);
            canvas.drawPath(pathTurnSegmentsPeaks.get(j), this.mPathTurnSegmentPeakPaint);
          }

          // DEBUG Output
          {
            //					int minLatitude =
            // this.mRoute.getLatitudeMinSpans()[nav.getNextRoutePointIndex()];
            //					int maxLatitude =
            // this.mRoute.getLatitudeMaxSpans()[nav.getNextRoutePointIndex()];
            //					int minLongitude =
            // this.mRoute.getLongitudeMinSpans()[nav.getNextRoutePointIndex()];
            //					int maxLongitude =
            // this.mRoute.getLongitudeMaxSpans()[nav.getNextRoutePointIndex()];
            //
            ////					Log.d(DEBUGTAG, "nextRoutePointIndex=" + nav.getNextRoutePointIndex());
            //
            //					int myLat = myCurrentLocationMapPoint.getLatitude();
            //					int myLon = myCurrentLocationMapPoint.getLongitude();
            //
            //					maxLatitude = Math.max(myLat, maxLatitude);
            //					minLatitude = Math.min(myLat, minLatitude);
            //					maxLongitude = Math.max(myLon, maxLongitude);
            //					minLongitude = Math.min(myLon, minLongitude);
            //
            //					int x1, x2, y1, y2;
            //					pj.toMapPixels(new GeoPoint(minLatitude, minLongitude), screenCoords);
            //					x1 = screenCoords.x;
            //					y1 = screenCoords.y;
            //
            //					pj.toMapPixels(new GeoPoint(maxLatitude, maxLongitude), screenCoords);
            //					x2 = screenCoords.x;
            //					y2 = screenCoords.y;
            ////					Log.d(DEBUGTAG, "x1=" + x1 + ", y1=" + y1 + ", x2=" + x2 + ", y2="+ y2);
            //					Paint p = new Paint();
            //					p.setStrokeWidth(3);
            //					p.setARGB(255,255,0,0);
            //					p.setStyle(Style.STROKE);
            //					canvas.drawRect(new Rect(x1,y1,x2,y2), p);
          }
          // END DEBUG Output

          {
              /* Print Pin-MArkers. */
            /* Finally draw a fancy PIN to mark the end... */
            pj.toMapPixels(endPoint, screenCoords);

            canvas.drawBitmap(
                this.MARKER_END,
                screenCoords.x - MARKER_DESTINATION_HOTSPOT_X,
                screenCoords.y - MARKER_DESTINATION_HOTSPOT_Y,
                this.mMarkerPaint);

            /* ...for all via-points. */
            final List<GeoPoint> vias = this.mRoute.getVias();
            for (final GeoPoint mpVia : vias) {
              pj.toMapPixels(mpVia, screenCoords);

              canvas.drawBitmap(
                  this.MARKER_VIA,
                  screenCoords.x - MARKER_VIA_HOTSPOT_X,
                  screenCoords.y - MARKER_VIA_HOTSPOT_Y,
                  this.mMarkerPaint);
            }

            /* ...and the start of the route.*/
            pj.toMapPixels(startPoint, screenCoords);

            canvas.drawBitmap(
                this.MARKER_START,
                screenCoords.x - MARKER_START_HOTSPOT_X,
                screenCoords.y - MARKER_START_HOTSPOT_Y,
                this.mMarkerPaint);
          }

          {
            /* DEBUG Output */
            //					routedrawEndMs = System.currentTimeMillis();
          } /* END DEBUG Output */
        }

        final AbstractAndNavLocationProvider andNavLocationProvider =
            this.myDDMapActivity.getAndNavLocationProvider();

        if (myCurrentLocationGeoPoint != null) {
          /* Draw ourself to our real location. */
          pj.toMapPixels(myCurrentLocationGeoPoint, screenCoords);

          /* Draw the HorizontalPositioningError if we have a location. */
          if (this.mShowAccuracy) {

            final float accuracyRadius =
                (andNavLocationProvider.hasHorizontalPositioningError())
                    ? pj.metersToEquatorPixels(
                        andNavLocationProvider.getHorizontalPositioningError())
                    : RADIUS_NO_ACCURACY;

            /* Only draw if the DirectionArrow doesn't cover it. */
            if (accuracyRadius > 8) {
              /* Draw the inner shadow. */
              this.mAccuracyPaint.setAntiAlias(false);
              this.mAccuracyPaint.setAlpha(30);
              this.mAccuracyPaint.setStyle(Style.FILL);
              canvas.drawCircle(
                  screenCoords.x, screenCoords.y, accuracyRadius, this.mAccuracyPaint);

              /* Draw the edge. */
              this.mAccuracyPaint.setAntiAlias(true);
              this.mAccuracyPaint.setAlpha(150);
              this.mAccuracyPaint.setStyle(Style.STROKE);
              canvas.drawCircle(
                  screenCoords.x, screenCoords.y, accuracyRadius, this.mAccuracyPaint);
            }
          }

          /* Get the bearing if available. */
          final boolean hasBearing = andNavLocationProvider.hasBearing();
          final float directionBearing = (hasBearing) ? andNavLocationProvider.getBearing() : 0;

          /* Rotate the direction-Arrow according to the bearing we are driving. And draw it to the canvas. */
          this.mDirectionRotater.setRotate(
              directionBearing, this.DIRECTION_ARROW_CENTER_X, this.DIRECTION_ARROW_CENTER_Y);
          final Bitmap rotatedDirection =
              Bitmap.createBitmap(
                  this.DIRECTION_ARROW,
                  0,
                  0,
                  this.DIRECTION_ARROW_WIDTH,
                  this.DIRECTION_ARROW_HEIGHT,
                  this.mDirectionRotater,
                  true);

          /* Calculate the deltas needed after the rotation, to paint the hotspot of the directionarrow on the actual location. */
          final float py = this.DIRECTION_ARROW_HOTSPOT_Y - this.DIRECTION_ARROW_CENTER_Y;

          final float dx;
          final float dy;

          if (py < 0.001 || py > 0.001) {
            final float alpha = MathConstants.DEG2RAD * (-directionBearing + 90f);
            dx = FloatMath.cos(alpha) * py;
            dy = FloatMath.sin(alpha) * py;
          } else {
            dx = 0;
            dy = 0;
          }
          canvas.drawBitmap(
              rotatedDirection,
              screenCoords.x - rotatedDirection.getWidth() / 2 + dx,
              screenCoords.y - rotatedDirection.getHeight() / 2 - dy,
              this.mDirectionRotatorPaint);
        }

        {
          /* DEBUG Output */
          //				long endMs = System.currentTimeMillis();
          //
          //				this.debugDrawSum +=  endMs - startMs;
          //				this.debugDrawCount++;
          //				Log.d(DEBUGTAG, "GUI: " + (endMs - startMs) + " ms  [Avg: " + (this.debugDrawSum /
          // this.debugDrawCount) + " ms]"
          //						+ "    [Route: " + (routedrawEndMs - routedrawStartMs) + " ms]");
        } /* END DEBUG Output */
      }
    } catch (final Exception e) {
      Log.e(Constants.DEBUGTAG, "Error in directionsOverlay", e);
      //			Exceptor.e("Error in directionsOverlay", e, this.myDDMapActivity);
    }
  }
Esempio n. 30
0
  @Override
  protected void onDraw(Canvas canvas) {
    canvas.drawRGB(0, 0, 0);
    green.setStrokeWidth(barwidth);
    canvas.drawRect(0, 0, width - 1, height - 1, white);

    for (int freq = MIN_FREQ; freq < MAX_FREQ; ) {
      if (freq < 100) {
        freq += 10;
      } else if (freq < 1000) {
        freq += 100;
      } else if (freq < 10000) {
        freq += 1000;
      } else {
        freq += 10000;
      }

      float x = projectX(freq) * width;
      canvas.drawLine(x, 0, x, height - 1, gray);
    }

    for (int i = 0; i < levels.length; i++) {
      float freq = (float) FreqTable[i];
      float x = projectX(freq) * width - 8;
      canvas.drawText(
          String.format(freq < 1000 ? "%.0f" : "%.0fk", freq < 1000 ? freq : freq / 1000),
          x,
          height - 1,
          white);
    }

    for (int dB = MIN_DB; dB <= MAX_DB; dB += 5) {
      float y = projectY(dB) * height;
      if (dB == 0) {
        canvas.drawLine(0, y, width - 1, y, red);
      } else {
        canvas.drawLine(0, y, width - 1, y, gray);
      }
      canvas.drawText(String.format("%d", Math.abs(dB)), 1, y - 1, white);
    }

    float gain = (float) Math.pow(10, levels[0] / 20);
    for (int i = 0; i < biquads.length; i++) {
      float freq = (float) FreqTable[i];
      biquads[i].setHighShelf(freq * 2f, SAMPLING_RATE, levels[i + 1] - levels[i], 1f);
    }

    float oldx = -1;
    float olddB = 0;
    for (float freq = MIN_FREQ / CURVE_RESOLUTION;
        freq < MAX_FREQ * CURVE_RESOLUTION;
        freq *= CURVE_RESOLUTION) {
      float omega = freq / SAMPLING_RATE * (float) Math.PI * 2;
      z_sur.SetValue(FloatMath.cos(omega), FloatMath.sin(omega));

      /* Evaluate the response at frequency z */
      Complex z2 = biquads[0].evaluateTransfer(z_sur);
      Complex z3 = biquads[1].evaluateTransfer(z_sur);
      Complex z4 = biquads[2].evaluateTransfer(z_sur);
      Complex z5 = biquads[3].evaluateTransfer(z_sur);
      Complex z6 = biquads[4].evaluateTransfer(z_sur);
      Complex z7 = biquads[5].evaluateTransfer(z_sur);
      Complex z8 = biquads[6].evaluateTransfer(z_sur);
      Complex z9 = biquads[7].evaluateTransfer(z_sur);
      Complex z10 = biquads[8].evaluateTransfer(z_sur);

      /* Magnitude response, dB */
      float dB =
          lin2dB(
              gain * z2.rho() * z3.rho() * z4.rho() * z5.rho() * z6.rho() * z7.rho() * z8.rho()
                  * z9.rho() * z10.rho());
      float newBb = projectY(dB) * height;
      float newx = projectX(freq) * width;

      if (oldx != -1) {
        canvas.drawLine(oldx, olddB, newx, newBb, blue);
      }
      oldx = newx;
      olddB = newBb;
    }

    for (int i = 0; i < levels.length; i++) {
      float freq = (float) FreqTable[i];
      float x = projectX(freq) * width;
      float y = projectY(levels[i]) * height;
      canvas.drawLine(x, height / 2, x, y, green);
      canvas.drawText(String.format("%1.1f", Math.abs(levels[i])), x, height / 2, whiteCentered);
    }
  }