예제 #1
1
 public static Audio playWav(String wavFile, boolean loop) {
   try {
     AudioLoader.update(); // JIC
     Audio wav = AudioLoader.getAudio("WAV", ResourceLoader.getResourceAsStream(wavFile));
     sounds.add(wav);
     wav.playAsMusic(1.0f, 1.0f, loop);
     return wav;
   } catch (IOException e) {
     e.printStackTrace();
   }
   return null;
 }
예제 #2
1
  /** Initialise resources */
  public void init() {
    try {
      wavEffect =
          AudioLoader.getAudio(
              "WAV",
              ResourceLoader.getResourceAsStream("com/etk2000/SpaceGame/Music/MainMenuMusic.wav"));
      // @param: something, something, loop
      wavEffect.playAsMusic(1.0f, 1.0f, true);
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }

    /*
     * try {
     * // you can play oggs by loading the complete thing into
     * // a sound
     * oggEffect = AudioLoader.getAudio("OGG",
     * ResourceLoader.getResourceAsStream("testdata/restart.ogg"));
     *
     * // or setting up a stream to read from. Note that the argument becomes
     * // a URL here so it can be reopened when the stream is complete. Probably
     * // should have reset the stream by thats not how the original stuff worked
     * oggStream = AudioLoader.getStreamingAudio("OGG",
     * ResourceLoader.getResource("testdata/bongos.ogg"));
     *
     * // can load mods (XM, MOD) using ibxm which is then played through OpenAL. MODs
     * // are always streamed based on the way IBXM works
     * modStream = AudioLoader.getStreamingAudio("MOD",
     * ResourceLoader.getResource("testdata/SMB-X.XM"));
     *
     * // playing as music uses that reserved source to play the sound. The first
     * // two arguments are pitch and gain, the boolean is whether to loop the content
     * modStream.playAsMusic(1.0f, 1.0f, true);
     *
     * // you can play aifs by loading the complete thing into
     * // a sound
     * aifEffect = AudioLoader.getAudio("AIF",
     * ResourceLoader.getResourceAsStream("testdata/burp.aif"));
     *
     * // you can play wavs by loading the complete thing into
     * // a sound
     * wavEffect = AudioLoader.getAudio("WAV",
     * ResourceLoader.getResourceAsStream("testdata/cbrown01.wav"));
     * } catch (Exception e) {
     * e.printStackTrace();
     * }
     */
  }
예제 #3
0
  public void initLoader() {
    BufferedReader reader =
        new BufferedReader(
            new InputStreamReader(
                ResourceLoader.getResourceAsStream(Props.getPropStr("Resource.Picture.Path"))));
    try {
      String line;
      while ((line = reader.readLine()) != null) {
        line = line.trim();

        if (line == null || line.isEmpty() || line.startsWith("#")) {
          continue;
        }
        String[] args = line.split(";");
        String key = args[0].trim();
        String path = args[1].trim();
        try {
          images.put(key, new Image(ResourceLoader.getResourceAsStream(path), path, false));
        } catch (SlickException ex) {
          LOGGER.log(Level.WARNING, "Unable to create image " + path, ex);
        }
      }
    } catch (IOException ex) {
      LOGGER.log(Level.SEVERE, "Unable to initialise the picture loader", ex);
    }
  }
예제 #4
0
  /* (non-Javadoc)
   * @see chu.engine.Game#init(int, int, java.lang.String)
   */
  public void init(int width, int height, String name) {
    super.init(width, height, name);
    Player p1 = new Player("Player", (byte) 0);
    localPlayer = p1;
    ByteBuffer icon16, icon32;
    icon16 = icon32 = null;
    try {
      icon16 =
          ByteBuffer.wrap(
              TextureLoader.getTexture(
                      "PNG", ResourceLoader.getResourceAsStream("res/gui/icon16.png"))
                  .getTextureData());
      icon32 =
          ByteBuffer.wrap(
              TextureLoader.getTexture(
                      "PNG", ResourceLoader.getResourceAsStream("res/gui/icon32.png"))
                  .getTextureData());
    } catch (IOException e) {
      e.printStackTrace();
    }
    Display.setIcon(new ByteBuffer[] {icon16, icon32});
    FEResources.loadResources();
    FEResources.loadBitmapFonts();
    WeaponFactory.loadWeapons();
    UnitFactory.loadUnits();
    p1.getParty().setColor(Party.TEAM_BLUE);

    /* OpenGL final setup */
    glEnable(GL_LINE_SMOOTH);

    UnitFactory.getUnit("Lyn");
    connect = new ConnectStage();
    setCurrentStage(new TitleStage());
    SoundTrack.loop("main");
  }
