;;; Sly ;;; Copyright (C) 2013, 2014 David Thompson ;;; ;;; This program is free software: you can redistribute it and/or ;;; modify it under the terms of the GNU General Public License as ;;; published by the Free Software Foundation, either version 3 of the ;;; License, or (at your option) any later version. ;;; ;;; This program is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;; General Public License for more details. ;;; ;;; You should have received a copy of the GNU General Public License ;;; along with this program. If not, see ;;; . ;;; Commentary: ;; ;; Sprites are typically the most important part of a 2D game. This ;; module provides sprites as an abstraction around OpenGL textures. ;; ;;; Code: (define-module (sly render sprite) #:use-module (srfi srfi-1) #:use-module (srfi srfi-9) #:use-module (gl) #:use-module (sly agenda) #:use-module (sly utils) #:use-module (sly render) #:use-module (sly render color) #:use-module (sly render mesh) #:use-module (sly render texture) #:use-module (sly render utils) #:use-module (sly math vector) #:export (make-sprite null-sprite load-sprite sprite? sprite-texture sprite-mesh render-sprite)) (define-record-type (%make-sprite texture mesh) sprite? (texture sprite-texture) (mesh sprite-mesh)) (define null-sprite (%make-sprite null-texture null-mesh)) (define* (make-sprite texture #:key (anchor 'center)) "Create a sprite that displays the image in TEXTURE. The size of the mesh is the size of TEXTURE in pixels. ANCHOR defines the origin of the sprite. By default, the anchor is 'center', which puts the origin in the middle of the sprite. See 'anchor-texture' for more anchoring options." (let* ((anchor (anchor-texture texture anchor)) (x1 (- (floor (vx anchor)))) (y1 (- (floor (vy anchor)))) (x2 (+ x1 (texture-width texture))) (y2 (+ y1 (texture-height texture))) (s1 (texture-s1 texture)) (t1 (texture-t1 texture)) (s2 (texture-s2 texture)) (t2 (texture-t2 texture)) (mesh (build-mesh #(0 3 2 0 2 1) (vector (vector3 x1 y1 0) (vector3 x2 y1 0) (vector3 x2 y2 0) (vector3 x1 y2 0)) (vector (vector2 s1 t1) (vector2 s2 t1) (vector2 s2 t2) (vector2 s1 t2))))) (%make-sprite texture mesh))) (define* (load-sprite file #:key (anchor 'center)) "Create a sprite from the texture in FILE whose origin is defined by ANCHOR. The default anchor is 'center'." (make-sprite (load-texture file) #:anchor anchor)) (define* (render-sprite sprite) "Create a renderer that draws a 2D rectangular mesh that displays the image TEXTURE. The size of the mesh is the size of TEXTURE in pixels." (with-texture (sprite-texture sprite) (render-mesh (sprite-mesh sprite))))