/* * Copyright (c) 2018-2019. Developed by Hedgecode. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hedgecode.chess.img.piece; import java.awt.image.BufferedImage; import java.util.HashMap; import java.util.Map; import org.hedgecode.chess.img.AbstractImageLoader; import org.hedgecode.chess.img.FilenameUtils; import org.hedgecode.chess.img.ImageConstants; import org.hedgecode.chess.img.ImageException; import org.hedgecode.chess.img.ImageFilter; /** * Loader for chess piece's set of images. * * @author Dmitry Samoshin aka gotty */ public class PieceSetLoader extends AbstractImageLoader { private static final String PIECES_DIR = ImageConstants.RESOURCE_PIECES_DIR; private static final String[] PIECES_NAMES = PieceSet.getAllPieceNames(); private Map pieceSetMap = new HashMap<>(); @Override public PieceSet load(String name) throws ImageException { PieceSet pieceSet; if (Type.STATELESS.equals(loadType()) || !pieceSetMap.containsKey(name)) { String piecePath = FilenameUtils.getFullPath(PIECES_DIR, name); pieceSet = loadPieces(piecePath); if (Type.STATEFUL.equals(loadType())) { pieceSetMap.put(name, pieceSet); } } else { pieceSet = pieceSetMap.get(name); } return pieceSet; } @Override public void unload(String name) { if (Type.STATEFUL.equals(loadType()) && pieceSetMap.containsKey(name)) { pieceSetMap.remove(name); } } @Override protected void clear() { pieceSetMap.clear(); } private PieceSet loadPieces(String piecePath) throws ImageException { PieceSet pieceSet = PieceSet.create(); Map images = loadImages( piecePath, new ImageFilter(PIECES_NAMES) ); for (String name : PIECES_NAMES) { pieceSet.add( name, images.get(name) ); } if (!pieceSet.isFilled()) { throw new ImageException("image.incomplete.piece.set", piecePath); } return pieceSet; } }