예제 #5
0
 public static InputStream getResourceAsStream(String ref) {
   InputStream ret = ResourceLoader.getResourceAsStream(ref);
   if (ret == null) {
     throw new RuntimeException("Resource not found");
   }
   return ret;
 }
예제 #6
0
  /**
   * Plays an audio file at the preview position. If the audio file is already playing, then nothing
   * will happen.
   *
   * @param beatmap the beatmap to play
   * @param loop whether or not to loop the track
   * @param preview whether to start at the preview time (true) or beginning (false)
   */
  public static void play(final Beatmap beatmap, final boolean loop, final boolean preview) {
    // new track: load and play
    if (lastBeatmap == null || !beatmap.audioFilename.equals(lastBeatmap.audioFilename)) {
      final File audioFile = beatmap.audioFilename;
      if (!audioFile.isFile() && !ResourceLoader.resourceExists(audioFile.getPath())) {
        UI.sendBarNotification(String.format("Could not find track '%s'.", audioFile.getName()));
        System.out.println(beatmap);
        return;
      }

      reset();
      System.gc();

      switch (BeatmapParser.getExtension(beatmap.audioFilename.getName())) {
        case "ogg":
        case "mp3":
          trackLoader =
              new Thread() {
                @Override
                public void run() {
                  loadTrack(audioFile, (preview) ? beatmap.previewTime : 0, loop);
                }
              };
          trackLoader.start();
          break;
        default:
          break;
      }
    }

    // new track position: play at position
    else if (beatmap.previewTime != lastBeatmap.previewTime) playAt(beatmap.previewTime, loop);

    lastBeatmap = beatmap;
  }
예제 #7
0
 public static URL getResource(String ref) {
   URL ret = ResourceLoader.getResource(ref);
   if (ret == null) {
     throw new RuntimeException("Resource not found");
   }
   return ret;
 }
예제 #8
0
  @Override
  public void draw(boolean flip) {
    try {
      if (ladder != null) GL11.glDeleteTextures(ladder.getTextureID());
      ladder =
          TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("res/amobox.png"));
    } catch (IOException e) {
      e.printStackTrace();
    }
    ladder.bind();
    GL11.glLoadIdentity();
    GL11.glTranslated(x, y, 0);

    GL11.glBegin(GL11.GL_QUADS);
    GL11.glTexCoord2f(0, 0);
    GL11.glVertex2f(100, 100);
    GL11.glTexCoord2f(1, 0);
    GL11.glVertex2f(100 + ladder.getTextureWidth(), 100);
    GL11.glTexCoord2f(1, 1);
    GL11.glVertex2f(100 + ladder.getTextureWidth(), 100 + ladder.getTextureHeight());
    GL11.glTexCoord2f(0, 1);
    GL11.glVertex2f(100, 100 + ladder.getTextureHeight());
    GL11.glEnd();
    GL11.glLoadIdentity();
  }
 public LoadTexture(String path, String filetype) {
   try {
     // Load texture atlas image
     textureAtlas = TextureLoader.getTexture(filetype, ResourceLoader.getResourceAsStream(path));
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
예제 #10
0
파일: Candle.java 프로젝트: Yeahat/Genhat
 @Override
 public void loadTextures() {
   try {
     texture =
         TextureLoader.getTexture(
             "png", ResourceLoader.getResourceAsStream("graphics/objects/thing2.png"));
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
예제 #11
0
 public Texture getTexture() {
   Texture tex = null;
   InputStream in = ResourceLoader.getResourceAsStream("res/tiles/Door16.png");
   try {
     tex = TextureLoader.getTexture("PNG", in);
   } catch (IOException e) {
     e.printStackTrace();
   }
   return tex;
 }
예제 #12
0
  // ***************************************************************************
  // init
  // ***************************************************************************
  private void init() {
    // load textures here and other things

    try {
      // load texture from PNG file
      texture =
          TextureLoader.getTexture(
              "JPG",
              // ResourceLoader.getResourceAsStream("/Users/robert/Desktop/IMG_0994.PNG"));
              ResourceLoader.getResourceAsStream("/Users/robert/Desktop/edkxryo.jpg"));

      System.out.println("Texture loaded:    " + texture);
      System.out.println(">> Image width:    " + texture.getImageWidth());
      System.out.println(">> Image height:   " + texture.getImageHeight());
      System.out.println(">> Texture width:  " + texture.getTextureWidth());
      System.out.println(">> Texture height: " + texture.getTextureHeight());
      System.out.println(">> Texture ID:     " + texture.getTextureID());

      // AL

      // you can play oggs by loading the complete thing into
      // a sound
      // oggEffect = AudioLoader.getAudio("OGG",
      // ResourceLoader.getResourceAsStream("testdata/restart.ogg"));

      // or setting up a stream to read from. Note that the argument becomes
      // a URL here so it can be reopened when the stream is complete. Probably
      // should have reset the stream by thats not how the original stuff worked
      // oggStream = AudioLoader.getStreamingAudio("OGG",
      // ResourceLoader.getResource("testdata/bongos.ogg"));

      // can load mods (XM, MOD) using ibxm which is then played through OpenAL. MODs
      // are always streamed based on the way IBXM works
      // modStream = AudioLoader.getStreamingAudio("MOD",
      // ResourceLoader.getResource("testdata/SMB-X.XM"));

      // playing as music uses that reserved source to play the sound. The first
      // two arguments are pitch and gain, the boolean is whether to loop the content
      // modStream.playAsMusic(1.0f, 1.0f, true);

      // you can play aifs by loading the complete thing into
      // a sound
      // aifEffect = AudioLoader.getAudio("AIF",
      // ResourceLoader.getResourceAsStream("testdata/burp.aif"));

      // you can play wavs by loading the complete thing into
      // a sound
      // wavEffect = AudioLoader.getAudio("WAV",
      // ResourceLoader.getResourceAsStream("testdata/cbrown01.wav"));

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
예제 #13
0
  static {
    ResourceLoader.addResourceLocation(
        new ResourceLocation() {
          public URL getResource(String ref) {
            return this.getClass().getResource(ref);
          }

          public InputStream getResourceAsStream(String ref) {
            return this.getClass().getResourceAsStream(ref);
          }
        });
  }
예제 #14
0
  @Override
  public void init(GameContainer container, StateBasedGame game) throws SlickException {
    super.init(container, game);

    this.game = game;

    // add asset-folder to the ResourceLocators of nifty and slick2d
    ResourceLoader.addResourceLocation(new FileSystemLocation(new File(menuAssetPath)));
    org.newdawn.slick.util.ResourceLoader.addResourceLocation(
        new org.newdawn.slick.util.FileSystemLocation(new File(menuAssetPath)));
    // read the nifty-xml-fiel
    fromXml(menuNiftyXMLFile, ResourceLoader.getResourceAsStream(menuNiftyXMLFile), this);
  }
예제 #15
0
 public static void playMusic(String name) {
   try {
     Audio song;
     song =
         AudioLoader.getAudio(
             "WAV",
             ResourceLoader.getResourceAsStream(
                 "resources" + Common.sep + "music" + Common.sep + name + ".wav"));
     song.playAsMusic(1.0f, 1.0f, true);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
예제 #16
0
  /**
   * Get the build number of slick
   *
   * @return The build number of slick
   */
  public static int getBuildVersion() {
    try {
      Properties props = new Properties();
      props.load(ResourceLoader.getResourceAsStream("version"));

      int build = Integer.parseInt(props.getProperty("build"));
      Log.info("Slick Build #" + build);

      return build;
    } catch (Exception e) {
      Log.error("Unable to determine Slick build number");
      return -1;
    }
  }
예제 #17
0
 public GuiButton(float x, float y, float sx, float sy, String tex) {
   PosX = x;
   PosY = y;
   SizeX = sx;
   SizeY = sy;
   try {
     TextureId =
         (TextureLoader.getTexture(
                 "", ResourceLoader.getResourceAsStream(System.getProperty("user.dir") + tex)))
             .getTextureID();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
  public void init(GameContainer container, StateBasedGame sbg) throws SlickException {
    hintergrund = new Image("res/pictures/background.png");
    this.game = sbg;
    // eigenes Font laden
    try {
      InputStream inputStream =
          ResourceLoader.getResourceAsStream("res/fonts/Volter__28Goldfish_29.ttf");

      Font awtFont = Font.createFont(Font.TRUETYPE_FONT, inputStream);
      // Font Groesse
      awtFont = awtFont.deriveFont(24f);
      font = new TrueTypeFont(awtFont, false);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
예제 #19
0
  private void loadFont(boolean numericOnly, String fontFolder) {
    if (numericOnly) {
      String[] tmp = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
      names = tmp;
    } else {

    }
    font = new Texture[names.length];
    for (int i = 0; i < names.length; i++) {
      try {
        font[i] =
            TextureLoader.getTexture(
                "PNG", ResourceLoader.getResourceAsStream(fontFolder + "/" + names[i] + ".png"));
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
예제 #20
0
  /**
   * Create a new font based on a font definition from AngelCode's tool and the font image generated
   * from the tool.
   *
   * @param fntFile The location of the font defnition file
   * @param image The image to use for the font
   * @throws SlickException Indicates a failure to load either file
   */
  public AngelCodeFont(String fntFile, Image image) throws SlickException {
    fontImage = image;

    parseFnt(ResourceLoader.getResourceAsStream(fntFile));
  }
예제 #21
0
 /**
  * Create a new font based on a font definition from AngelCode's tool and the font image generated
  * from the tool.
  *
  * @param fntFile The location of the font defnition file
  * @param imgFile The location of the font image
  * @param caching True if this font should use display list caching
  * @throws SlickException Indicates a failure to load either file
  */
 public AngelCodeFont(String fntFile, String imgFile, boolean caching) throws SlickException {
   fontImage = new Image(imgFile);
   displayListCaching = caching;
   parseFnt(ResourceLoader.getResourceAsStream(fntFile));
 }
예제 #22
0
  @Override
  public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
    gcw = gc.getWidth();
    gch = gc.getHeight();
    rotateTransition = new RotateTransition();
    selectTransition = new SelectTransition();
    emptyTransition = new EmptyTransition();
    // Set up images
    scorebackground = new Image("simple/playerscorebackground.png");
    background = new Image("simple/questionbg.png");

    // Set up item lists
    itemList = new ItemList();
    items = itemList.getItems();

    // Set up item panel
    itemPanel = new DialogLayout();
    itemPanel.setTheme("item-panel");
    itemPanel.setSize(400, 220);
    itemPanel.setPosition(50, fixed_y);
    itemDescriptionModel = new SimpleTextAreaModel();
    itemDescription = new TextArea(itemDescriptionModel);
    descriptionModel = new HTMLTextAreaModel();
    description = new TextArea(descriptionModel);
    description.setTheme("trusttextarea");
    description.setPosition(10, 110);
    description.setSize(780, 100);

    lItemName = new Label("Name: ");
    lDescription = new Label("Description: ");
    lItemValue = new Label("Value: ");
    lItemName.setTheme("questionatari16lbl");
    lDescription.setTheme("questionatari16lbl");
    lItemValue.setTheme("questionatari16lbl");

    // Set up fonts
    // Create custom font for question
    try {
      loadFont =
          java.awt.Font.createFont(
              java.awt.Font.TRUETYPE_FONT,
              org.newdawn.slick.util.ResourceLoader.getResourceAsStream("font/visitor2.ttf"));
    } catch (FontFormatException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    loadTitleFont = loadFont.deriveFont(Font.BOLD, titleFontSize);
    titleFont = new BasicFont(loadTitleFont);

    loadMainFont = loadFont.deriveFont(Font.BOLD, mainFontSize);
    mainFont = new BasicFont(loadMainFont);
    readyFont = new BasicFont(loadTitleFont, Color.red);

    loadTimerFont = loadFont.deriveFont(Font.BOLD, timerFontSize);
    loadTimerMFont = loadFont.deriveFont(Font.BOLD, timerMFontSize);
    timerFont = new BasicFont(loadTimerFont);
    timerMFont = new BasicFont(loadTimerMFont);

    // Confirmation GUI
    lblConfirmation = new Label("");
    btnYes = new Button("Yes");
    btnNo = new Button("No");

    lblConfirmation.setTheme("labelscoretotal");
    btnYes.setTheme("choicebutton");
    btnNo.setTheme("choicebutton");

    lblConfirmation.setPosition((gcw / 2) - lblConfirmation.getWidth() / 2, fixed_y + 320);
    btnYes.setPosition((gcw / 2) - 152, fixed_y + 340);
    btnNo.setPosition((gcw / 2) - 152, fixed_y + 370);
    btnYes.setSize(300, 25);
    btnNo.setSize(300, 25);

    btnYes.addCallback(
        new Runnable() {
          public void run() {
            emulateYes();
          }
        });

    btnNo.addCallback(
        new Runnable() {
          public void run() {
            enableChoices();
          }
        });

    // Bid GUI
    vaBid = new ValueAdjusterInt();
    vaBid.setSize(200, 30);
    vaBid.setPosition((gcw / 2) - vaBid.getWidth() / 2, fixed_y + 320);

    btnSubmit = new Button("Submit Bid");
    btnSubmit.setSize(200, 30);
    btnSubmit.setPosition((gcw / 2) - btnSubmit.getWidth() / 2 - 2, fixed_y + 360);
    btnSubmit.setTheme("choicebutton");

    btnSubmit.addCallback(
        new Runnable() {
          public void run() {
            emulateChoice();
          }
        });

    // Results GUI
    p1ResultPanel = new DialogLayout();
    p1ResultPanel.setTheme("incorrectbid-panel");
    p1ResultPanel.setSize(300, 80);
    p1ResultPanel.setPosition((gcw / 2 - p1ResultPanel.getWidth() / 2 - 200), 420);

    p2ResultPanel = new DialogLayout();
    p2ResultPanel.setTheme("incorrectbid-panel");
    p2ResultPanel.setSize(300, 80);
    p2ResultPanel.setPosition((gcw / 2 - p2ResultPanel.getWidth() / 2 + 160), 420);

    lBid = new Label("Bid:");
    lBid2 = new Label("Bid: ");
    lAmountWon = new Label("Amount Won: ");
    lblAmountWon = new Label("");

    lblBid = new Label("");
    lblBid2 = new Label("");
    lAmountWon2 = new Label("Amount Won: ");
    lblAmountWon2 = new Label("");

    lblBid.setTheme("labelscoretotalright");
    lblBid2.setTheme("labelscoretotalright");
    lblAmountWon.setTheme("labelscoretotalright");
    lblAmountWon2.setTheme("labelscoretotalright");

    DialogLayout.Group hLeftLabel1 = p1ResultPanel.createParallelGroup(lBid, lAmountWon);
    DialogLayout.Group hRightResult1 = p1ResultPanel.createParallelGroup(lblBid, lblAmountWon);

    p1ResultPanel.setHorizontalGroup(
        p1ResultPanel
            .createParallelGroup()
            .addGap(120)
            .addGroup(p1ResultPanel.createSequentialGroup(hLeftLabel1, hRightResult1)));

    p1ResultPanel.setVerticalGroup(
        p1ResultPanel
            .createSequentialGroup()
            .addGap(30)
            .addGroup(p1ResultPanel.createParallelGroup(lBid, lblBid))
            .addGroup(p1ResultPanel.createParallelGroup(lAmountWon, lblAmountWon)));

    DialogLayout.Group hLeftLabel2 = p2ResultPanel.createParallelGroup(lBid2, lAmountWon2);
    DialogLayout.Group hRightResult2 = p2ResultPanel.createParallelGroup(lblBid2, lblAmountWon2);

    p2ResultPanel.setHorizontalGroup(
        p2ResultPanel
            .createParallelGroup()
            .addGroup(p2ResultPanel.createSequentialGroup(hLeftLabel2, hRightResult2)));

    p2ResultPanel.setVerticalGroup(
        p2ResultPanel
            .createSequentialGroup()
            .addGap(30)
            .addGroup(p2ResultPanel.createParallelGroup(lBid2, lblBid2))
            .addGroup(p2ResultPanel.createParallelGroup(lAmountWon2, lblAmountWon2)));
  }
예제 #23
0
  public void save(File outputBMFontFile) throws IOException, SlickException {
    File outputDir = outputBMFontFile.getParentFile();
    String outputName = outputBMFontFile.getName();
    if (outputName.endsWith(".fnt")) outputName = outputName.substring(0, outputName.length() - 4);

    unicodeFont.loadGlyphs();

    PrintStream out =
        new PrintStream(new FileOutputStream(new File(outputDir, outputName + ".fnt")));
    Font font = unicodeFont.getFont();
    int pageWidth = unicodeFont.getGlyphPageWidth();
    int pageHeight = unicodeFont.getGlyphPageHeight();
    out.println(
        "info face=\""
            + font.getFontName()
            + "\" size="
            + font.getSize()
            + " bold="
            + (font.isBold() ? 1 : 0)
            + " italic="
            + (font.isItalic() ? 1 : 0)
            + " charset=\"\" unicode=0 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=1,1");
    out.println(
        "common lineHeight="
            + unicodeFont.getLineHeight()
            + " base=26 scaleW="
            + pageWidth
            + " scaleH="
            + pageHeight
            + " pages="
            + unicodeFont.getGlyphPages().size()
            + " packed=0");

    int pageIndex = 0, glyphCount = 0;
    for (Iterator pageIter = unicodeFont.getGlyphPages().iterator(); pageIter.hasNext(); ) {
      GlyphPage page = (GlyphPage) pageIter.next();
      String fileName;
      if (pageIndex == 0 && !pageIter.hasNext()) fileName = outputName + ".png";
      else fileName = outputName + (pageIndex + 1) + ".png";
      out.println("page id=" + pageIndex + " file=\"" + fileName + "\"");
      glyphCount += page.getGlyphs().size();
      pageIndex++;
    }

    out.println("chars count=" + glyphCount);

    // Always output space entry (codepoint 32).
    int[] glyphMetrics = getGlyphMetrics(font, 32);
    int xAdvance = glyphMetrics[1];
    out.println(
        "char id=32   x=0     y=0     width=0     height=0     xoffset=0     yoffset="
            + unicodeFont.getAscent()
            + "    xadvance="
            + xAdvance
            + "     page=0  chnl=0 ");

    pageIndex = 0;
    List allGlyphs = new ArrayList(512);
    for (Iterator pageIter = unicodeFont.getGlyphPages().iterator(); pageIter.hasNext(); ) {
      GlyphPage page = (GlyphPage) pageIter.next();
      for (Iterator glyphIter = page.getGlyphs().iterator(); glyphIter.hasNext(); ) {
        Glyph glyph = (Glyph) glyphIter.next();

        glyphMetrics = getGlyphMetrics(font, glyph.getCodePoint());
        int xOffset = glyphMetrics[0];
        xAdvance = glyphMetrics[1];

        out.println(
            "char id="
                + glyph.getCodePoint()
                + "   "
                + "x="
                + (int) (glyph.getImage().getTextureOffsetX() * pageWidth)
                + "     y="
                + (int) (glyph.getImage().getTextureOffsetY() * pageHeight)
                + "     width="
                + glyph.getWidth()
                + "     height="
                + glyph.getHeight()
                + "     xoffset="
                + xOffset
                + "     yoffset="
                + glyph.getYOffset()
                + "    xadvance="
                + xAdvance
                + "     page="
                + pageIndex
                + "  chnl=0 ");
      }
      allGlyphs.addAll(page.getGlyphs());
      pageIndex++;
    }

    String ttfFileRef = unicodeFont.getFontFile();
    if (ttfFileRef == null)
      Log.warn(
          "Kerning information could not be output because a TTF font file was not specified.");
    else {
      Kerning kerning = new Kerning();
      try {
        kerning.load(ResourceLoader.getResourceAsStream(ttfFileRef), font.getSize());
      } catch (IOException ex) {
        Log.warn("Unable to read kerning information from font: " + ttfFileRef);
      }

      Map glyphCodeToCodePoint = new HashMap();
      for (Iterator iter = allGlyphs.iterator(); iter.hasNext(); ) {
        Glyph glyph = (Glyph) iter.next();
        glyphCodeToCodePoint.put(
            new Integer(getGlyphCode(font, glyph.getCodePoint())),
            new Integer(glyph.getCodePoint()));
      }

      List kernings = new ArrayList(256);
      class KerningPair {
        public int firstCodePoint, secondCodePoint, offset;
      }
      for (Iterator iter1 = allGlyphs.iterator(); iter1.hasNext(); ) {
        Glyph firstGlyph = (Glyph) iter1.next();
        int firstGlyphCode = getGlyphCode(font, firstGlyph.getCodePoint());
        int[] values = kerning.getValues(firstGlyphCode);
        if (values == null) continue;
        for (int i = 0; i < values.length; i++) {
          Integer secondCodePoint =
              (Integer) glyphCodeToCodePoint.get(new Integer(values[i] & 0xffff));
          if (secondCodePoint == null) continue; // We may not be outputting the second character.
          int offset = values[i] >> 16;
          KerningPair pair = new KerningPair();
          pair.firstCodePoint = firstGlyph.getCodePoint();
          pair.secondCodePoint = secondCodePoint.intValue();
          pair.offset = offset;
          kernings.add(pair);
        }
      }
      out.println("kernings count=" + kerning.getCount());
      for (Iterator iter = kernings.iterator(); iter.hasNext(); ) {
        KerningPair pair = (KerningPair) iter.next();
        out.println(
            "kerning first="
                + pair.firstCodePoint
                + "  second="
                + pair.secondCodePoint
                + "  amount="
                + pair.offset);
      }
    }
    out.close();

    pageIndex = 0;
    ImageIOWriter imageWriter = new ImageIOWriter();
    for (Iterator pageIter = unicodeFont.getGlyphPages().iterator(); pageIter.hasNext(); ) {
      GlyphPage page = (GlyphPage) pageIter.next();
      String fileName;
      if (pageIndex == 0 && !pageIter.hasNext()) fileName = outputName + ".png";
      else fileName = outputName + (pageIndex + 1) + ".png";
      File imageOutputFile = new File(outputDir, fileName);
      FileOutputStream imageOutput = new FileOutputStream(imageOutputFile);
      try {
        imageWriter.saveImage(page.getImage(), "png", imageOutput, true);
      } finally {
        imageOutput.close();
      }
      // Flip output image.
      Image image = new ImageIcon(imageOutputFile.getAbsolutePath()).getImage();
      BufferedImage bufferedImage =
          new BufferedImage(
              image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
      Graphics g = bufferedImage.getGraphics();
      g.drawImage(image, 0, 0, null);
      AffineTransform tx = AffineTransform.getScaleInstance(-1, 1);
      tx.translate(0, -image.getHeight(null));
      AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
      bufferedImage = op.filter(bufferedImage, null);
      ImageIO.write(bufferedImage, "png", imageOutputFile);

      pageIndex++;
    }
  }
예제 #24
0
  /**
   * Returns the issue reporting URI. This will auto-fill the report with the relevant information
   * if possible.
   *
   * @param error a description of the error
   * @param e the exception causing the error
   * @param trace the stack trace
   * @return the created URI
   */
  private static URI getIssueURI(String error, Throwable e, String trace) {
    // generate report information
    String issueTitle = (error != null) ? error : e.getMessage();
    StringBuilder sb = new StringBuilder();
    try {
      // read version and build date from version file, if possible
      Properties props = new Properties();
      props.load(ResourceLoader.getResourceAsStream(Options.VERSION_FILE));
      String version = props.getProperty("version");
      if (version != null && !version.equals("${pom.version}")) {
        sb.append("**Version:** ");
        sb.append(version);
        String hash = Utils.getGitHash();
        if (hash != null) {
          sb.append(" (");
          sb.append(hash.substring(0, 12));
          sb.append(')');
        }
        sb.append('\n');
      }
      String timestamp = props.getProperty("build.date");
      if (timestamp != null
          && !timestamp.equals("${maven.build.timestamp}")
          && !timestamp.equals("${timestamp}")) {
        sb.append("**Build date:** ");
        sb.append(timestamp);
        sb.append('\n');
      }
    } catch (IOException e1) {
      Log.warn("Could not read version file.", e1);
    }
    sb.append("**OS:** ");
    sb.append(System.getProperty("os.name"));
    sb.append(" (");
    sb.append(System.getProperty("os.arch"));
    sb.append(")\n");
    sb.append("**JRE:** ");
    sb.append(System.getProperty("java.version"));
    sb.append('\n');
    if (glString != null) {
      sb.append("**OpenGL Version:** ");
      sb.append(glString);
      sb.append('\n');
    }
    if (error != null) {
      sb.append("**Error:** `");
      sb.append(error);
      sb.append("`\n");
    }
    if (trace != null) {
      sb.append("**Stack trace:**");
      sb.append("\n```\n");
      sb.append(trace);
      sb.append("```");
    }

    // return auto-filled URI
    try {
      return URI.create(
          String.format(
              Options.ISSUES_URL,
              URLEncoder.encode(issueTitle, "UTF-8"),
              URLEncoder.encode(sb.toString(), "UTF-8")));
    } catch (UnsupportedEncodingException e1) {
      Log.warn("URLEncoder failed to encode the auto-filled issue report URL.");
      return URI.create(String.format(Options.ISSUES_URL, "", ""));
    }
  }
예제 #25
0
  /**
   * Create a new font based on a font definition from AngelCode's tool and the font image generated
   * from the tool.
   *
   * @param fntFile The location of the font defnition file
   * @param imgFile The location of the font image
   * @throws SlickException Indicates a failure to load either file
   */
  public AngelCodeFont(String fntFile, String imgFile) throws SlickException {
    fontImage = new Image(imgFile);

    parseFnt(ResourceLoader.getResourceAsStream(fntFile));
  }
예제 #26
0
 /**
  * Get the Sound based on a specified OGG file
  *
  * @param ref The reference to the OGG file in the classpath
  * @return The Sound read from the OGG file
  * @throws IOException Indicates a failure to load the OGG
  */
 public Audio getOgg(String ref) throws IOException {
   return getOgg(ref, ResourceLoader.getResourceAsStream(ref));
 }
예제 #27
0
 /**
  * Create a new tile map based on a given TMX file
  *
  * @param ref The location of the tile map to load
  * @param loadTileSets True if we want to load tilesets - including their image data
  * @throws SlickException Indicates a failure to load the tilemap
  */
 public TiledMap(String ref, boolean loadTileSets) throws SlickException {
   this.loadTileSets = loadTileSets;
   ref = ref.replace('\\', '/');
   load(ResourceLoader.getResourceAsStream(ref), ref.substring(0, ref.lastIndexOf("/")));
 }
예제 #28
0
 /**
  * Create a new tile map based on a given TMX file
  *
  * @param ref The location of the tile map to load
  * @param tileSetsLocation The location where we can find the tileset images and other resources
  * @throws SlickException Indicates a failure to load the tilemap
  */
 public TiledMap(String ref, String tileSetsLocation) throws SlickException {
   load(ResourceLoader.getResourceAsStream(ref), tileSetsLocation);
 }
예제 #29
0
파일: Opsu.java 프로젝트: Szunti/opsu
  /** Launches opsu!. */
  public static void main(String[] args) {
    // log all errors to a file
    Log.setVerbose(false);
    try {
      DefaultLogSystem.out = new PrintStream(new FileOutputStream(Options.LOG_FILE, true));
    } catch (FileNotFoundException e) {
      Log.error(e);
    }
    Thread.setDefaultUncaughtExceptionHandler(
        new Thread.UncaughtExceptionHandler() {
          @Override
          public void uncaughtException(Thread t, Throwable e) {
            ErrorHandler.error("** Uncaught Exception! **", e, true);
          }
        });

    // parse configuration file
    Options.parseOptions();

    // only allow a single instance
    try {
      SERVER_SOCKET = new ServerSocket(Options.getPort(), 1, InetAddress.getLocalHost());
    } catch (UnknownHostException e) {
      // shouldn't happen
    } catch (IOException e) {
      ErrorHandler.error(
          String.format(
              "opsu! could not be launched for one of these reasons:\n"
                  + "- An instance of opsu! is already running.\n"
                  + "- Another program is bound to port %d. "
                  + "You can change the port opsu! uses by editing the \"Port\" field in the configuration file.",
              Options.getPort()),
          null,
          false);
      System.exit(1);
    }

    // set path for lwjgl natives - NOT NEEDED if using JarSplice
    File nativeDir = new File("./target/natives/");
    if (nativeDir.isDirectory())
      System.setProperty("org.lwjgl.librarypath", nativeDir.getAbsolutePath());

    // set the resource paths
    ResourceLoader.addResourceLocation(new FileSystemLocation(new File("./res/")));

    // initialize databases
    try {
      DBController.init();
    } catch (UnsatisfiedLinkError e) {
      errorAndExit(e, "The databases could not be initialized.");
    }

    // check if just updated
    if (args.length >= 2) Updater.get().setUpdateInfo(args[0], args[1]);

    // check for updates
    if (!Options.isUpdaterDisabled()) {
      new Thread() {
        @Override
        public void run() {
          try {
            Updater.get().checkForUpdates();
          } catch (IOException e) {
            Log.warn("Check for updates failed.", e);
          }
        }
      }.start();
    }

    // start the game
    try {
      // loop until force exit
      while (true) {
        Opsu opsu = new Opsu("opsu!");
        Container app = new Container(opsu);

        // basic game settings
        Options.setDisplayMode(app);
        String[] icons = {"icon16.png", "icon32.png"};
        app.setIcons(icons);
        app.setForceExit(true);

        app.start();

        // run update if available
        if (Updater.get().getStatus() == Updater.Status.UPDATE_FINAL) {
          close();
          Updater.get().runUpdate();
          break;
        }
      }
    } catch (SlickException e) {
      errorAndExit(e, "An error occurred while creating the game container.");
    }
  }
예제 #30
0
 public AnimationParser(ImageLib imageLib, AnimLib animLib, String animLoaderFilePath) {
   super(ResourceLoader.getResourceAsStream(animLoaderFilePath));
   this.imageLib = imageLib;
   this.animLib = animLib;
 }