repo
string | commit
string | message
string | diff
string |
---|---|---|---|
devnev/skyways
|
a55ab686460f28487e2e677e2f955bccda771635
|
Rewrote build system to use per-dir makefiles.
|
diff --git a/Config.mk.in b/Config.mk.in
new file mode 100644
index 0000000..495edce
--- /dev/null
+++ b/Config.mk.in
@@ -0,0 +1,34 @@
+#!/usr/bin/make -f
+# @configure_input@
+
+$(if $(MK_INCLUDE),,$(error This makefile is meant for inclusion by other makefiles))
+
+prefix=@prefix@
+datarootdir=@datarootdir@
+datadir=@datadir@
+appdatadir=${datadir}/@PACKAGE_TARNAME@
+srcdir=@srcdir@
+vpath %.c @srcdir@
+vpath %.cpp @srcdir@
+vpath %.hpp @srcdir@
+vpath %.o @builddir@
+vpath %.d @builddir@
+
+MODULES := @modules@
+
+@glut_backend_stmt@SkywaysGlut_BINARY := skyways.glut
+@qt_backend_stmt@SkywaysQt_BINARY := skyways.qt
+@sdl_backend_stmt@SkywaysSdl_BINARY := skyways.sdl
+
+CFLAGS := @CFLAGS@ -Wall $(CFLAGS)
+CXXFLAGS := @CXXFLAGS@ -Wall $(CXXFLAGS)
+CPPFLAGS := @CPPFLAGS@ -Wall @FTGL_CFLAGS@ @BOOST_CPPFLAGS@ -I@top_srcdir@/src -DDATADIR='"$(appdatadir)"' $(CPPFLAGS)
+LDFLAGS := @LDFLAGS@ @BOOST_LDFLAGS@ $(LDFLAGS)
+LIBS := @LIBS@ @FTGL_LIBS@ @BOOST_FILESYSTEM_LIB@ $(LIBS)
+
+@glut_backend_stmt@SkywaysGlut_LIBS=@GLUT_LIBS@ @BOOST_PROGRAM_OPTIONS_LIB@
+@qt_backend_stmt@SkywaysQt_CPPFLAGS=-D_REENTRANT -DQT_NO_DEBUG -DQT_OPENGL_LIB -DQT_GUI_LIB -DQT_CORE_LIB @QT_CFLAGS@
+@qt_backend_stmt@SkywaysQt_LIBS=@QT_LIBS@
+@qt_backend_stmt@SkywaysQt_OBJECTS=src/backends/moc_qtwindow_SkywaysQt.o
+@sdl_backend_stmt@SkywaysSdl_CPPFLAGS=@SDL_CFLAGS@
+@sdl_backend_stmt@SkywaysSdl_LIBS=@SDL_LIBS@ @BOOST_PROGRAM_OPTIONS_LIB@
diff --git a/Dir.mk b/Dir.mk
new file mode 100644
index 0000000..6bccc68
--- /dev/null
+++ b/Dir.mk
@@ -0,0 +1,10 @@
+#!/usr/bin/make -f
+
+$(if $(MK_INCLUDE),,$(error This makefile is meant for inclusion by other makefiles))
+$(eval $(call enter_directory))
+
+SUBDIRS := src
+
+$(eval $(call leave_directory))
+
+# vim: ft=make
diff --git a/Dir.mk.tpl b/Dir.mk.tpl
new file mode 100644
index 0000000..66da189
--- /dev/null
+++ b/Dir.mk.tpl
@@ -0,0 +1,16 @@
+#!/usr/bin/make -f
+
+$(if $(MK_INCLUDE),,$(error This makefile is meant for inclusion by other makefiles))
+$(eval $(call enter_directory))
+
+CSOURCES_$(sp) :=
+CXXSOURCES_$(sp) :=
+HEADERS_$(sp) :=
+CSOURCES_module_$(sp) :=
+CXXSOURCES_module_$(sp) :=
+HEADERS_module_$(sp) :=
+SUBDIRS :=
+
+$(eval $(call leave_directory))
+
+# vim: ft=make
diff --git a/Makefile.in b/Makefile.in
index a1779c7..a65567c 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -1,214 +1,10 @@
#!/usr/bin/make
# @configure_input@
-
-######################################
-# configuration: change things here. #
-######################################
-
-prefix=@prefix@
-datarootdir=@datarootdir@
-datadir=@datadir@
-appdatadir=${datadir}/@PACKAGE_TARNAME@
-srcdir=@srcdir@
-vpath %.c @srcdir@
-vpath %.cpp @srcdir@
-vpath %.hpp @srcdir@
-vpath %.o @builddir@
-vpath %.d @builddir@
-
-PROGRAMS?=@programs@
-
-SkywaysGlut_BINARY=skyways.glut
-SkywaysQt_BINARY=skyways.qt
-SkywaysSdl_BINARY=skyways.sdl
-
-Common_HEADERS= \
- src/configuration.hpp \
- src/controller.hpp \
- src/display/shader.hpp \
- src/display/textprinter.hpp \
- src/display/uniform.hpp \
- src/game.hpp \
- src/loading/blockloader.hpp \
- src/loading/mapgenerator.hpp \
- src/loading/maploader.hpp \
- src/loading/objmodel.hpp \
- src/range.hpp \
- src/vector.hpp \
- src/world/aabb.hpp \
- src/world/block.hpp \
- src/world/collisionaccelerator.hpp \
- src/world/element.hpp \
- src/world/map.hpp \
- src/world/model.hpp \
- src/world/ship.hpp \
- #
-
-SkywaysGlut_HEADERS= $(Common_HEADERS) \
- src/backends/configparser.hpp \
- #
-
-SkywaysQt_HEADERS= $(Common_HEADERS) \
- src/backends/qtconfigparser.hpp \
- src/backends/qtwindow.hpp \
- #
-
-SkywaysSdl_HEADERS= $(Common_HEADERS) \
- src/backends/configparser.hpp \
- #
-
-Common_CXXSOURCES= \
- src/configuration.cpp \
- src/controller.cpp \
- src/display/shader.cpp \
- src/display/textprinter.cpp \
- src/game.cpp \
- src/loading/blockloader.cpp \
- src/loading/mapgenerator.cpp \
- src/loading/maploader.cpp \
- src/loading/objmodel.cpp \
- src/world/block.cpp \
- src/world/collisionaccelerator.cpp \
- src/world/element.cpp \
- src/world/map.cpp \
- src/world/ship.cpp \
- #
-
-SkywaysGlut_CXXSOURCES= $(Common_CXXSOURCES) \
- src/backends/configparser.cpp \
- src/backends/glutmain.cpp \
- #
-
-SkywaysQt_CXXSOURCES= $(Common_CXXSOURCES) \
- src/backends/qtconfigparser.cpp \
- src/backends/qtmain.cpp \
- src/backends/qtwindow.cpp \
- #
-
-SkywaysSdl_CXXSOURCES= $(Common_CXXSOURCES) \
- src/backends/configparser.cpp \
- src/backends/sdlmain.cpp \
- #
-
-CFLAGS:= @CFLAGS@ -Wall $(CFLAGS)
-CXXFLAGS:= @CXXFLAGS@ -Wall $(CXXFLAGS)
-CPPFLAGS:= @CPPFLAGS@ -Wall @FTGL_CFLAGS@ @BOOST_CPPFLAGS@ $(CPPFLAGS) -I@top_srcdir@/src -DDATADIR='"${appdatadir}"'
-LDFLAGS:= @LDFLAGS@ @BOOST_LDFLAGS@ $(LDFLAGS)
-LIBS:=@LIBS@ @FTGL_LIBS@ @BOOST_FILESYSTEM_LIB@ $(LIBS)
-
-SkywaysGlut_LIBS=@GLUT_LIBS@ @BOOST_PROGRAM_OPTIONS_LIB@
-SkywaysQt_CPPFLAGS=-D_REENTRANT -DQT_NO_DEBUG -DQT_OPENGL_LIB -DQT_GUI_LIB -DQT_CORE_LIB @QT_CFLAGS@
-SkywaysQt_LIBS=@QT_LIBS@
-SkywaysQt_OBJECTS=src/backends/moc_qtwindow_SkywaysQt.o
-SkywaysSdl_CPPFLAGS=@SDL_CFLAGS@
-SkywaysSdl_LIBS=@SDL_LIBS@ @BOOST_PROGRAM_OPTIONS_LIB@
-
-EXTRADIST=configure.ac Makefile.in configure config.h.in aclocal.m4 \
- shaders/shader.glslf shaders/shader.glslv DejaVuSans.ttf\
- blocks/cube blocks/flat blocks/tunnel world \
- COPYING README
-
-######################################
-# auto-configuration: do not change! #
-######################################
-
-CWD:=$(shell pwd)
-
+#
default: all
+ @:
-$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_SOURCES=$($(prog)_SOURCES) $($(prog)_CSOURCES) $($(prog)_CXXSOURCES)))
-$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_OBJECTS=$($(prog)_OBJECTS) $(patsubst %.c,%_$(prog).o,$($(prog)_CSOURCES)) $(patsubst %.cpp,%_$(prog).o,$($(prog)_CXXSOURCES))))
-$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_HEADERS=$($(prog)_HEADERS)))
-$(foreach flag,CFLAGS CPPFLAGS CXXFLAGS LDFLAGS LIBS,$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_$(flag)=$($(flag)) $($(prog)_$(flag)))))
-
-SOURCES=$(foreach prog,$(PROGRAMS),$($(prog)_ALL_SOURCES))
-HEADERS=$(foreach prog,$(PROGRAMS),$($(prog)_ALL_HEADERS))
-OBJECTS=$(foreach prog,$(PROGRAMS),$($(prog)_ALL_OBJECTS))
-BINARIES=$(foreach prog,$(PROGRAMS),$($(prog)_BINARY))
-DEPENDS=$(patsubst %.o,%.d,$(OBJECTS))
-
-define CDEP_template
- %_$(1).d: %.c $$($(1)_ALL_HEADERS)
- @mkdir -p "`dirname $$@`"
- @set -e; rm -f "$$@" || true; \
- $$(CC) -MM -MQ "`echo "$$@" | sed 's/\.d$$$$/.o'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) "$$<" > $$@
- @echo @ECHO_N@ ".@ECHO_C@"
-endef
-
-define CXXDEP_template
- %_$(1).d: %.cpp $$($(1)_ALL_HEADERS)
- @mkdir -p "`dirname $$@`"
- @set -e; rm -f "$$@" || true; \
- $$(CXX) -MM -MQ "`echo "$$<" | sed 's,\($$*\)\.cpp,\1_$(1).o,'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) "$$<" > $$@
- @echo @ECHO_N@ ".@ECHO_C@"
-endef
-
-define CSRC_template
- %_$(1).o: %.c
- $$(CC) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) $$< -o $$@
-endef
-
-define CXXSRC_template
- %_$(1).o: %.cpp
- $$(CXX) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) $$< -o $$@
-endef
-
-define BINARY_template
- $$($(1)_BINARY): $$($(1)_ALL_OBJECTS)
- $$(CC) $$($(1)_ALL_LDFLAGS) $$($(1)_ALL_LIBS) $$^ $$(LOADLIBS) $$(LDLIBS) -o $$@
-endef
-
-$(foreach template,CDEP CXXDEP CSRC CXXSRC BINARY,$(foreach prog,$(PROGRAMS),$(eval $(call $(template)_template,$(prog)))))
-
-all: $(BINARIES)
-
-# this rule is just to add a newline after the dots from deps calculation
-Makefile: $(DEPENDS)
- @echo
- @touch $@
-
-%.tar.gz:
- rm -f $@
- echo $(patsubst @top_srcdir@/%,%,$(filter @top_srcdir@/%,$^)) | tr ' ' '\n' | tar -C @top_srcdir@ -cf $(patsubst %.gz,%,$@) --files-from=-
- tar -rf $(patsubst %.gz,%,$@) $(filter-out @top_srcdir@/%,$^)
- gzip $(patsubst %.gz,%,$@)
-
-@[email protected]: $(SOURCES) $(HEADERS) $(EXTRADIST)
-
-DISTFILES=@[email protected]
-
-dist: $(DISTFILES)
-
-distcheck: dist
- mkdir .dist-check
- tar -C .dist-check -xzf @[email protected]
- (cd .dist-check && ./configure && $(MAKE) && $(MAKE) dist)
- cp .dist-check/@[email protected] .
- rm -rf .dist-check
-
-#################################
-# extra stuff: change as needed #
-#################################
-
-AC_OUTPUT=configure config.h.in aclocal.m4
-AC_OUTPUT_DIRS=autom4te.cache
-CONFIG_OUTPUT=config.h Makefile config.log config.status
-
-clean:
- rm -f $(OBJECTS) $(BINARIES) $(DEPENDS) $(DISTFILES) src/backends/moc_qtwindow.cpp || true
-
-clean-config:
- rm -f $(CONFIG_OUTPUT) || true
-
-clean-ac:
- rm -f $(AC_OUTPUT) || true
- rm -rf $(AC_OUTPUT_DIRS) || true
-
-clean-full: clean clean-config clean-ac
-
-moc_%.cpp: %.hpp
- moc-qt4 $(SkywaysQt_CPPFLAGS) $(SkywaysQt_CXXFLAGS) $< -o $@
-
-.PHONY: default dist clean clean-config clean-ac clean-full
+.PHONY: default
--include $(DEPENDS)
+%::
+ $(MAKE) -r --no-print-directory -f @top_srcdir@/Rules.mk BUILDDIR=@builddir@ SRCDIR=@top_srcdir@ $@
diff --git a/Rules.mk b/Rules.mk
new file mode 100644
index 0000000..9f3d662
--- /dev/null
+++ b/Rules.mk
@@ -0,0 +1,116 @@
+
+default: all
+
+MK_INCLUDE:=1
+SRCDIR:=.
+BUILDDIR:=.
+DEPDIR:=.deps
+
+include $(BUILDDIR)/Config.mk
+
+define enter_directory
+ $$(if $$(directory),,$$(error Set the `directory` variable before including this makefile in other makefiles))
+ supsp := $$(sp)
+ sp := $$(lastsp).x
+ lastsp := $$(sp)
+ sp_list := $$(sp_list) $$(sp)
+ dirstack_$$(sp) := $$(d)
+ d := $$(directory)
+ DIRECTORIES := $$(DIRECTORIES) $$(d)
+endef
+
+define leave_directory
+ SUBDIRS_$$(sp) := $$(SUBDIRS)
+ SUBDIRS :=
+ $$(if $$(SUBDIRS_$$(sp)),$$(eval $$(call include_subdir_list,$$(SUBDIRS_$$(sp)))),)
+ d := $$(dirstack_$$(sp))
+ sp := $$(supsp)
+endef
+
+define include_subdir
+ directory := $$(d)/$(1)
+ include $$(SRCDIR)/$$(directory)/Dir.mk
+endef
+
+define include_subdir_list
+ $$(foreach subdir,$(1),$$(eval $$(call include_subdir,$$(subdir))))
+endef
+
+directory := .
+include $(SRCDIR)/Dir.mk
+
+define csrcall_moddir_tpl
+ CSOURCES_$(1)_$(2):=$$(CSOURCES_$(1)_$(2)) $$(CSOURCES_$(2))
+ CSOURCES_$(1):=$$(CSOURCES_$(1)) $$(CSOURCES_$(1)_$(2))
+endef
+define cxxsrcall_moddir_tpl
+ CXXSOURCES_$(1)_$(2):=$$(CXXSOURCES_$(1)_$(2)) $$(CXXSOURCES_$(2))
+ CXXSOURCES_$(1):=$$(CXXSOURCES_$(1)) $$(CXXSOURCES_$(1)_$(2))
+endef
+define hdrall_moddir_tpl
+ HEADERS_$(1)_$(2):=$$(HEADERS_$(1)_$(2)) $$(HEADERS_$(2))
+ HEADERS_$(1):=$$(HEADERS_$(1)) $$(HEADERS_$(1)_$(2))
+endef
+define objects_moddir_tpl
+ OBJECTS_$(1)_$(2):=$$(OBJECTS_$(1)_$(2)) $$(patsubst %.c,%_$(1).o,$$(CSOURCES_$(1)_$(2)))
+ OBJECTS_$(1)_$(2):=$$(OBJECTS_$(1)_$(2)) $$(patsubst %.cpp,%_$(1).o,$$(CXXSOURCES_$(1)_$(2)))
+ OBJECTS_$(1):=$$(OBJECTS_$(1)) $$(OBJECTS_$(1)_$(2))
+endef
+MODDIR_TEMPLATES := $(MODDIR_TEMPLATES) \
+ csrcall_moddir_tpl cxxsrcall_moddir_tpl hdrall_moddir_tpl objects_moddir_tpl
+
+define process_module_directory
+ $$(foreach tpl,$$(MODDIR_TEMPLATES),$$(eval $$(call $$(tpl),$(1),$(2))))
+endef
+
+define FLAGS_mod_template
+ $$(foreach flag,CFLAGS CXXFLAGS CPPFLAGS LDFLAGS LIBS,$$(eval $$(flag)_$(1):=$$($$(flag)) $$($(1)_$$(flag)) $$($$(flag)_$(1))))
+endef
+define C_mod_template
+ %_$(1).o: %.c
+ $$(CC) $$(CFLAGS_$(1)) $$(CPPFLAGS_$(1)) -MT $$@ -MD -MP -MF $$(dir $$*)$$(DEPDIR)/$$(notdir $$*)_$(1).Td -c -o $$@ $$<
+ mv -f $$(dir $$*)$$(DEPDIR)/$$(notdir $$*)_$(1).Td $$(dir $$*)$$(DEPDIR)/$$(notdir $$*)_$(1).d
+endef
+define CXX_mod_template
+ %_$(1).o: %.cpp
+ $$(CXX) $$(CXXFLAGS_$(1)) $$(CPPFLAGS_$(1)) -MT $$@ -MD -MP -MF $$(dir $$*)$$(DEPDIR)/$$(notdir $$*)_$(1).Td -c -o $$@ $$<
+ mv -f $$(dir $$*)$$(DEPDIR)/$$(notdir $$*)_$(1).Td $$(dir $$*)$$(DEPDIR)/$$(notdir $$*)_$(1).d
+endef
+define LD_mod_template
+ $$($(1)_BINARY): $$(OBJECTS_$(1))
+ $$(LINK.o) $$(LDFLAGS_$(1)) $$(LIBS_$(1)) $$^ $$(LOADLIBES) $$(LDLIBS) -o $$@
+endef
+MOD_TEMPLATES := $(MOD_TEMPLATES) FLAGS_mod_template C_mod_template CXX_mod_template LD_mod_template
+
+define process_module
+ $$(foreach sp,$$(sp_list),$$(eval $$(call process_module_directory,$(1),$$(sp))))
+ $$(foreach tpl,$$(MOD_TEMPLATES),$$(eval $$(call $$(tpl),$(1))))
+endef
+
+define process_modules
+ $$(foreach mod,$(1),$$(eval $$(call process_module,$$(mod))))
+ OBJECTS:=$$(foreach mod,$(1),$$(OBJECTS_$$(mod)))
+ BINARIES:=$$(foreach mod,$(1),$$($$(mod)_BINARY))
+ #DEPENDS:=$$(foreach obj,$$(OBJECTS),$$(dir $$(obj))$$(DEPDIR)/$$(basename $$(obj)).d)
+ DEPENDS:=$$(join $$(dir $$(OBJECTS)),$$(addprefix $$(DEPDIR)/,$$(addsuffix .d,$$(basename $$(notdir $$(OBJECTS))))))
+endef
+
+$(eval $(call process_modules,$(MODULES)))
+-include $(DEPENDS)
+
+CLEAN:=$(CLEAN) $(OBJECTS) $(BINARIES) $(DEPENDS)
+
+.PHONY: default all
+all: $(BINARIES)
+
+.PHONY: clean
+clean:
+ rm -f $(CLEAN) || true
+
+.PHONY: force
+force:
+ @/bin/true
+
+$(SRCDIR)/Rules.mk: force
+ @mkdir -p $(patsubst %,$(BUILDDIR)/%,$(DIRECTORIES)) $(patsubst %,$(BUILDDIR)/%/$(DEPDIR),$(DIRECTORIES))
+
diff --git a/configure.ac b/configure.ac
index 079ce94..620a5ae 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,111 +1,123 @@
# -*- Autoconf -*-
# vim: ft=m4
# Process this file with autoconf to produce a configure script.
AC_PREREQ([2.63])
AC_INIT([skyways], [0.0.1], [[email protected]])
AC_CONFIG_MACRO_DIR([m4])
AC_CONFIG_SRCDIR([src/configuration.hpp])
AC_CONFIG_HEADERS([config.h])
# Checks for programs.
AC_PROG_CXX
PKG_PROG_PKG_CONFIG
# Checks for libraries.
AC_CHECK_LIB([GL], [glGetString])
AC_CHECK_LIB([GLEW], [glewInit])
PKG_CHECK_MODULES([FTGL],[ftgl >= 2.1])
AX_BOOST_BASE([1.34.0])
AX_BOOST_FILESYSTEM
AX_BOOST_PROGRAM_OPTIONS
-programs=""
+modules=""
AC_ARG_ENABLE([qt], AS_HELP_STRING([--enable-qt], [Enable Qt backend (default: test)]),
[ if test "x$enableval" = "xyes" ; then qt_backend=yes
elif test "x$enableval" = "xtest" ; then qt_backend=test
elif test "x$enableval" = "xno" ; then qt_backend=no
else echo "Error: unknown --enable-qt option $enableval" ; exit 1
fi
],
[ qt_backend=test
])
if test "x$qt_backend" == "xyes" ; then
PKG_CHECK_MODULES([QT],[QtCore >= 4.5.0 QtGui >= 4.5.0 QtOpenGL >= 4.5.0])
AC_CHECK_LIB([pthread],[pthread_create],[QT_LIBS="-lpthread $QT_LIBS"])
AC_CHECK_LIB([GLU], [gluGetString],[QT_LIBS="-lGLU $QT_LIBS"])
elif test "x$qt_backend" == "xtest" ; then
PKG_CHECK_MODULES([QT],[QtCore >= 4.5.0 QtGui >= 4.5.0 QtOpenGL >= 4.5.0],[qt_backend="yes"],[qt_backend="no"])
if test "x$qt_backend" = "xyes" ; then
AC_CHECK_LIB([pthread],[pthread_create],[QT_LIBS="-lpthread $QT_LIBS"; qt_backend="yes"],[qt_backend="no"])
fi
if test "x$qt_backend" = "xyes" ; then
AC_CHECK_LIB([GLU], [gluGetString],[QT_LIBS="-lGLU $QT_LIBS"; qt_backend="yes"],[qt_backend="no"])
fi
fi
-AC_SUBST(qt_backend)
if test "x$qt_backend" = "xyes" ; then
- programs="SkywaysQt $programs"
+ modules="SkywaysQt $modules"
+ qt_backend_stmt=""
+else
+ qt_backend_stmt="#"
fi
+AC_SUBST(qt_backend)
+AC_SUBST(qt_backend_stmt)
AC_ARG_ENABLE([sdl], AS_HELP_STRING([--enable-sdl], [Enable SDL backend (default: test)]),
[ if test "x$enableval" = "xyes" ; then sdl_backend=yes
elif test "x$enableval" = "xtest" ; then sdl_backend=test
elif test "x$enableval" = "xno" ; then sdl_backend=no
else echo "Error: unknown --enable-sdl option $enableval" ; exit 1
fi
],
[ sdl_backend=test
])
if test "x$sdl_backend" == "xyes" ; then
PKG_CHECK_MODULES([SDL],[sdl >= 1.2.13])
elif test "x$sdl_backend" == "xtest" ; then
PKG_CHECK_MODULES([SDL],[sdl >= 1.2.13],[sdl_backend="yes"],[sdl_backend="no"])
fi
-AC_SUBST(sdl_backend)
if test "x$sdl_backend" = "xyes" ; then
- programs="SkywaysSdl $programs"
+ modules="SkywaysSdl $modules"
+ sdl_backend_stmt=""
+else
+ sdl_backend_stmt="#"
fi
+AC_SUBST(sdl_backend)
+AC_SUBST(sdl_backend_stmt)
AC_ARG_ENABLE([glut], AS_HELP_STRING([--enable-glut], [Enable GLUT backend (default: test)]),
[ if test "x$enableval" = "xyes" ; then glut_backend=yes
elif test "x$enableval" = "xtest" ; then glut_backend=test
elif test "x$enableval" = "xno" ; then glut_backend=no
else echo "Error: unknown --enable-glut option $enableval" ; exit 1
fi
],
[ glut_backend=test
])
if test "x$glut_backend" == "xyes" ; then
AC_CHECK_LIB([glut],[glutMainLoop],[GLUT_LIBS="-lglut"])
elif test "x$glut_backend" == "xtest" ; then
AC_CHECK_LIB([glut],[glutMainLoop],[GLUT_LIBS="-lglut"; glut_backend="yes"],[glut_backend="no"])
fi
-AC_SUBST(glut_backend)
-AC_SUBST(GLUT_LIBS)
if test "x$glut_backend" = "xyes" ; then
- programs="SkywaysGlut $programs"
+ modules="SkywaysGlut $modules"
+ glut_backend_stmt=""
+else
+ glut_backend_stmt="#"
fi
+AC_SUBST(glut_backend)
+AC_SUBST(GLUT_LIBS)
+AC_SUBST(glut_backend_stmt)
-if test -z "$programs" ; then
+if test -z "$modules" ; then
echo "Error: no backends will be built, aborting."
exit 1
fi
-AC_SUBST(programs)
+AC_SUBST(modules)
# Checks for header files.
# Checks for typedefs, structures, and compiler characteristics.
# Checks for library functions.
-AC_CONFIG_FILES([Makefile])
+AC_CONFIG_FILES([Makefile Config.mk])
AC_OUTPUT
echo "Configuration complete. Backends to be built:"
echo " Qt backend... $qt_backend"
echo " SDL backend... $sdl_backend"
echo " GLUT backend... $glut_backend"
diff --git a/src/Dir.mk b/src/Dir.mk
new file mode 100644
index 0000000..9aa59f2
--- /dev/null
+++ b/src/Dir.mk
@@ -0,0 +1,13 @@
+#!/usr/bin/make -f
+
+$(if $(MK_INCLUDE),,$(error This makefile is meant for inclusion by other makefiles))
+$(eval $(call enter_directory))
+
+CXXSOURCES_$(sp) := $(d)/configuration.cpp $(d)/controller.cpp $(d)/game.cpp
+HEADERS_$(sp) := $(d)/configuration.hpp $(d)/controller.hpp $(d)/game.hpp $(d)/range.hpp $(d)/vector.hpp
+
+SUBDIRS := backends display loading world
+
+$(eval $(call leave_directory))
+
+# vim: ft=make
diff --git a/src/backends/Dir.mk b/src/backends/Dir.mk
new file mode 100644
index 0000000..9bfb815
--- /dev/null
+++ b/src/backends/Dir.mk
@@ -0,0 +1,19 @@
+#!/usr/bin/make -f
+
+$(if $(MK_INCLUDE),,$(error This makefile is meant for inclusion by other makefiles))
+$(eval $(call enter_directory))
+
+CXXSOURCES_SkywaysQt_$(sp) := $(d)/qtconfigparser.cpp $(d)/qtmain.cpp $(d)/qtwindow.cpp
+CXXSOURCES_SkywaysSdl_$(sp) := $(d)/configparser.cpp $(d)/sdlmain.cpp
+CXXSOURCES_SkywaysGlut_$(sp) := $(d)/configparser.cpp $(d)/glutmain.cpp
+HEADERS_SkywaysQt_$(sp) := $(d)/qtconfigparser.hpp $(d)/qtwindow.hpp
+HEADERS_SkywaysSdl_$(sp) := $(d)/configparser.hpp
+HEADERS_SkywaysGlut_$(sp) := $(d)/configparser.hpp
+OBJECTS_SkywaysQt_$(sp) := $(d)/moc_qtwindow_SkywaysQt.o
+
+moc_%.cpp: %.hpp
+ moc-qt4 $(SkywaysQt_CPPFLAGS) $(SkywaysQt_CXXFLAGS) $< -o $@
+
+$(eval $(call leave_directory))
+
+# vim: ft=make
diff --git a/src/display/Dir.mk b/src/display/Dir.mk
new file mode 100644
index 0000000..335251b
--- /dev/null
+++ b/src/display/Dir.mk
@@ -0,0 +1,11 @@
+#!/usr/bin/make -f
+
+$(if $(MK_INCLUDE),,$(error This makefile is meant for inclusion by other makefiles))
+$(eval $(call enter_directory))
+
+CXXSOURCES_$(sp) := $(d)/shader.cpp $(d)/textprinter.cpp
+HEADERS_$(sp) := $(d)/shader.hpp $(d)/textprinter.hpp $(d)/uniform.hpp
+
+$(eval $(call leave_directory))
+
+# vim: ft=make
diff --git a/src/loading/Dir.mk b/src/loading/Dir.mk
new file mode 100644
index 0000000..3436fe2
--- /dev/null
+++ b/src/loading/Dir.mk
@@ -0,0 +1,11 @@
+#!/usr/bin/make -f
+
+$(if $(MK_INCLUDE),,$(error This makefile is meant for inclusion by other makefiles))
+$(eval $(call enter_directory))
+
+CXXSOURCES_$(sp) := $(d)/blockloader.cpp $(d)/mapgenerator.cpp $(d)/maploader.cpp $(d)/objmodel.cpp
+HEADERS_$(sp) := $(d)/blockloader.hpp $(d)/mapgenerator.hpp $(d)/maploader.hpp $(d)/objmodel.hpp
+
+$(eval $(call leave_directory))
+
+# vim: ft=make
diff --git a/src/world/Dir.mk b/src/world/Dir.mk
new file mode 100644
index 0000000..d44f467
--- /dev/null
+++ b/src/world/Dir.mk
@@ -0,0 +1,11 @@
+#!/usr/bin/make -f
+
+$(if $(MK_INCLUDE),,$(error This makefile is meant for inclusion by other makefiles))
+$(eval $(call enter_directory))
+
+CXXSOURCES_$(sp) := $(d)/block.cpp $(d)/collisionaccelerator.cpp $(d)/element.cpp $(d)/map.cpp $(d)/ship.cpp
+HEADERS_$(sp) := $(d)/aabb.hpp $(d)/block.hpp $(d)/collisionaccelerator.hpp $(d)/element.hpp $(d)/map.hpp $(d)/model.hpp $(d)/ship.hpp
+
+$(eval $(call leave_directory))
+
+# vim: ft=make
diff --git a/testbuild.sh b/testbuild.sh
index 858f241..ea552c2 100755
--- a/testbuild.sh
+++ b/testbuild.sh
@@ -1,5 +1,5 @@
#!/bin/sh
mkdir -p build && \
cd build && \
../configure --prefix=`pwd` && \
- make appdatadir=`pwd`/..
+ make appdatadir=.
|
devnev/skyways
|
7fcb93946db4236c372161b4e3f912969f62bab8
|
Added support for compile-time relocatable data directory.
|
diff --git a/Makefile.in b/Makefile.in
index 74cb70a..a1779c7 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -1,207 +1,214 @@
#!/usr/bin/make
# @configure_input@
######################################
# configuration: change things here. #
######################################
+prefix=@prefix@
+datarootdir=@datarootdir@
+datadir=@datadir@
+appdatadir=${datadir}/@PACKAGE_TARNAME@
+srcdir=@srcdir@
+vpath %.c @srcdir@
+vpath %.cpp @srcdir@
+vpath %.hpp @srcdir@
+vpath %.o @builddir@
+vpath %.d @builddir@
+
PROGRAMS?=@programs@
SkywaysGlut_BINARY=skyways.glut
SkywaysQt_BINARY=skyways.qt
SkywaysSdl_BINARY=skyways.sdl
Common_HEADERS= \
src/configuration.hpp \
src/controller.hpp \
src/display/shader.hpp \
src/display/textprinter.hpp \
src/display/uniform.hpp \
src/game.hpp \
src/loading/blockloader.hpp \
src/loading/mapgenerator.hpp \
src/loading/maploader.hpp \
src/loading/objmodel.hpp \
src/range.hpp \
src/vector.hpp \
src/world/aabb.hpp \
src/world/block.hpp \
src/world/collisionaccelerator.hpp \
src/world/element.hpp \
src/world/map.hpp \
src/world/model.hpp \
src/world/ship.hpp \
#
SkywaysGlut_HEADERS= $(Common_HEADERS) \
src/backends/configparser.hpp \
#
SkywaysQt_HEADERS= $(Common_HEADERS) \
src/backends/qtconfigparser.hpp \
src/backends/qtwindow.hpp \
#
SkywaysSdl_HEADERS= $(Common_HEADERS) \
src/backends/configparser.hpp \
#
Common_CXXSOURCES= \
src/configuration.cpp \
src/controller.cpp \
src/display/shader.cpp \
src/display/textprinter.cpp \
src/game.cpp \
src/loading/blockloader.cpp \
src/loading/mapgenerator.cpp \
src/loading/maploader.cpp \
src/loading/objmodel.cpp \
src/world/block.cpp \
src/world/collisionaccelerator.cpp \
src/world/element.cpp \
src/world/map.cpp \
src/world/ship.cpp \
#
SkywaysGlut_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/configparser.cpp \
src/backends/glutmain.cpp \
#
SkywaysQt_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/qtconfigparser.cpp \
src/backends/qtmain.cpp \
src/backends/qtwindow.cpp \
#
SkywaysSdl_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/configparser.cpp \
src/backends/sdlmain.cpp \
#
CFLAGS:= @CFLAGS@ -Wall $(CFLAGS)
CXXFLAGS:= @CXXFLAGS@ -Wall $(CXXFLAGS)
-CPPFLAGS:= @CPPFLAGS@ -Wall @FTGL_CFLAGS@ @BOOST_CPPFLAGS@ $(CPPFLAGS) -I@top_srcdir@/src
+CPPFLAGS:= @CPPFLAGS@ -Wall @FTGL_CFLAGS@ @BOOST_CPPFLAGS@ $(CPPFLAGS) -I@top_srcdir@/src -DDATADIR='"${appdatadir}"'
LDFLAGS:= @LDFLAGS@ @BOOST_LDFLAGS@ $(LDFLAGS)
LIBS:=@LIBS@ @FTGL_LIBS@ @BOOST_FILESYSTEM_LIB@ $(LIBS)
SkywaysGlut_LIBS=@GLUT_LIBS@ @BOOST_PROGRAM_OPTIONS_LIB@
SkywaysQt_CPPFLAGS=-D_REENTRANT -DQT_NO_DEBUG -DQT_OPENGL_LIB -DQT_GUI_LIB -DQT_CORE_LIB @QT_CFLAGS@
SkywaysQt_LIBS=@QT_LIBS@
SkywaysQt_OBJECTS=src/backends/moc_qtwindow_SkywaysQt.o
SkywaysSdl_CPPFLAGS=@SDL_CFLAGS@
SkywaysSdl_LIBS=@SDL_LIBS@ @BOOST_PROGRAM_OPTIONS_LIB@
EXTRADIST=configure.ac Makefile.in configure config.h.in aclocal.m4 \
shaders/shader.glslf shaders/shader.glslv DejaVuSans.ttf\
blocks/cube blocks/flat blocks/tunnel world \
COPYING README
-vpath %.c @srcdir@
-vpath %.cpp @srcdir@
-vpath %.hpp @srcdir@
-
######################################
# auto-configuration: do not change! #
######################################
CWD:=$(shell pwd)
default: all
$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_SOURCES=$($(prog)_SOURCES) $($(prog)_CSOURCES) $($(prog)_CXXSOURCES)))
$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_OBJECTS=$($(prog)_OBJECTS) $(patsubst %.c,%_$(prog).o,$($(prog)_CSOURCES)) $(patsubst %.cpp,%_$(prog).o,$($(prog)_CXXSOURCES))))
$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_HEADERS=$($(prog)_HEADERS)))
$(foreach flag,CFLAGS CPPFLAGS CXXFLAGS LDFLAGS LIBS,$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_$(flag)=$($(flag)) $($(prog)_$(flag)))))
SOURCES=$(foreach prog,$(PROGRAMS),$($(prog)_ALL_SOURCES))
HEADERS=$(foreach prog,$(PROGRAMS),$($(prog)_ALL_HEADERS))
OBJECTS=$(foreach prog,$(PROGRAMS),$($(prog)_ALL_OBJECTS))
BINARIES=$(foreach prog,$(PROGRAMS),$($(prog)_BINARY))
DEPENDS=$(patsubst %.o,%.d,$(OBJECTS))
define CDEP_template
%_$(1).d: %.c $$($(1)_ALL_HEADERS)
@mkdir -p "`dirname $$@`"
@set -e; rm -f "$$@" || true; \
$$(CC) -MM -MQ "`echo "$$@" | sed 's/\.d$$$$/.o'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) "$$<" > $$@
@echo @ECHO_N@ ".@ECHO_C@"
endef
define CXXDEP_template
%_$(1).d: %.cpp $$($(1)_ALL_HEADERS)
@mkdir -p "`dirname $$@`"
@set -e; rm -f "$$@" || true; \
$$(CXX) -MM -MQ "`echo "$$<" | sed 's,\($$*\)\.cpp,\1_$(1).o,'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) "$$<" > $$@
@echo @ECHO_N@ ".@ECHO_C@"
endef
define CSRC_template
%_$(1).o: %.c
$$(CC) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) $$< -o $$@
endef
define CXXSRC_template
%_$(1).o: %.cpp
$$(CXX) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) $$< -o $$@
endef
define BINARY_template
$$($(1)_BINARY): $$($(1)_ALL_OBJECTS)
$$(CC) $$($(1)_ALL_LDFLAGS) $$($(1)_ALL_LIBS) $$^ $$(LOADLIBS) $$(LDLIBS) -o $$@
endef
$(foreach template,CDEP CXXDEP CSRC CXXSRC BINARY,$(foreach prog,$(PROGRAMS),$(eval $(call $(template)_template,$(prog)))))
all: $(BINARIES)
# this rule is just to add a newline after the dots from deps calculation
Makefile: $(DEPENDS)
@echo
@touch $@
%.tar.gz:
rm -f $@
echo $(patsubst @top_srcdir@/%,%,$(filter @top_srcdir@/%,$^)) | tr ' ' '\n' | tar -C @top_srcdir@ -cf $(patsubst %.gz,%,$@) --files-from=-
tar -rf $(patsubst %.gz,%,$@) $(filter-out @top_srcdir@/%,$^)
gzip $(patsubst %.gz,%,$@)
@[email protected]: $(SOURCES) $(HEADERS) $(EXTRADIST)
DISTFILES=@[email protected]
dist: $(DISTFILES)
distcheck: dist
mkdir .dist-check
tar -C .dist-check -xzf @[email protected]
(cd .dist-check && ./configure && $(MAKE) && $(MAKE) dist)
cp .dist-check/@[email protected] .
rm -rf .dist-check
#################################
# extra stuff: change as needed #
#################################
AC_OUTPUT=configure config.h.in aclocal.m4
AC_OUTPUT_DIRS=autom4te.cache
CONFIG_OUTPUT=config.h Makefile config.log config.status
clean:
rm -f $(OBJECTS) $(BINARIES) $(DEPENDS) $(DISTFILES) src/backends/moc_qtwindow.cpp || true
clean-config:
rm -f $(CONFIG_OUTPUT) || true
clean-ac:
rm -f $(AC_OUTPUT) || true
rm -rf $(AC_OUTPUT_DIRS) || true
clean-full: clean clean-config clean-ac
moc_%.cpp: %.hpp
moc-qt4 $(SkywaysQt_CPPFLAGS) $(SkywaysQt_CXXFLAGS) $< -o $@
.PHONY: default dist clean clean-config clean-ac clean-full
-include $(DEPENDS)
diff --git a/src/configuration.cpp b/src/configuration.cpp
index 5522fde..21e3af8 100644
--- a/src/configuration.cpp
+++ b/src/configuration.cpp
@@ -1,48 +1,48 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <display/textprinter.hpp>
#include <loading/objmodel.hpp>
#include <iostream>
#include <stdexcept>
#include "controller.hpp"
#include "configuration.hpp"
std::auto_ptr< Controller > Configuration::buildController( Controller::QuitCallback cbquit )
{
- std::auto_ptr< TextPrinter > printer( new TextPrinter( "DejaVuSans.ttf" ) );
+ std::auto_ptr< TextPrinter > printer( new TextPrinter( DATADIR "/DejaVuSans.ttf" ) );
std::auto_ptr< Model > shipModel;
if ( ship.length() > 0 )
{
shipModel.reset( new Model() );
loadObjModel( ship.c_str(), *shipModel, true, 0, "mtl\0" );
}
std::auto_ptr< Ship > ship( new Ship( shipModel ) );
std::auto_ptr< Game > game( new Game(
10, 5, 100, 20, 1.5, ship
) );
std::auto_ptr< Controller > controller( new Controller (
game, 3.5, 6, 10, cbquit, printer
) );
if ( map.length() )
controller->loadMap( map );
else
controller->generateMap();
return controller;
}
diff --git a/src/controller.cpp b/src/controller.cpp
index d47890e..c93f5b4 100644
--- a/src/controller.cpp
+++ b/src/controller.cpp
@@ -1,212 +1,212 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <GL/glew.h>
#include <GL/gl.h>
#include <boost/format.hpp>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <display/textprinter.hpp>
#include <display/shader.hpp>
#include <loading/maploader.hpp>
#include <loading/mapgenerator.hpp>
#include <loading/blockloader.hpp>
#include "controller.hpp"
Controller::Controller(
std::auto_ptr< Game > game
, double cameraheight, double cameradistance, double camerarotation
, Controller::QuitCallback cbQuit
, std::auto_ptr< TextPrinter > printer
)
: _game( game )
, _camy( cameraheight ), _camz( cameradistance ), _camrot( camerarotation )
, _quitcb( cbQuit ), _printer( printer )
, _windowwidth( 1 ), _windowheight( 1 )
{
srand(time(0));
}
Controller::~Controller()
{
}
void Controller::keydown( int key )
{
switch ( key )
{
case STRAFE_L_KEY: _game->setStrafe( -1 ); break;
case STRAFE_R_KEY: _game->setStrafe( 1 ); break;
case ACCEL_KEY: _game->setAcceleration( 1 ); break;
case DECEL_KEY: _game->setAcceleration( -1 ); break;
case JUMP_KEY: _game->startJump(); break;
case QUIT_KEY:
if ( _game->dead() )
{
_quitcb();
}
else
{
_game->suicide();
}
break;
}
}
void Controller::keyup( int key )
{
switch ( key )
{
case STRAFE_L_KEY:
_game->setStrafe( 0 );
break;
case STRAFE_R_KEY:
_game->setStrafe( 0 );
break;
case ACCEL_KEY:
_game->setAcceleration( 0 );
break;
case DECEL_KEY:
_game->setAcceleration( 0 );
break;
}
}
void Controller::loadBlocks()
{
BlockLoader bl;
boost::ptr_map< std::string, Block > blocks;
bl.loadDirectory( "blocks", blocks );
_game->addBlocks( blocks );
}
void Controller::loadMap( std::string filename )
{
loadBlocks();
MapLoader ml( &_game->getBlocks() );
std::ifstream mapFile( filename.c_str() );
MapInfo mapinfo;
ml.loadMap( mapFile, mapinfo );
_game->setMap( mapinfo.map );
_game->setPos( mapinfo.startPos );
}
void Controller::generateMap()
{
loadBlocks();
MapGenerator mg( &_game->getBlocks() );
MapInfo mapinfo;
mg.generate( mapinfo );
_game->setMap( mapinfo.map );
_game->setPos( mapinfo.startPos );
}
void Controller::initialize()
{
GLenum err = glewInit();
if (err != GLEW_OK)
throw std::runtime_error((const char*)glewGetErrorString(err));
if (!GLEW_VERSION_2_0)
throw std::runtime_error("Nead OpenGL >= 2.0 for shaders. Update your graphics drivers!");
- _shaderProgram = createShaderProgram("shaders/shader.glslv", "shaders/shader.glslf");
+ _shaderProgram = createShaderProgram(DATADIR "/shaders/shader.glslv", DATADIR "/shaders/shader.glslf");
_game->setShader( *_shaderProgram );
glClearColor( 0.2, 0.2, 0.2, 0 );
glClearDepth( 1.0 );
glDepthFunc( GL_LEQUAL );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
glEnable( GL_LINE_SMOOTH );
glHint( GL_LINE_SMOOTH_HINT, GL_NICEST );
}
void Controller::resize( int width, int height )
{
glViewport( 0, 0, width, height );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
double fH = tan( 30.0 / 180.0 * 3.14159265358979323846 );
double fW = ( (double)width ) / ( (double)height ) * fH;
glFrustum( -fW, fW, -fH, fH, 1.0, 1000.0 );
glMatrixMode( GL_MODELVIEW );
_windowwidth = width;
_windowheight = height;
}
void Controller::draw()
{
glClear( GL_DEPTH_BUFFER_BIT );
// draw gradient background
glMatrixMode( GL_PROJECTION );
glPushMatrix();
glLoadIdentity();
glOrtho( 0, 1, 1, 0, -1, 1 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glDisable( GL_DEPTH_TEST );
glDisable( GL_BLEND );
glBegin( GL_QUADS );
glColor3f(0.1, 0.1, 0.1);
glVertex2f(0, 0);
glColor3f(0.15, 0.05, 0);
glVertex2f(0, 1);
glColor3f(0.15, 0.05, 0);
glVertex2f(1, 1);
glColor3f(0.1, 0.1, 0.1);
glVertex2f(1, 0);
glEnd();
glMatrixMode( GL_PROJECTION );
glPopMatrix();
glMatrixMode( GL_MODELVIEW );
glEnable( GL_DEPTH_TEST );
glEnable( GL_CULL_FACE );
glEnable( GL_BLEND );
glLoadIdentity();
glRotatef( _camrot, 1, 0, 0 );
glTranslated( 0.0, -_camy, -_camz );
_game->draw( _camz );
if ( _game->dead() )
{
glUseProgram(0);
_printer->print(
( boost::format( "%1% Distance Traveled: %2%" )
% _game->deathCause()
% _game->distanceTraveled() ).str(),
_windowwidth / 2, _windowheight / 4 * 3,
TextPrinter::ALIGN_CENTER
);
}
}
void Controller::update( int difference )
{
if ( _game->dead() )
return;
_game->update( difference );
}
diff --git a/testbuild.sh b/testbuild.sh
new file mode 100755
index 0000000..858f241
--- /dev/null
+++ b/testbuild.sh
@@ -0,0 +1,5 @@
+#!/bin/sh
+mkdir -p build && \
+ cd build && \
+ ../configure --prefix=`pwd` && \
+ make appdatadir=`pwd`/..
|
devnev/skyways
|
25263a9aca586a0a33a71fb8d2d43d4e3d7815e4
|
Fixed vpath woes.
|
diff --git a/Makefile.in b/Makefile.in
index 1dc25d0..74cb70a 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -1,205 +1,207 @@
#!/usr/bin/make
# @configure_input@
######################################
# configuration: change things here. #
######################################
PROGRAMS?=@programs@
SkywaysGlut_BINARY=skyways.glut
SkywaysQt_BINARY=skyways.qt
SkywaysSdl_BINARY=skyways.sdl
Common_HEADERS= \
src/configuration.hpp \
src/controller.hpp \
src/display/shader.hpp \
src/display/textprinter.hpp \
src/display/uniform.hpp \
src/game.hpp \
src/loading/blockloader.hpp \
src/loading/mapgenerator.hpp \
src/loading/maploader.hpp \
src/loading/objmodel.hpp \
src/range.hpp \
src/vector.hpp \
src/world/aabb.hpp \
src/world/block.hpp \
src/world/collisionaccelerator.hpp \
src/world/element.hpp \
src/world/map.hpp \
src/world/model.hpp \
src/world/ship.hpp \
#
SkywaysGlut_HEADERS= $(Common_HEADERS) \
src/backends/configparser.hpp \
#
SkywaysQt_HEADERS= $(Common_HEADERS) \
src/backends/qtconfigparser.hpp \
src/backends/qtwindow.hpp \
#
SkywaysSdl_HEADERS= $(Common_HEADERS) \
src/backends/configparser.hpp \
#
Common_CXXSOURCES= \
src/configuration.cpp \
src/controller.cpp \
src/display/shader.cpp \
src/display/textprinter.cpp \
src/game.cpp \
src/loading/blockloader.cpp \
src/loading/mapgenerator.cpp \
src/loading/maploader.cpp \
src/loading/objmodel.cpp \
src/world/block.cpp \
src/world/collisionaccelerator.cpp \
src/world/element.cpp \
src/world/map.cpp \
src/world/ship.cpp \
#
SkywaysGlut_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/configparser.cpp \
src/backends/glutmain.cpp \
#
SkywaysQt_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/qtconfigparser.cpp \
src/backends/qtmain.cpp \
src/backends/qtwindow.cpp \
#
SkywaysSdl_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/configparser.cpp \
src/backends/sdlmain.cpp \
#
CFLAGS:= @CFLAGS@ -Wall $(CFLAGS)
CXXFLAGS:= @CXXFLAGS@ -Wall $(CXXFLAGS)
CPPFLAGS:= @CPPFLAGS@ -Wall @FTGL_CFLAGS@ @BOOST_CPPFLAGS@ $(CPPFLAGS) -I@top_srcdir@/src
LDFLAGS:= @LDFLAGS@ @BOOST_LDFLAGS@ $(LDFLAGS)
LIBS:=@LIBS@ @FTGL_LIBS@ @BOOST_FILESYSTEM_LIB@ $(LIBS)
SkywaysGlut_LIBS=@GLUT_LIBS@ @BOOST_PROGRAM_OPTIONS_LIB@
SkywaysQt_CPPFLAGS=-D_REENTRANT -DQT_NO_DEBUG -DQT_OPENGL_LIB -DQT_GUI_LIB -DQT_CORE_LIB @QT_CFLAGS@
SkywaysQt_LIBS=@QT_LIBS@
SkywaysQt_OBJECTS=src/backends/moc_qtwindow_SkywaysQt.o
SkywaysSdl_CPPFLAGS=@SDL_CFLAGS@
SkywaysSdl_LIBS=@SDL_LIBS@ @BOOST_PROGRAM_OPTIONS_LIB@
EXTRADIST=configure.ac Makefile.in configure config.h.in aclocal.m4 \
shaders/shader.glslf shaders/shader.glslv DejaVuSans.ttf\
blocks/cube blocks/flat blocks/tunnel world \
COPYING README
-VPATH=@top_srcdir@
+vpath %.c @srcdir@
+vpath %.cpp @srcdir@
+vpath %.hpp @srcdir@
######################################
# auto-configuration: do not change! #
######################################
CWD:=$(shell pwd)
default: all
$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_SOURCES=$($(prog)_SOURCES) $($(prog)_CSOURCES) $($(prog)_CXXSOURCES)))
$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_OBJECTS=$($(prog)_OBJECTS) $(patsubst %.c,%_$(prog).o,$($(prog)_CSOURCES)) $(patsubst %.cpp,%_$(prog).o,$($(prog)_CXXSOURCES))))
$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_HEADERS=$($(prog)_HEADERS)))
$(foreach flag,CFLAGS CPPFLAGS CXXFLAGS LDFLAGS LIBS,$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_$(flag)=$($(flag)) $($(prog)_$(flag)))))
SOURCES=$(foreach prog,$(PROGRAMS),$($(prog)_ALL_SOURCES))
HEADERS=$(foreach prog,$(PROGRAMS),$($(prog)_ALL_HEADERS))
OBJECTS=$(foreach prog,$(PROGRAMS),$($(prog)_ALL_OBJECTS))
BINARIES=$(foreach prog,$(PROGRAMS),$($(prog)_BINARY))
DEPENDS=$(patsubst %.o,%.d,$(OBJECTS))
define CDEP_template
%_$(1).d: %.c $$($(1)_ALL_HEADERS)
@mkdir -p "`dirname $$@`"
@set -e; rm -f "$$@" || true; \
$$(CC) -MM -MQ "`echo "$$@" | sed 's/\.d$$$$/.o'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) "$$<" > $$@
@echo @ECHO_N@ ".@ECHO_C@"
endef
define CXXDEP_template
%_$(1).d: %.cpp $$($(1)_ALL_HEADERS)
@mkdir -p "`dirname $$@`"
@set -e; rm -f "$$@" || true; \
$$(CXX) -MM -MQ "`echo "$$<" | sed 's,\($$*\)\.cpp,\1_$(1).o,'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) "$$<" > $$@
@echo @ECHO_N@ ".@ECHO_C@"
endef
define CSRC_template
%_$(1).o: %.c
$$(CC) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) $$< -o $$@
endef
define CXXSRC_template
%_$(1).o: %.cpp
$$(CXX) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) $$< -o $$@
endef
define BINARY_template
$$($(1)_BINARY): $$($(1)_ALL_OBJECTS)
$$(CC) $$($(1)_ALL_LDFLAGS) $$($(1)_ALL_LIBS) $$^ $$(LOADLIBS) $$(LDLIBS) -o $$@
endef
$(foreach template,CDEP CXXDEP CSRC CXXSRC BINARY,$(foreach prog,$(PROGRAMS),$(eval $(call $(template)_template,$(prog)))))
all: $(BINARIES)
# this rule is just to add a newline after the dots from deps calculation
Makefile: $(DEPENDS)
@echo
@touch $@
%.tar.gz:
rm -f $@
echo $(patsubst @top_srcdir@/%,%,$(filter @top_srcdir@/%,$^)) | tr ' ' '\n' | tar -C @top_srcdir@ -cf $(patsubst %.gz,%,$@) --files-from=-
tar -rf $(patsubst %.gz,%,$@) $(filter-out @top_srcdir@/%,$^)
gzip $(patsubst %.gz,%,$@)
@[email protected]: $(SOURCES) $(HEADERS) $(EXTRADIST)
DISTFILES=@[email protected]
dist: $(DISTFILES)
distcheck: dist
mkdir .dist-check
tar -C .dist-check -xzf @[email protected]
(cd .dist-check && ./configure && $(MAKE) && $(MAKE) dist)
cp .dist-check/@[email protected] .
rm -rf .dist-check
#################################
# extra stuff: change as needed #
#################################
AC_OUTPUT=configure config.h.in aclocal.m4
AC_OUTPUT_DIRS=autom4te.cache
CONFIG_OUTPUT=config.h Makefile config.log config.status
clean:
rm -f $(OBJECTS) $(BINARIES) $(DEPENDS) $(DISTFILES) src/backends/moc_qtwindow.cpp || true
clean-config:
rm -f $(CONFIG_OUTPUT) || true
clean-ac:
rm -f $(AC_OUTPUT) || true
rm -rf $(AC_OUTPUT_DIRS) || true
clean-full: clean clean-config clean-ac
moc_%.cpp: %.hpp
moc-qt4 $(SkywaysQt_CPPFLAGS) $(SkywaysQt_CXXFLAGS) $< -o $@
.PHONY: default dist clean clean-config clean-ac clean-full
-include $(DEPENDS)
|
devnev/skyways
|
29556fe0609b777cbec262b7c4b6e836182b75b3
|
Made ship model configurable from command-line.
|
diff --git a/src/backends/configparser.cpp b/src/backends/configparser.cpp
index a0ee0ce..b5eee32 100644
--- a/src/backends/configparser.cpp
+++ b/src/backends/configparser.cpp
@@ -1,47 +1,51 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <iostream>
#include "configparser.hpp"
ConfigParser::ConfigParser( Configuration& config )
: _config( config )
{
namespace po = boost::program_options;
options.add_options()
("help,h", "print help message")
("map,w",
po::value<std::string>()->default_value(std::string()),
"set map to load")
+ ("ship,s",
+ po::value<std::string>()->default_value(std::string()),
+ "set ship model to use")
;
}
bool ConfigParser::args(int argc, char * argv[])
{
namespace po = boost::program_options;
po::store(po::command_line_parser(argc, argv).options(options).run(), vm);
po::notify(vm);
if (vm.count("help"))
{
std::cout << options << '\n';
return false;
}
- _config.setMap(vm["map"].as<std::string>());
+ _config.map = vm["map"].as<std::string>();
+ _config.ship = vm["ship"].as<std::string>();
return true;
}
diff --git a/src/backends/qtconfigparser.cpp b/src/backends/qtconfigparser.cpp
index 9ff164c..c21fcf2 100644
--- a/src/backends/qtconfigparser.cpp
+++ b/src/backends/qtconfigparser.cpp
@@ -1,39 +1,39 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <QSettings>
#include "qtconfigparser.hpp"
ConfigParser::ConfigParser( Configuration& config )
: _config( config )
{
}
void ConfigParser::readSettings()
{
QSettings settings(
QSettings::IniFormat, QSettings::UserScope,
"Unspecified", "Skyways"
);
- _config.setMap(
- settings.value("mapfile", QString(""))
- .toString().toStdString()
- );
+ _config.map = settings.value("mapfile", QString(""))
+ .toString().toStdString();
+ _config.ship = settings.value("shipfile", QString(""))
+ .toString().toStdString();
}
diff --git a/src/configuration.cpp b/src/configuration.cpp
index 3000a16..5522fde 100644
--- a/src/configuration.cpp
+++ b/src/configuration.cpp
@@ -1,64 +1,48 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <display/textprinter.hpp>
#include <loading/objmodel.hpp>
#include <iostream>
#include <stdexcept>
#include "controller.hpp"
#include "configuration.hpp"
-Configuration::Configuration()
-{
-}
-
std::auto_ptr< Controller > Configuration::buildController( Controller::QuitCallback cbquit )
{
std::auto_ptr< TextPrinter > printer( new TextPrinter( "DejaVuSans.ttf" ) );
- std::auto_ptr< Model > shipModel( new Model() );
- try
- {
- loadObjModel("ship.obj", *shipModel, true, 0, "mtl\0");
- std::cout << "loaded "
- << shipModel->vertices.size() << " vertices and "
- << shipModel->trifaces.size() + shipModel->quadfaces.size()
- << " faces for ship." << std::endl;
- }
- catch (std::runtime_error& e)
+ std::auto_ptr< Model > shipModel;
+ if ( ship.length() > 0 )
{
- shipModel.reset();
- std::cerr <<
- "Warning: failed to load ship model, "
- "falling back to box ship.\n"
- "Exception caught was: "
- << e.what() << '\n';
+ shipModel.reset( new Model() );
+ loadObjModel( ship.c_str(), *shipModel, true, 0, "mtl\0" );
}
std::auto_ptr< Ship > ship( new Ship( shipModel ) );
std::auto_ptr< Game > game( new Game(
10, 5, 100, 20, 1.5, ship
) );
std::auto_ptr< Controller > controller( new Controller (
game, 3.5, 6, 10, cbquit, printer
) );
- if ( _map.length() )
- controller->loadMap( _map );
+ if ( map.length() )
+ controller->loadMap( map );
else
controller->generateMap();
return controller;
}
diff --git a/src/configuration.hpp b/src/configuration.hpp
index 90236dc..755ed86 100644
--- a/src/configuration.hpp
+++ b/src/configuration.hpp
@@ -1,43 +1,36 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _CONFIGURATION_HPP_
#define _CONFIGURATION_HPP_
#include <memory>
#include "controller.hpp"
-class Configuration
+struct Configuration
{
-public:
-
- Configuration();
-
- void setMap( const std::string& map ) { _map = map; }
-
std::auto_ptr< Controller > buildController( Controller::QuitCallback cbquit );
-private:
-
- std::string _map;
+ std::string map;
+ std::string ship;
};
#endif // _CONFIGURATION_HPP_
|
devnev/skyways
|
422c2f73296a3a9fc05507ae0fd08d99db2e888d
|
Moved loading ship model into configuration.
|
diff --git a/src/configuration.cpp b/src/configuration.cpp
index 878f826..3000a16 100644
--- a/src/configuration.cpp
+++ b/src/configuration.cpp
@@ -1,44 +1,64 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <display/textprinter.hpp>
+#include <loading/objmodel.hpp>
+#include <iostream>
+#include <stdexcept>
#include "controller.hpp"
#include "configuration.hpp"
Configuration::Configuration()
{
}
std::auto_ptr< Controller > Configuration::buildController( Controller::QuitCallback cbquit )
{
std::auto_ptr< TextPrinter > printer( new TextPrinter( "DejaVuSans.ttf" ) );
- std::auto_ptr< Ship > ship( new Ship() );
- ship->initialize();
+ std::auto_ptr< Model > shipModel( new Model() );
+ try
+ {
+ loadObjModel("ship.obj", *shipModel, true, 0, "mtl\0");
+ std::cout << "loaded "
+ << shipModel->vertices.size() << " vertices and "
+ << shipModel->trifaces.size() + shipModel->quadfaces.size()
+ << " faces for ship." << std::endl;
+ }
+ catch (std::runtime_error& e)
+ {
+ shipModel.reset();
+ std::cerr <<
+ "Warning: failed to load ship model, "
+ "falling back to box ship.\n"
+ "Exception caught was: "
+ << e.what() << '\n';
+ }
+ std::auto_ptr< Ship > ship( new Ship( shipModel ) );
std::auto_ptr< Game > game( new Game(
10, 5, 100, 20, 1.5, ship
) );
std::auto_ptr< Controller > controller( new Controller (
game, 3.5, 6, 10, cbquit, printer
) );
if ( _map.length() )
controller->loadMap( _map );
else
controller->generateMap();
return controller;
}
diff --git a/src/world/model.hpp b/src/world/model.hpp
index 486fb54..d1e4720 100644
--- a/src/world/model.hpp
+++ b/src/world/model.hpp
@@ -1,105 +1,107 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _MODEL_HPP_
#define _MODEL_HPP_
#include <vector>
#include <GL/gl.h>
#include <vector.hpp>
typedef struct
{
size_t ix[3];
} Triangle;
typedef struct
{
size_t ix[4];
} Quad;
template<size_t N>
struct Face
{
size_t vertices[N];
size_t normals[N];
bool valid()
{
for (size_t i = 0; i < N; ++i)
{
if ( vertices[i] == vertices[(i+1)%N] )
return false;
}
return true;
}
};
-typedef struct
+class Model
{
+public:
+
std::vector< Vector3 > vertices;
std::vector< Vector3 > normals;
std::vector< Face<3> > trifaces;
std::vector< Face<4> > quadfaces;
void draw() const
{
glBegin( GL_TRIANGLES );
for ( size_t i = 0; i < trifaces.size(); ++i )
drawFace( trifaces[i] );
glEnd();
glBegin( GL_QUADS );
for ( size_t i = 0; i < quadfaces.size(); ++i )
drawFace( quadfaces[i] );
glEnd();
}
private:
template<size_t N>
void drawFace( const Face<N>& face ) const
{
for ( size_t i = 0; i < N; ++i )
{
if ( normals.size() > 0 )
{
glNormal3d(
normals[face.normals[i]].x,
normals[face.normals[i]].y,
normals[face.normals[i]].z
);
}
glVertex3d(
vertices[face.vertices[i]].x,
vertices[face.vertices[i]].y,
vertices[face.vertices[i]].z
);
}
}
-} Model;
+};
#endif // _MODEL_HPP_
diff --git a/src/world/ship.cpp b/src/world/ship.cpp
index 6e7b7b7..10e31b0 100644
--- a/src/world/ship.cpp
+++ b/src/world/ship.cpp
@@ -1,122 +1,101 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <GL/gl.h>
#include <cmath>
-#include <iostream>
-#include <stdexcept>
-#include <loading/objmodel.hpp>
+#include "model.hpp"
#include "ship.hpp"
-Ship::Ship()
+Ship::Ship( std::auto_ptr< Model > model )
: _pos(Vector3(0, 0, 0))
, _size(Vector3(0.8, 0.5, 1.0))
+ , _model(model)
, _shipDl(0)
{
}
Ship::~Ship()
{
}
-void Ship::initialize()
-{
- try
- {
- loadObjModel("ship.obj", _model, true, 0, "mtl\0");
- std::cout << "loaded "
- << _model.vertices.size() << " vertices and "
- << _model.trifaces.size() + _model.quadfaces.size()
- << " faces for ship." << std::endl;
- }
- catch (std::runtime_error& e)
- {
- std::cerr <<
- "Warning: failed to load ship model, "
- "falling back to box ship.\n"
- "Exception caught was: "
- << e.what() << '\n';
- }
-}
-
void Ship::draw()
{
glTranslated( 0, _size.y / 2, -_size.z / 2 );
- if ( _model.vertices.size() && _model.trifaces.size() )
+ if ( _model.get() )
{
glScaled( _size.x, _size.y, -_size.z );
- _model.draw();
+ _model->draw();
}
else
{
glScaled( _size.x, _size.y, _size.z );
glEnable( GL_POLYGON_OFFSET_FILL );
glPolygonOffset( 0.01f, 0.01f );
drawSimple();
glDisable( GL_POLYGON_OFFSET_FILL );
}
}
void Ship::drawDl()
{
if ( _shipDl == 0 )
{
_shipDl = glGenLists( 1 );
glNewList( _shipDl, GL_COMPILE_AND_EXECUTE );
draw();
glEndList();
}
else
{
glCallList( _shipDl );
}
}
void Ship::drawSimple()
{
glBegin( GL_QUADS );
glNormal3d( 0, 0, 1 );
glVertex3d( -0.5, 0.5, 0.5 );
glVertex3d( -0.5, -0.5, 0.5 );
glVertex3d( 0.5, -0.5, 0.5 );
glVertex3d( 0.5, 0.5, 0.5 );
glEnd();
glBegin( GL_TRIANGLES );
glNormal3d( -1, 0, -0.5 );
glVertex3d( -0.5, -0.5, 0.5 );
glVertex3d( -0.5, 0.5, 0.5 );
glVertex3d( 0, 0, -1.0 );
glNormal3d( 0, 1, -0.5 );
glVertex3d( -0.5, 0.5, 0.5 );
glVertex3d( 0.5, 0.5, 0.5 );
glVertex3d( 0, 0, -1.0 );
glNormal3d( 1, 0, -0.5 );
glVertex3d( 0.5, 0.5, 0.5 );
glVertex3d( 0.5, -0.5, 0.5 );
glVertex3d( 0, 0, -1.0 );
glNormal3d( 0, -1, -0.5 );
glVertex3d( 0.5, -0.5, 0.5 );
glVertex3d( -0.5, -0.5, 0.5 );
glVertex3d( 0, 0, -1.0 );
glEnd();
}
diff --git a/src/world/ship.hpp b/src/world/ship.hpp
index 907bf37..f29b34a 100644
--- a/src/world/ship.hpp
+++ b/src/world/ship.hpp
@@ -1,60 +1,60 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _SHIP_HPP_
#define _SHIP_HPP_
#include <vector>
+#include <memory>
#include <GL/gl.h>
#include <vector.hpp>
-#include "model.hpp"
+
+class Model;
class Ship
{
public:
- Ship();
+ Ship( std::auto_ptr< Model > model );
~Ship();
- void initialize();
-
double xpos() const throw() { return _pos.x; }
double ypos() const throw() { return _pos.y; }
double zpos() const throw() { return _pos.z; }
const Vector3& pos() const throw() { return _pos; }
Vector3& pos() throw() { return _pos; }
const Vector3& size() const throw() { return _size; }
void draw();
void drawDl();
private:
void drawSimple();
Vector3 _pos;
Vector3 _size;
- Model _model;
+ std::auto_ptr< Model > _model;
GLuint _shipDl;
};
#endif // _SHIP_HPP_
|
devnev/skyways
|
dbb4ab2e5d2c486438dd17e30d3237cfd5ae7aa3
|
Moved creation of ship object out of game class.
|
diff --git a/src/configuration.cpp b/src/configuration.cpp
index de22c3d..878f826 100644
--- a/src/configuration.cpp
+++ b/src/configuration.cpp
@@ -1,42 +1,44 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <display/textprinter.hpp>
#include "controller.hpp"
#include "configuration.hpp"
Configuration::Configuration()
{
}
std::auto_ptr< Controller > Configuration::buildController( Controller::QuitCallback cbquit )
{
std::auto_ptr< TextPrinter > printer( new TextPrinter( "DejaVuSans.ttf" ) );
+ std::auto_ptr< Ship > ship( new Ship() );
+ ship->initialize();
std::auto_ptr< Game > game( new Game(
- 10, 5, 100, 20, 1.5
+ 10, 5, 100, 20, 1.5, ship
) );
std::auto_ptr< Controller > controller( new Controller (
game, 3.5, 6, 10, cbquit, printer
) );
if ( _map.length() )
controller->loadMap( _map );
else
controller->generateMap();
return controller;
}
diff --git a/src/game.cpp b/src/game.cpp
index 794f2e1..ee8c725 100644
--- a/src/game.cpp
+++ b/src/game.cpp
@@ -1,152 +1,152 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <display/shader.hpp>
#include "game.hpp"
Game::Game(
double acceleration, double strafespeed, double speedlimit
, double gravity, double jumpstrength
+ , std::auto_ptr< Ship > ship
, ShaderProgram * shader
)
- : _ship(), _map( 0 ), _shader( shader )
+ : _ship( ship ), _map( 0 ), _shader( shader )
, _currAcc( 0 ), _maxAcc( acceleration )
, _currStrafe( 0 ), _maxStrafe( strafespeed )
, _maxSpeed( speedlimit ), _zspeed( 0 )
, _yapex( 0 ), _tapex( 0 ), _gravity( gravity )
, _jstrength( jumpstrength ), _grounded( true )
{
- _ship.initialize();
- _ship.pos().x = 0.5;
+ _ship->pos().x = 0.5;
std::string empty;
_blocks.insert( empty, new Block() );
}
void Game::startJump()
{
if ( _grounded ||
_map->collide( AABB(
- _ship.pos().offset(0, -0.2, 0),
- _ship.pos().offset(0, -0.2, 0).offset(_ship.size())
+ _ship->pos().offset(0, -0.2, 0),
+ _ship->pos().offset(0, -0.2, 0).offset(_ship->size())
) ) )
{
- _yapex = _ship.ypos() + _jstrength;
+ _yapex = _ship->ypos() + _jstrength;
_tapex = sqrt( _jstrength / _gravity );
}
}
void Game::draw( double zminClip )
{
_shader->use();
glPushMatrix();
- glTranslated( _ship.xpos() - 0.5, _ship.ypos(), 0.0 );
+ glTranslated( _ship->xpos() - 0.5, _ship->ypos(), 0.0 );
glColor4f( 1, 0, 0, 0.25 );
- _ship.drawDl();
+ _ship->drawDl();
glPopMatrix();
glColor3f( 0.8f, 1, 1 );
- glTranslatef( -0.5, 0.0, _ship.zpos() );
- _map->glDraw( _ship.zpos() - zminClip );
+ glTranslatef( -0.5, 0.0, _ship->zpos() );
+ _map->glDraw( _ship->zpos() - zminClip );
}
void Game::update( int difference )
{
double multiplier = ( (double)difference ) / 1000;
- Vector3 newPos = _ship.pos();
+ Vector3 newPos = _ship->pos();
AABB shipAabb(
- Vector3( -_ship.size().x/2, 0, 0 ),
- Vector3( _ship.size().x/2, _ship.size().y, _ship.size().z )
+ Vector3( -_ship->size().x/2, 0, 0 ),
+ Vector3( _ship->size().x/2, _ship->size().y, _ship->size().z )
);
if ( _currAcc < -_maxAcc ) _currAcc = -_maxAcc;
else if ( _currAcc > _maxAcc ) _currAcc = _maxAcc;
_zspeed += _currAcc*multiplier;
if ( _zspeed < 0 ) _zspeed = 0;
if ( _zspeed > _maxSpeed ) _zspeed = _maxSpeed;
newPos.z += multiplier * _zspeed;
if ( _map->collide( shipAabb.offset( newPos ) ) )
{
- newPos.z = _ship.pos().z;
+ newPos.z = _ship->pos().z;
_zspeed = 0;
}
else
- _ship.pos().z = newPos.z;
+ _ship->pos().z = newPos.z;
if ( _currStrafe < -_maxStrafe ) _currStrafe = -_maxStrafe;
if ( _currStrafe > _maxStrafe ) _currStrafe = _maxStrafe;
if ( _currStrafe != 0 )
{
newPos.x += _currStrafe*multiplier;
if ( _map->collide( shipAabb.offset( newPos ) ) )
- newPos.x = _ship.pos().x;
+ newPos.x = _ship->pos().x;
else
- _ship.pos().x = newPos.x;
+ _ship->pos().x = newPos.x;
}
if ( _tapex <= 0 && _grounded )
{
_tapex = 0;
- _yapex = _ship.pos().y;
+ _yapex = _ship->pos().y;
}
_tapex -= multiplier;
newPos.y = _yapex - _gravity * ( _tapex*_tapex );
const Element * collision;
if ( ( collision = _map->collide( shipAabb.offset( newPos ) ) ) )
{
- newPos.y = _ship.pos().y;
+ newPos.y = _ship->pos().y;
if (_tapex < 0) {
_grounded = true;
collision->trigger( *this );
}
_tapex = 0;
- _yapex = _ship.pos().y;
+ _yapex = _ship->pos().y;
}
else
{
- _ship.pos().y = newPos.y;
+ _ship->pos().y = newPos.y;
_grounded = false;
}
if ( droppedOut() )
{
kill( "You dropped into the void!" );
}
}
void Game::suicide()
{
kill( "You committed suicide!" );
}
void Game::explode()
{
kill( "You exploded!" );
}
void Game::kill( const std::string & cause )
{
_death = cause;
}
diff --git a/src/game.hpp b/src/game.hpp
index 292d244..0680e10 100644
--- a/src/game.hpp
+++ b/src/game.hpp
@@ -1,78 +1,79 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _WORLD_HPP_
#define _WORLD_HPP_
#include <world/ship.hpp>
#include <world/map.hpp>
class ShaderProgram;
class Game
{
public:
Game(
double acceleration, double strafespeed, double speedlimit
, double gravity, double jumpstrength
+ , std::auto_ptr< Ship > ship
, ShaderProgram * shader = 0
);
void addBlocks(boost::ptr_map< std::string, Block >& blocks) { _blocks.transfer( blocks ); }
void setMap(std::auto_ptr<Map> map) throw() { _map = map; _map->optimize(); }
- void setPos(const Vector3& pos) throw() { _ship.pos() = pos; }
+ void setPos(const Vector3& pos) throw() { _ship->pos() = pos; }
void setShader(ShaderProgram& shader) throw() { _shader = &shader; }
const boost::ptr_map< std::string, Block >& getBlocks() { return _blocks; }
void setAcceleration( double accel ) { _currAcc = accel*_maxAcc; }
void setStrafe( double strafe ) { _currStrafe = strafe*_maxStrafe; }
void startJump();
void draw( double zminClip );
void update( int difference );
- double distanceTraveled() const throw() { return _ship.pos().z; }
+ double distanceTraveled() const throw() { return _ship->pos().z; }
bool droppedOut() const throw() {
- return _ship.pos().y < _map->lowestPoint() - 1;
+ return _ship->pos().y < _map->lowestPoint() - 1;
}
void kill( const std::string & cause );
void suicide();
void explode();
bool dead() const throw() { return !_death.empty(); }
const std::string& deathCause() const { return _death; }
private:
boost::ptr_map< std::string, Block > _blocks;
- Ship _ship;
+ std::auto_ptr< Ship > _ship;
std::auto_ptr< Map > _map;
ShaderProgram * _shader;
double _currAcc, _maxAcc;
double _currStrafe, _maxStrafe;
double _maxSpeed, _zspeed;
double _yapex, _tapex, _gravity;
double _jstrength;
bool _grounded;
std::string _death;
};
#endif // _WORLD_HPP_
|
devnev/skyways
|
6e59e9f2340e36e075d376569d54e0da209ab4cc
|
Reduced minimum boost version to 1.34.0.
|
diff --git a/configure.ac b/configure.ac
index 6fa7216..079ce94 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,111 +1,111 @@
# -*- Autoconf -*-
# vim: ft=m4
# Process this file with autoconf to produce a configure script.
AC_PREREQ([2.63])
AC_INIT([skyways], [0.0.1], [[email protected]])
AC_CONFIG_MACRO_DIR([m4])
AC_CONFIG_SRCDIR([src/configuration.hpp])
AC_CONFIG_HEADERS([config.h])
# Checks for programs.
AC_PROG_CXX
PKG_PROG_PKG_CONFIG
# Checks for libraries.
AC_CHECK_LIB([GL], [glGetString])
AC_CHECK_LIB([GLEW], [glewInit])
PKG_CHECK_MODULES([FTGL],[ftgl >= 2.1])
-AX_BOOST_BASE([1.35.0])
+AX_BOOST_BASE([1.34.0])
AX_BOOST_FILESYSTEM
AX_BOOST_PROGRAM_OPTIONS
programs=""
AC_ARG_ENABLE([qt], AS_HELP_STRING([--enable-qt], [Enable Qt backend (default: test)]),
[ if test "x$enableval" = "xyes" ; then qt_backend=yes
elif test "x$enableval" = "xtest" ; then qt_backend=test
elif test "x$enableval" = "xno" ; then qt_backend=no
else echo "Error: unknown --enable-qt option $enableval" ; exit 1
fi
],
[ qt_backend=test
])
if test "x$qt_backend" == "xyes" ; then
PKG_CHECK_MODULES([QT],[QtCore >= 4.5.0 QtGui >= 4.5.0 QtOpenGL >= 4.5.0])
AC_CHECK_LIB([pthread],[pthread_create],[QT_LIBS="-lpthread $QT_LIBS"])
AC_CHECK_LIB([GLU], [gluGetString],[QT_LIBS="-lGLU $QT_LIBS"])
elif test "x$qt_backend" == "xtest" ; then
PKG_CHECK_MODULES([QT],[QtCore >= 4.5.0 QtGui >= 4.5.0 QtOpenGL >= 4.5.0],[qt_backend="yes"],[qt_backend="no"])
if test "x$qt_backend" = "xyes" ; then
AC_CHECK_LIB([pthread],[pthread_create],[QT_LIBS="-lpthread $QT_LIBS"; qt_backend="yes"],[qt_backend="no"])
fi
if test "x$qt_backend" = "xyes" ; then
AC_CHECK_LIB([GLU], [gluGetString],[QT_LIBS="-lGLU $QT_LIBS"; qt_backend="yes"],[qt_backend="no"])
fi
fi
AC_SUBST(qt_backend)
if test "x$qt_backend" = "xyes" ; then
programs="SkywaysQt $programs"
fi
AC_ARG_ENABLE([sdl], AS_HELP_STRING([--enable-sdl], [Enable SDL backend (default: test)]),
[ if test "x$enableval" = "xyes" ; then sdl_backend=yes
elif test "x$enableval" = "xtest" ; then sdl_backend=test
elif test "x$enableval" = "xno" ; then sdl_backend=no
else echo "Error: unknown --enable-sdl option $enableval" ; exit 1
fi
],
[ sdl_backend=test
])
if test "x$sdl_backend" == "xyes" ; then
PKG_CHECK_MODULES([SDL],[sdl >= 1.2.13])
elif test "x$sdl_backend" == "xtest" ; then
PKG_CHECK_MODULES([SDL],[sdl >= 1.2.13],[sdl_backend="yes"],[sdl_backend="no"])
fi
AC_SUBST(sdl_backend)
if test "x$sdl_backend" = "xyes" ; then
programs="SkywaysSdl $programs"
fi
AC_ARG_ENABLE([glut], AS_HELP_STRING([--enable-glut], [Enable GLUT backend (default: test)]),
[ if test "x$enableval" = "xyes" ; then glut_backend=yes
elif test "x$enableval" = "xtest" ; then glut_backend=test
elif test "x$enableval" = "xno" ; then glut_backend=no
else echo "Error: unknown --enable-glut option $enableval" ; exit 1
fi
],
[ glut_backend=test
])
if test "x$glut_backend" == "xyes" ; then
AC_CHECK_LIB([glut],[glutMainLoop],[GLUT_LIBS="-lglut"])
elif test "x$glut_backend" == "xtest" ; then
AC_CHECK_LIB([glut],[glutMainLoop],[GLUT_LIBS="-lglut"; glut_backend="yes"],[glut_backend="no"])
fi
AC_SUBST(glut_backend)
AC_SUBST(GLUT_LIBS)
if test "x$glut_backend" = "xyes" ; then
programs="SkywaysGlut $programs"
fi
if test -z "$programs" ; then
echo "Error: no backends will be built, aborting."
exit 1
fi
AC_SUBST(programs)
# Checks for header files.
# Checks for typedefs, structures, and compiler characteristics.
# Checks for library functions.
AC_CONFIG_FILES([Makefile])
AC_OUTPUT
echo "Configuration complete. Backends to be built:"
echo " Qt backend... $qt_backend"
echo " SDL backend... $sdl_backend"
echo " GLUT backend... $glut_backend"
|
devnev/skyways
|
e1806a0b40b842b5500a10489a7fb23dc39b719c
|
Added simple distcheck target.
|
diff --git a/Makefile.in b/Makefile.in
index 3f6b8f8..1dc25d0 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -1,198 +1,205 @@
#!/usr/bin/make
# @configure_input@
######################################
# configuration: change things here. #
######################################
PROGRAMS?=@programs@
SkywaysGlut_BINARY=skyways.glut
SkywaysQt_BINARY=skyways.qt
SkywaysSdl_BINARY=skyways.sdl
Common_HEADERS= \
src/configuration.hpp \
src/controller.hpp \
src/display/shader.hpp \
src/display/textprinter.hpp \
src/display/uniform.hpp \
src/game.hpp \
src/loading/blockloader.hpp \
src/loading/mapgenerator.hpp \
src/loading/maploader.hpp \
src/loading/objmodel.hpp \
src/range.hpp \
src/vector.hpp \
src/world/aabb.hpp \
src/world/block.hpp \
src/world/collisionaccelerator.hpp \
src/world/element.hpp \
src/world/map.hpp \
src/world/model.hpp \
src/world/ship.hpp \
#
SkywaysGlut_HEADERS= $(Common_HEADERS) \
src/backends/configparser.hpp \
#
SkywaysQt_HEADERS= $(Common_HEADERS) \
src/backends/qtconfigparser.hpp \
src/backends/qtwindow.hpp \
#
SkywaysSdl_HEADERS= $(Common_HEADERS) \
src/backends/configparser.hpp \
#
Common_CXXSOURCES= \
src/configuration.cpp \
src/controller.cpp \
src/display/shader.cpp \
src/display/textprinter.cpp \
src/game.cpp \
src/loading/blockloader.cpp \
src/loading/mapgenerator.cpp \
src/loading/maploader.cpp \
src/loading/objmodel.cpp \
src/world/block.cpp \
src/world/collisionaccelerator.cpp \
src/world/element.cpp \
src/world/map.cpp \
src/world/ship.cpp \
#
SkywaysGlut_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/configparser.cpp \
src/backends/glutmain.cpp \
#
SkywaysQt_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/qtconfigparser.cpp \
src/backends/qtmain.cpp \
src/backends/qtwindow.cpp \
#
SkywaysSdl_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/configparser.cpp \
src/backends/sdlmain.cpp \
#
CFLAGS:= @CFLAGS@ -Wall $(CFLAGS)
CXXFLAGS:= @CXXFLAGS@ -Wall $(CXXFLAGS)
CPPFLAGS:= @CPPFLAGS@ -Wall @FTGL_CFLAGS@ @BOOST_CPPFLAGS@ $(CPPFLAGS) -I@top_srcdir@/src
LDFLAGS:= @LDFLAGS@ @BOOST_LDFLAGS@ $(LDFLAGS)
LIBS:=@LIBS@ @FTGL_LIBS@ @BOOST_FILESYSTEM_LIB@ $(LIBS)
SkywaysGlut_LIBS=@GLUT_LIBS@ @BOOST_PROGRAM_OPTIONS_LIB@
SkywaysQt_CPPFLAGS=-D_REENTRANT -DQT_NO_DEBUG -DQT_OPENGL_LIB -DQT_GUI_LIB -DQT_CORE_LIB @QT_CFLAGS@
SkywaysQt_LIBS=@QT_LIBS@
SkywaysQt_OBJECTS=src/backends/moc_qtwindow_SkywaysQt.o
SkywaysSdl_CPPFLAGS=@SDL_CFLAGS@
SkywaysSdl_LIBS=@SDL_LIBS@ @BOOST_PROGRAM_OPTIONS_LIB@
EXTRADIST=configure.ac Makefile.in configure config.h.in aclocal.m4 \
shaders/shader.glslf shaders/shader.glslv DejaVuSans.ttf\
blocks/cube blocks/flat blocks/tunnel world \
COPYING README
VPATH=@top_srcdir@
######################################
# auto-configuration: do not change! #
######################################
CWD:=$(shell pwd)
default: all
$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_SOURCES=$($(prog)_SOURCES) $($(prog)_CSOURCES) $($(prog)_CXXSOURCES)))
$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_OBJECTS=$($(prog)_OBJECTS) $(patsubst %.c,%_$(prog).o,$($(prog)_CSOURCES)) $(patsubst %.cpp,%_$(prog).o,$($(prog)_CXXSOURCES))))
$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_HEADERS=$($(prog)_HEADERS)))
$(foreach flag,CFLAGS CPPFLAGS CXXFLAGS LDFLAGS LIBS,$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_$(flag)=$($(flag)) $($(prog)_$(flag)))))
SOURCES=$(foreach prog,$(PROGRAMS),$($(prog)_ALL_SOURCES))
HEADERS=$(foreach prog,$(PROGRAMS),$($(prog)_ALL_HEADERS))
OBJECTS=$(foreach prog,$(PROGRAMS),$($(prog)_ALL_OBJECTS))
BINARIES=$(foreach prog,$(PROGRAMS),$($(prog)_BINARY))
DEPENDS=$(patsubst %.o,%.d,$(OBJECTS))
define CDEP_template
%_$(1).d: %.c $$($(1)_ALL_HEADERS)
@mkdir -p "`dirname $$@`"
@set -e; rm -f "$$@" || true; \
$$(CC) -MM -MQ "`echo "$$@" | sed 's/\.d$$$$/.o'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) "$$<" > $$@
@echo @ECHO_N@ ".@ECHO_C@"
endef
define CXXDEP_template
%_$(1).d: %.cpp $$($(1)_ALL_HEADERS)
@mkdir -p "`dirname $$@`"
@set -e; rm -f "$$@" || true; \
$$(CXX) -MM -MQ "`echo "$$<" | sed 's,\($$*\)\.cpp,\1_$(1).o,'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) "$$<" > $$@
@echo @ECHO_N@ ".@ECHO_C@"
endef
define CSRC_template
%_$(1).o: %.c
$$(CC) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) $$< -o $$@
endef
define CXXSRC_template
%_$(1).o: %.cpp
$$(CXX) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) $$< -o $$@
endef
define BINARY_template
$$($(1)_BINARY): $$($(1)_ALL_OBJECTS)
$$(CC) $$($(1)_ALL_LDFLAGS) $$($(1)_ALL_LIBS) $$^ $$(LOADLIBS) $$(LDLIBS) -o $$@
endef
$(foreach template,CDEP CXXDEP CSRC CXXSRC BINARY,$(foreach prog,$(PROGRAMS),$(eval $(call $(template)_template,$(prog)))))
all: $(BINARIES)
# this rule is just to add a newline after the dots from deps calculation
Makefile: $(DEPENDS)
@echo
@touch $@
%.tar.gz:
rm -f $@
echo $(patsubst @top_srcdir@/%,%,$(filter @top_srcdir@/%,$^)) | tr ' ' '\n' | tar -C @top_srcdir@ -cf $(patsubst %.gz,%,$@) --files-from=-
tar -rf $(patsubst %.gz,%,$@) $(filter-out @top_srcdir@/%,$^)
gzip $(patsubst %.gz,%,$@)
@[email protected]: $(SOURCES) $(HEADERS) $(EXTRADIST)
DISTFILES=@[email protected]
dist: $(DISTFILES)
+distcheck: dist
+ mkdir .dist-check
+ tar -C .dist-check -xzf @[email protected]
+ (cd .dist-check && ./configure && $(MAKE) && $(MAKE) dist)
+ cp .dist-check/@[email protected] .
+ rm -rf .dist-check
+
#################################
# extra stuff: change as needed #
#################################
AC_OUTPUT=configure config.h.in aclocal.m4
AC_OUTPUT_DIRS=autom4te.cache
CONFIG_OUTPUT=config.h Makefile config.log config.status
clean:
rm -f $(OBJECTS) $(BINARIES) $(DEPENDS) $(DISTFILES) src/backends/moc_qtwindow.cpp || true
clean-config:
rm -f $(CONFIG_OUTPUT) || true
clean-ac:
rm -f $(AC_OUTPUT) || true
rm -rf $(AC_OUTPUT_DIRS) || true
clean-full: clean clean-config clean-ac
moc_%.cpp: %.hpp
moc-qt4 $(SkywaysQt_CPPFLAGS) $(SkywaysQt_CXXFLAGS) $< -o $@
.PHONY: default dist clean clean-config clean-ac clean-full
-include $(DEPENDS)
|
devnev/skyways
|
13386d63555a60205c882446c447428a86f1b429
|
Fixed incorrect include.
|
diff --git a/src/world/ship.hpp b/src/world/ship.hpp
index 060c586..907bf37 100644
--- a/src/world/ship.hpp
+++ b/src/world/ship.hpp
@@ -1,60 +1,60 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _SHIP_HPP_
#define _SHIP_HPP_
#include <vector>
#include <GL/gl.h>
-#include "vector.hpp"
+#include <vector.hpp>
#include "model.hpp"
class Ship
{
public:
Ship();
~Ship();
void initialize();
double xpos() const throw() { return _pos.x; }
double ypos() const throw() { return _pos.y; }
double zpos() const throw() { return _pos.z; }
const Vector3& pos() const throw() { return _pos; }
Vector3& pos() throw() { return _pos; }
const Vector3& size() const throw() { return _size; }
void draw();
void drawDl();
private:
void drawSimple();
Vector3 _pos;
Vector3 _size;
Model _model;
GLuint _shipDl;
};
#endif // _SHIP_HPP_
|
devnev/skyways
|
6c261972f6ed462cc74bb74bd088e07aaca35718
|
Added support for "parallel" builds.
|
diff --git a/Makefile.in b/Makefile.in
index 95403e8..3f6b8f8 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -1,190 +1,198 @@
#!/usr/bin/make
# @configure_input@
######################################
# configuration: change things here. #
######################################
PROGRAMS?=@programs@
SkywaysGlut_BINARY=skyways.glut
SkywaysQt_BINARY=skyways.qt
SkywaysSdl_BINARY=skyways.sdl
Common_HEADERS= \
src/configuration.hpp \
src/controller.hpp \
src/display/shader.hpp \
src/display/textprinter.hpp \
src/display/uniform.hpp \
src/game.hpp \
src/loading/blockloader.hpp \
src/loading/mapgenerator.hpp \
src/loading/maploader.hpp \
src/loading/objmodel.hpp \
src/range.hpp \
src/vector.hpp \
src/world/aabb.hpp \
src/world/block.hpp \
src/world/collisionaccelerator.hpp \
src/world/element.hpp \
src/world/map.hpp \
src/world/model.hpp \
src/world/ship.hpp \
#
SkywaysGlut_HEADERS= $(Common_HEADERS) \
src/backends/configparser.hpp \
#
SkywaysQt_HEADERS= $(Common_HEADERS) \
src/backends/qtconfigparser.hpp \
src/backends/qtwindow.hpp \
#
SkywaysSdl_HEADERS= $(Common_HEADERS) \
src/backends/configparser.hpp \
#
Common_CXXSOURCES= \
src/configuration.cpp \
src/controller.cpp \
src/display/shader.cpp \
src/display/textprinter.cpp \
src/game.cpp \
src/loading/blockloader.cpp \
src/loading/mapgenerator.cpp \
src/loading/maploader.cpp \
src/loading/objmodel.cpp \
src/world/block.cpp \
src/world/collisionaccelerator.cpp \
src/world/element.cpp \
src/world/map.cpp \
src/world/ship.cpp \
#
SkywaysGlut_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/configparser.cpp \
src/backends/glutmain.cpp \
#
SkywaysQt_CXXSOURCES= $(Common_CXXSOURCES) \
- src/backends/moc_qtwindow.cpp \
src/backends/qtconfigparser.cpp \
src/backends/qtmain.cpp \
src/backends/qtwindow.cpp \
#
SkywaysSdl_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/configparser.cpp \
src/backends/sdlmain.cpp \
#
CFLAGS:= @CFLAGS@ -Wall $(CFLAGS)
CXXFLAGS:= @CXXFLAGS@ -Wall $(CXXFLAGS)
-CPPFLAGS:= @CPPFLAGS@ -Wall @FTGL_CFLAGS@ @BOOST_CPPFLAGS@ $(CPPFLAGS) -Isrc
+CPPFLAGS:= @CPPFLAGS@ -Wall @FTGL_CFLAGS@ @BOOST_CPPFLAGS@ $(CPPFLAGS) -I@top_srcdir@/src
LDFLAGS:= @LDFLAGS@ @BOOST_LDFLAGS@ $(LDFLAGS)
LIBS:=@LIBS@ @FTGL_LIBS@ @BOOST_FILESYSTEM_LIB@ $(LIBS)
SkywaysGlut_LIBS=@GLUT_LIBS@ @BOOST_PROGRAM_OPTIONS_LIB@
SkywaysQt_CPPFLAGS=-D_REENTRANT -DQT_NO_DEBUG -DQT_OPENGL_LIB -DQT_GUI_LIB -DQT_CORE_LIB @QT_CFLAGS@
SkywaysQt_LIBS=@QT_LIBS@
+SkywaysQt_OBJECTS=src/backends/moc_qtwindow_SkywaysQt.o
SkywaysSdl_CPPFLAGS=@SDL_CFLAGS@
SkywaysSdl_LIBS=@SDL_LIBS@ @BOOST_PROGRAM_OPTIONS_LIB@
EXTRADIST=configure.ac Makefile.in configure config.h.in aclocal.m4 \
shaders/shader.glslf shaders/shader.glslv DejaVuSans.ttf\
blocks/cube blocks/flat blocks/tunnel world \
COPYING README
+VPATH=@top_srcdir@
+
######################################
# auto-configuration: do not change! #
######################################
CWD:=$(shell pwd)
default: all
-$(foreach prog,$(PROGRAMS),$(eval $(prog)_SOURCES=$($(prog)_CSOURCES) $($(prog)_CXXSOURCES)))
-$(foreach prog,$(PROGRAMS),$(eval $(prog)_OBJECTS=$(patsubst %.c,%_$(prog).o,$($(prog)_CSOURCES)) $(patsubst %.cpp,%_$(prog).o,$($(prog)_CXXSOURCES))))
+$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_SOURCES=$($(prog)_SOURCES) $($(prog)_CSOURCES) $($(prog)_CXXSOURCES)))
+$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_OBJECTS=$($(prog)_OBJECTS) $(patsubst %.c,%_$(prog).o,$($(prog)_CSOURCES)) $(patsubst %.cpp,%_$(prog).o,$($(prog)_CXXSOURCES))))
+$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_HEADERS=$($(prog)_HEADERS)))
$(foreach flag,CFLAGS CPPFLAGS CXXFLAGS LDFLAGS LIBS,$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_$(flag)=$($(flag)) $($(prog)_$(flag)))))
-SOURCES=$(foreach prog,$(PROGRAMS),$($(prog)_SOURCES))
-HEADERS=$(foreach prog,$(PROGRAMS),$($(prog)_HEADERS))
-OBJECTS=$(foreach prog,$(PROGRAMS),$($(prog)_OBJECTS))
+SOURCES=$(foreach prog,$(PROGRAMS),$($(prog)_ALL_SOURCES))
+HEADERS=$(foreach prog,$(PROGRAMS),$($(prog)_ALL_HEADERS))
+OBJECTS=$(foreach prog,$(PROGRAMS),$($(prog)_ALL_OBJECTS))
BINARIES=$(foreach prog,$(PROGRAMS),$($(prog)_BINARY))
DEPENDS=$(patsubst %.o,%.d,$(OBJECTS))
define CDEP_template
- %_$(1).d: %.c $$($(1)_HEADERS)
+ %_$(1).d: %.c $$($(1)_ALL_HEADERS)
+ @mkdir -p "`dirname $$@`"
@set -e; rm -f "$$@" || true; \
$$(CC) -MM -MQ "`echo "$$@" | sed 's/\.d$$$$/.o'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) "$$<" > $$@
@echo @ECHO_N@ ".@ECHO_C@"
endef
define CXXDEP_template
- %_$(1).d: %.cpp $$($(1)_HEADERS)
+ %_$(1).d: %.cpp $$($(1)_ALL_HEADERS)
+ @mkdir -p "`dirname $$@`"
@set -e; rm -f "$$@" || true; \
$$(CXX) -MM -MQ "`echo "$$<" | sed 's,\($$*\)\.cpp,\1_$(1).o,'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) "$$<" > $$@
@echo @ECHO_N@ ".@ECHO_C@"
endef
define CSRC_template
%_$(1).o: %.c
$$(CC) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) $$< -o $$@
endef
define CXXSRC_template
%_$(1).o: %.cpp
$$(CXX) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) $$< -o $$@
endef
define BINARY_template
- $$($(1)_BINARY): $$($(1)_OBJECTS)
+ $$($(1)_BINARY): $$($(1)_ALL_OBJECTS)
$$(CC) $$($(1)_ALL_LDFLAGS) $$($(1)_ALL_LIBS) $$^ $$(LOADLIBS) $$(LDLIBS) -o $$@
endef
$(foreach template,CDEP CXXDEP CSRC CXXSRC BINARY,$(foreach prog,$(PROGRAMS),$(eval $(call $(template)_template,$(prog)))))
all: $(BINARIES)
# this rule is just to add a newline after the dots from deps calculation
Makefile: $(DEPENDS)
@echo
@touch $@
%.tar.gz:
- tar -czf "$@" $^
+ rm -f $@
+ echo $(patsubst @top_srcdir@/%,%,$(filter @top_srcdir@/%,$^)) | tr ' ' '\n' | tar -C @top_srcdir@ -cf $(patsubst %.gz,%,$@) --files-from=-
+ tar -rf $(patsubst %.gz,%,$@) $(filter-out @top_srcdir@/%,$^)
+ gzip $(patsubst %.gz,%,$@)
@[email protected]: $(SOURCES) $(HEADERS) $(EXTRADIST)
DISTFILES=@[email protected]
dist: $(DISTFILES)
#################################
# extra stuff: change as needed #
#################################
AC_OUTPUT=configure config.h.in aclocal.m4
AC_OUTPUT_DIRS=autom4te.cache
CONFIG_OUTPUT=config.h Makefile config.log config.status
clean:
rm -f $(OBJECTS) $(BINARIES) $(DEPENDS) $(DISTFILES) src/backends/moc_qtwindow.cpp || true
clean-config:
rm -f $(CONFIG_OUTPUT) || true
clean-ac:
rm -f $(AC_OUTPUT) || true
rm -rf $(AC_OUTPUT_DIRS) || true
clean-full: clean clean-config clean-ac
moc_%.cpp: %.hpp
moc-qt4 $(SkywaysQt_CPPFLAGS) $(SkywaysQt_CXXFLAGS) $< -o $@
.PHONY: default dist clean clean-config clean-ac clean-full
-include $(DEPENDS)
|
devnev/skyways
|
2b24c318b53c848fb055f560893810364ef9fefb
|
Added various clean rules to Makefile.
|
diff --git a/Makefile.in b/Makefile.in
index be2707d..95403e8 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -1,177 +1,190 @@
#!/usr/bin/make
# @configure_input@
######################################
# configuration: change things here. #
######################################
PROGRAMS?=@programs@
SkywaysGlut_BINARY=skyways.glut
SkywaysQt_BINARY=skyways.qt
SkywaysSdl_BINARY=skyways.sdl
Common_HEADERS= \
src/configuration.hpp \
src/controller.hpp \
src/display/shader.hpp \
src/display/textprinter.hpp \
src/display/uniform.hpp \
src/game.hpp \
src/loading/blockloader.hpp \
src/loading/mapgenerator.hpp \
src/loading/maploader.hpp \
src/loading/objmodel.hpp \
src/range.hpp \
src/vector.hpp \
src/world/aabb.hpp \
src/world/block.hpp \
src/world/collisionaccelerator.hpp \
src/world/element.hpp \
src/world/map.hpp \
src/world/model.hpp \
src/world/ship.hpp \
#
SkywaysGlut_HEADERS= $(Common_HEADERS) \
src/backends/configparser.hpp \
#
SkywaysQt_HEADERS= $(Common_HEADERS) \
src/backends/qtconfigparser.hpp \
src/backends/qtwindow.hpp \
#
SkywaysSdl_HEADERS= $(Common_HEADERS) \
src/backends/configparser.hpp \
#
Common_CXXSOURCES= \
src/configuration.cpp \
src/controller.cpp \
src/display/shader.cpp \
src/display/textprinter.cpp \
src/game.cpp \
src/loading/blockloader.cpp \
src/loading/mapgenerator.cpp \
src/loading/maploader.cpp \
src/loading/objmodel.cpp \
src/world/block.cpp \
src/world/collisionaccelerator.cpp \
src/world/element.cpp \
src/world/map.cpp \
src/world/ship.cpp \
#
SkywaysGlut_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/configparser.cpp \
src/backends/glutmain.cpp \
#
SkywaysQt_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/moc_qtwindow.cpp \
src/backends/qtconfigparser.cpp \
src/backends/qtmain.cpp \
src/backends/qtwindow.cpp \
#
SkywaysSdl_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/configparser.cpp \
src/backends/sdlmain.cpp \
#
CFLAGS:= @CFLAGS@ -Wall $(CFLAGS)
CXXFLAGS:= @CXXFLAGS@ -Wall $(CXXFLAGS)
CPPFLAGS:= @CPPFLAGS@ -Wall @FTGL_CFLAGS@ @BOOST_CPPFLAGS@ $(CPPFLAGS) -Isrc
LDFLAGS:= @LDFLAGS@ @BOOST_LDFLAGS@ $(LDFLAGS)
LIBS:=@LIBS@ @FTGL_LIBS@ @BOOST_FILESYSTEM_LIB@ $(LIBS)
SkywaysGlut_LIBS=@GLUT_LIBS@ @BOOST_PROGRAM_OPTIONS_LIB@
SkywaysQt_CPPFLAGS=-D_REENTRANT -DQT_NO_DEBUG -DQT_OPENGL_LIB -DQT_GUI_LIB -DQT_CORE_LIB @QT_CFLAGS@
SkywaysQt_LIBS=@QT_LIBS@
SkywaysSdl_CPPFLAGS=@SDL_CFLAGS@
SkywaysSdl_LIBS=@SDL_LIBS@ @BOOST_PROGRAM_OPTIONS_LIB@
EXTRADIST=configure.ac Makefile.in configure config.h.in aclocal.m4 \
shaders/shader.glslf shaders/shader.glslv DejaVuSans.ttf\
blocks/cube blocks/flat blocks/tunnel world \
COPYING README
######################################
# auto-configuration: do not change! #
######################################
CWD:=$(shell pwd)
default: all
$(foreach prog,$(PROGRAMS),$(eval $(prog)_SOURCES=$($(prog)_CSOURCES) $($(prog)_CXXSOURCES)))
$(foreach prog,$(PROGRAMS),$(eval $(prog)_OBJECTS=$(patsubst %.c,%_$(prog).o,$($(prog)_CSOURCES)) $(patsubst %.cpp,%_$(prog).o,$($(prog)_CXXSOURCES))))
$(foreach flag,CFLAGS CPPFLAGS CXXFLAGS LDFLAGS LIBS,$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_$(flag)=$($(flag)) $($(prog)_$(flag)))))
SOURCES=$(foreach prog,$(PROGRAMS),$($(prog)_SOURCES))
HEADERS=$(foreach prog,$(PROGRAMS),$($(prog)_HEADERS))
OBJECTS=$(foreach prog,$(PROGRAMS),$($(prog)_OBJECTS))
BINARIES=$(foreach prog,$(PROGRAMS),$($(prog)_BINARY))
DEPENDS=$(patsubst %.o,%.d,$(OBJECTS))
define CDEP_template
%_$(1).d: %.c $$($(1)_HEADERS)
@set -e; rm -f "$$@" || true; \
$$(CC) -MM -MQ "`echo "$$@" | sed 's/\.d$$$$/.o'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) "$$<" > $$@
@echo @ECHO_N@ ".@ECHO_C@"
endef
define CXXDEP_template
%_$(1).d: %.cpp $$($(1)_HEADERS)
@set -e; rm -f "$$@" || true; \
$$(CXX) -MM -MQ "`echo "$$<" | sed 's,\($$*\)\.cpp,\1_$(1).o,'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) "$$<" > $$@
@echo @ECHO_N@ ".@ECHO_C@"
endef
define CSRC_template
%_$(1).o: %.c
$$(CC) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) $$< -o $$@
endef
define CXXSRC_template
%_$(1).o: %.cpp
$$(CXX) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) $$< -o $$@
endef
define BINARY_template
$$($(1)_BINARY): $$($(1)_OBJECTS)
$$(CC) $$($(1)_ALL_LDFLAGS) $$($(1)_ALL_LIBS) $$^ $$(LOADLIBS) $$(LDLIBS) -o $$@
endef
$(foreach template,CDEP CXXDEP CSRC CXXSRC BINARY,$(foreach prog,$(PROGRAMS),$(eval $(call $(template)_template,$(prog)))))
all: $(BINARIES)
# this rule is just to add a newline after the dots from deps calculation
Makefile: $(DEPENDS)
@echo
@touch $@
%.tar.gz:
tar -czf "$@" $^
@[email protected]: $(SOURCES) $(HEADERS) $(EXTRADIST)
DISTFILES=@[email protected]
dist: $(DISTFILES)
#################################
# extra stuff: change as needed #
#################################
+AC_OUTPUT=configure config.h.in aclocal.m4
+AC_OUTPUT_DIRS=autom4te.cache
+CONFIG_OUTPUT=config.h Makefile config.log config.status
+
clean:
- rm -f $(OBJECTS) $(BINARIES) $(DEPENDS) $(DISTFILES) || true
+ rm -f $(OBJECTS) $(BINARIES) $(DEPENDS) $(DISTFILES) src/backends/moc_qtwindow.cpp || true
+
+clean-config:
+ rm -f $(CONFIG_OUTPUT) || true
+
+clean-ac:
+ rm -f $(AC_OUTPUT) || true
+ rm -rf $(AC_OUTPUT_DIRS) || true
+
+clean-full: clean clean-config clean-ac
moc_%.cpp: %.hpp
moc-qt4 $(SkywaysQt_CPPFLAGS) $(SkywaysQt_CXXFLAGS) $< -o $@
-.PHONY: default dist clean
+.PHONY: default dist clean clean-config clean-ac clean-full
-include $(DEPENDS)
|
devnev/skyways
|
519dd80e4292a580a461d7e322d7f6c88b3de1d4
|
Added make target "dist".
|
diff --git a/Makefile.in b/Makefile.in
index 5c6f952..be2707d 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -1,163 +1,177 @@
#!/usr/bin/make
# @configure_input@
######################################
# configuration: change things here. #
######################################
PROGRAMS?=@programs@
SkywaysGlut_BINARY=skyways.glut
SkywaysQt_BINARY=skyways.qt
SkywaysSdl_BINARY=skyways.sdl
Common_HEADERS= \
src/configuration.hpp \
src/controller.hpp \
src/display/shader.hpp \
src/display/textprinter.hpp \
src/display/uniform.hpp \
src/game.hpp \
src/loading/blockloader.hpp \
src/loading/mapgenerator.hpp \
src/loading/maploader.hpp \
src/loading/objmodel.hpp \
src/range.hpp \
src/vector.hpp \
src/world/aabb.hpp \
src/world/block.hpp \
src/world/collisionaccelerator.hpp \
src/world/element.hpp \
src/world/map.hpp \
src/world/model.hpp \
src/world/ship.hpp \
#
SkywaysGlut_HEADERS= $(Common_HEADERS) \
src/backends/configparser.hpp \
#
SkywaysQt_HEADERS= $(Common_HEADERS) \
src/backends/qtconfigparser.hpp \
src/backends/qtwindow.hpp \
#
SkywaysSdl_HEADERS= $(Common_HEADERS) \
src/backends/configparser.hpp \
#
Common_CXXSOURCES= \
src/configuration.cpp \
src/controller.cpp \
src/display/shader.cpp \
src/display/textprinter.cpp \
src/game.cpp \
src/loading/blockloader.cpp \
src/loading/mapgenerator.cpp \
src/loading/maploader.cpp \
src/loading/objmodel.cpp \
src/world/block.cpp \
src/world/collisionaccelerator.cpp \
src/world/element.cpp \
src/world/map.cpp \
src/world/ship.cpp \
#
SkywaysGlut_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/configparser.cpp \
src/backends/glutmain.cpp \
#
SkywaysQt_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/moc_qtwindow.cpp \
src/backends/qtconfigparser.cpp \
src/backends/qtmain.cpp \
src/backends/qtwindow.cpp \
#
SkywaysSdl_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/configparser.cpp \
src/backends/sdlmain.cpp \
#
CFLAGS:= @CFLAGS@ -Wall $(CFLAGS)
CXXFLAGS:= @CXXFLAGS@ -Wall $(CXXFLAGS)
CPPFLAGS:= @CPPFLAGS@ -Wall @FTGL_CFLAGS@ @BOOST_CPPFLAGS@ $(CPPFLAGS) -Isrc
LDFLAGS:= @LDFLAGS@ @BOOST_LDFLAGS@ $(LDFLAGS)
LIBS:=@LIBS@ @FTGL_LIBS@ @BOOST_FILESYSTEM_LIB@ $(LIBS)
SkywaysGlut_LIBS=@GLUT_LIBS@ @BOOST_PROGRAM_OPTIONS_LIB@
SkywaysQt_CPPFLAGS=-D_REENTRANT -DQT_NO_DEBUG -DQT_OPENGL_LIB -DQT_GUI_LIB -DQT_CORE_LIB @QT_CFLAGS@
SkywaysQt_LIBS=@QT_LIBS@
SkywaysSdl_CPPFLAGS=@SDL_CFLAGS@
SkywaysSdl_LIBS=@SDL_LIBS@ @BOOST_PROGRAM_OPTIONS_LIB@
-EXTRADIST=
+EXTRADIST=configure.ac Makefile.in configure config.h.in aclocal.m4 \
+ shaders/shader.glslf shaders/shader.glslv DejaVuSans.ttf\
+ blocks/cube blocks/flat blocks/tunnel world \
+ COPYING README
######################################
# auto-configuration: do not change! #
######################################
CWD:=$(shell pwd)
default: all
$(foreach prog,$(PROGRAMS),$(eval $(prog)_SOURCES=$($(prog)_CSOURCES) $($(prog)_CXXSOURCES)))
$(foreach prog,$(PROGRAMS),$(eval $(prog)_OBJECTS=$(patsubst %.c,%_$(prog).o,$($(prog)_CSOURCES)) $(patsubst %.cpp,%_$(prog).o,$($(prog)_CXXSOURCES))))
$(foreach flag,CFLAGS CPPFLAGS CXXFLAGS LDFLAGS LIBS,$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_$(flag)=$($(flag)) $($(prog)_$(flag)))))
+SOURCES=$(foreach prog,$(PROGRAMS),$($(prog)_SOURCES))
+HEADERS=$(foreach prog,$(PROGRAMS),$($(prog)_HEADERS))
OBJECTS=$(foreach prog,$(PROGRAMS),$($(prog)_OBJECTS))
BINARIES=$(foreach prog,$(PROGRAMS),$($(prog)_BINARY))
DEPENDS=$(patsubst %.o,%.d,$(OBJECTS))
define CDEP_template
%_$(1).d: %.c $$($(1)_HEADERS)
@set -e; rm -f "$$@" || true; \
$$(CC) -MM -MQ "`echo "$$@" | sed 's/\.d$$$$/.o'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) "$$<" > $$@
@echo @ECHO_N@ ".@ECHO_C@"
endef
define CXXDEP_template
%_$(1).d: %.cpp $$($(1)_HEADERS)
@set -e; rm -f "$$@" || true; \
$$(CXX) -MM -MQ "`echo "$$<" | sed 's,\($$*\)\.cpp,\1_$(1).o,'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) "$$<" > $$@
@echo @ECHO_N@ ".@ECHO_C@"
endef
define CSRC_template
%_$(1).o: %.c
$$(CC) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) $$< -o $$@
endef
define CXXSRC_template
%_$(1).o: %.cpp
$$(CXX) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) $$< -o $$@
endef
define BINARY_template
$$($(1)_BINARY): $$($(1)_OBJECTS)
$$(CC) $$($(1)_ALL_LDFLAGS) $$($(1)_ALL_LIBS) $$^ $$(LOADLIBS) $$(LDLIBS) -o $$@
endef
$(foreach template,CDEP CXXDEP CSRC CXXSRC BINARY,$(foreach prog,$(PROGRAMS),$(eval $(call $(template)_template,$(prog)))))
all: $(BINARIES)
# this rule is just to add a newline after the dots from deps calculation
Makefile: $(DEPENDS)
@echo
@touch $@
+%.tar.gz:
+ tar -czf "$@" $^
+
+@[email protected]: $(SOURCES) $(HEADERS) $(EXTRADIST)
+
+DISTFILES=@[email protected]
+
+dist: $(DISTFILES)
+
#################################
# extra stuff: change as needed #
#################################
clean:
rm -f $(OBJECTS) $(BINARIES) $(DEPENDS) $(DISTFILES) || true
moc_%.cpp: %.hpp
moc-qt4 $(SkywaysQt_CPPFLAGS) $(SkywaysQt_CXXFLAGS) $< -o $@
-.PHONY: default clean
+.PHONY: default dist clean
-include $(DEPENDS)
|
devnev/skyways
|
90f92ff5c4c43712e1257dc5c66720cfc257a2fc
|
Fixed build files to detect Boost using autoconf.
|
diff --git a/Makefile.in b/Makefile.in
index bc22738..5c6f952 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -1,163 +1,163 @@
#!/usr/bin/make
# @configure_input@
######################################
# configuration: change things here. #
######################################
PROGRAMS?=@programs@
SkywaysGlut_BINARY=skyways.glut
SkywaysQt_BINARY=skyways.qt
SkywaysSdl_BINARY=skyways.sdl
Common_HEADERS= \
src/configuration.hpp \
src/controller.hpp \
src/display/shader.hpp \
src/display/textprinter.hpp \
src/display/uniform.hpp \
src/game.hpp \
src/loading/blockloader.hpp \
src/loading/mapgenerator.hpp \
src/loading/maploader.hpp \
src/loading/objmodel.hpp \
src/range.hpp \
src/vector.hpp \
src/world/aabb.hpp \
src/world/block.hpp \
src/world/collisionaccelerator.hpp \
src/world/element.hpp \
src/world/map.hpp \
src/world/model.hpp \
src/world/ship.hpp \
#
SkywaysGlut_HEADERS= $(Common_HEADERS) \
src/backends/configparser.hpp \
#
SkywaysQt_HEADERS= $(Common_HEADERS) \
src/backends/qtconfigparser.hpp \
src/backends/qtwindow.hpp \
#
SkywaysSdl_HEADERS= $(Common_HEADERS) \
src/backends/configparser.hpp \
#
Common_CXXSOURCES= \
src/configuration.cpp \
src/controller.cpp \
src/display/shader.cpp \
src/display/textprinter.cpp \
src/game.cpp \
src/loading/blockloader.cpp \
src/loading/mapgenerator.cpp \
src/loading/maploader.cpp \
src/loading/objmodel.cpp \
src/world/block.cpp \
src/world/collisionaccelerator.cpp \
src/world/element.cpp \
src/world/map.cpp \
src/world/ship.cpp \
#
SkywaysGlut_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/configparser.cpp \
src/backends/glutmain.cpp \
#
SkywaysQt_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/moc_qtwindow.cpp \
src/backends/qtconfigparser.cpp \
src/backends/qtmain.cpp \
src/backends/qtwindow.cpp \
#
SkywaysSdl_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/configparser.cpp \
src/backends/sdlmain.cpp \
#
CFLAGS:= @CFLAGS@ -Wall $(CFLAGS)
CXXFLAGS:= @CXXFLAGS@ -Wall $(CXXFLAGS)
-CPPFLAGS:= @CPPFLAGS@ -Wall @FTGL_CFLAGS@ $(CPPFLAGS) -Isrc
-LDFLAGS:= @LDFLAGS@ $(LDFLAGS)
-LIBS:=@LIBS@ @FTGL_LIBS@ -lboost_filesystem $(LIBS)
+CPPFLAGS:= @CPPFLAGS@ -Wall @FTGL_CFLAGS@ @BOOST_CPPFLAGS@ $(CPPFLAGS) -Isrc
+LDFLAGS:= @LDFLAGS@ @BOOST_LDFLAGS@ $(LDFLAGS)
+LIBS:=@LIBS@ @FTGL_LIBS@ @BOOST_FILESYSTEM_LIB@ $(LIBS)
-SkywaysGlut_LIBS=@GLUT_LIBS@ -lboost_program_options
+SkywaysGlut_LIBS=@GLUT_LIBS@ @BOOST_PROGRAM_OPTIONS_LIB@
SkywaysQt_CPPFLAGS=-D_REENTRANT -DQT_NO_DEBUG -DQT_OPENGL_LIB -DQT_GUI_LIB -DQT_CORE_LIB @QT_CFLAGS@
SkywaysQt_LIBS=@QT_LIBS@
SkywaysSdl_CPPFLAGS=@SDL_CFLAGS@
-SkywaysSdl_LIBS=@SDL_LIBS@ -lboost_program_options
+SkywaysSdl_LIBS=@SDL_LIBS@ @BOOST_PROGRAM_OPTIONS_LIB@
EXTRADIST=
######################################
# auto-configuration: do not change! #
######################################
CWD:=$(shell pwd)
default: all
$(foreach prog,$(PROGRAMS),$(eval $(prog)_SOURCES=$($(prog)_CSOURCES) $($(prog)_CXXSOURCES)))
$(foreach prog,$(PROGRAMS),$(eval $(prog)_OBJECTS=$(patsubst %.c,%_$(prog).o,$($(prog)_CSOURCES)) $(patsubst %.cpp,%_$(prog).o,$($(prog)_CXXSOURCES))))
$(foreach flag,CFLAGS CPPFLAGS CXXFLAGS LDFLAGS LIBS,$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_$(flag)=$($(flag)) $($(prog)_$(flag)))))
OBJECTS=$(foreach prog,$(PROGRAMS),$($(prog)_OBJECTS))
BINARIES=$(foreach prog,$(PROGRAMS),$($(prog)_BINARY))
DEPENDS=$(patsubst %.o,%.d,$(OBJECTS))
define CDEP_template
%_$(1).d: %.c $$($(1)_HEADERS)
@set -e; rm -f "$$@" || true; \
$$(CC) -MM -MQ "`echo "$$@" | sed 's/\.d$$$$/.o'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) "$$<" > $$@
@echo @ECHO_N@ ".@ECHO_C@"
endef
define CXXDEP_template
%_$(1).d: %.cpp $$($(1)_HEADERS)
@set -e; rm -f "$$@" || true; \
$$(CXX) -MM -MQ "`echo "$$<" | sed 's,\($$*\)\.cpp,\1_$(1).o,'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) "$$<" > $$@
@echo @ECHO_N@ ".@ECHO_C@"
endef
define CSRC_template
%_$(1).o: %.c
$$(CC) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) $$< -o $$@
endef
define CXXSRC_template
%_$(1).o: %.cpp
$$(CXX) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) $$< -o $$@
endef
define BINARY_template
$$($(1)_BINARY): $$($(1)_OBJECTS)
$$(CC) $$($(1)_ALL_LDFLAGS) $$($(1)_ALL_LIBS) $$^ $$(LOADLIBS) $$(LDLIBS) -o $$@
endef
$(foreach template,CDEP CXXDEP CSRC CXXSRC BINARY,$(foreach prog,$(PROGRAMS),$(eval $(call $(template)_template,$(prog)))))
all: $(BINARIES)
# this rule is just to add a newline after the dots from deps calculation
Makefile: $(DEPENDS)
@echo
@touch $@
#################################
# extra stuff: change as needed #
#################################
clean:
rm -f $(OBJECTS) $(BINARIES) $(DEPENDS) $(DISTFILES) || true
moc_%.cpp: %.hpp
moc-qt4 $(SkywaysQt_CPPFLAGS) $(SkywaysQt_CXXFLAGS) $< -o $@
.PHONY: default clean
-include $(DEPENDS)
diff --git a/configure.ac b/configure.ac
index bd31d8e..6fa7216 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,111 +1,111 @@
# -*- Autoconf -*-
# vim: ft=m4
# Process this file with autoconf to produce a configure script.
AC_PREREQ([2.63])
AC_INIT([skyways], [0.0.1], [[email protected]])
AC_CONFIG_MACRO_DIR([m4])
AC_CONFIG_SRCDIR([src/configuration.hpp])
AC_CONFIG_HEADERS([config.h])
# Checks for programs.
AC_PROG_CXX
PKG_PROG_PKG_CONFIG
# Checks for libraries.
AC_CHECK_LIB([GL], [glGetString])
AC_CHECK_LIB([GLEW], [glewInit])
PKG_CHECK_MODULES([FTGL],[ftgl >= 2.1])
-dnl FIXME: check for boost
-dnl AC_CHECK_LIB([boost_filesystem], [main])
-dnl AC_CHECK_LIB([boost_program_options], [main])
+AX_BOOST_BASE([1.35.0])
+AX_BOOST_FILESYSTEM
+AX_BOOST_PROGRAM_OPTIONS
programs=""
AC_ARG_ENABLE([qt], AS_HELP_STRING([--enable-qt], [Enable Qt backend (default: test)]),
[ if test "x$enableval" = "xyes" ; then qt_backend=yes
elif test "x$enableval" = "xtest" ; then qt_backend=test
elif test "x$enableval" = "xno" ; then qt_backend=no
else echo "Error: unknown --enable-qt option $enableval" ; exit 1
fi
],
[ qt_backend=test
])
if test "x$qt_backend" == "xyes" ; then
PKG_CHECK_MODULES([QT],[QtCore >= 4.5.0 QtGui >= 4.5.0 QtOpenGL >= 4.5.0])
AC_CHECK_LIB([pthread],[pthread_create],[QT_LIBS="-lpthread $QT_LIBS"])
AC_CHECK_LIB([GLU], [gluGetString],[QT_LIBS="-lGLU $QT_LIBS"])
elif test "x$qt_backend" == "xtest" ; then
PKG_CHECK_MODULES([QT],[QtCore >= 4.5.0 QtGui >= 4.5.0 QtOpenGL >= 4.5.0],[qt_backend="yes"],[qt_backend="no"])
if test "x$qt_backend" = "xyes" ; then
AC_CHECK_LIB([pthread],[pthread_create],[QT_LIBS="-lpthread $QT_LIBS"; qt_backend="yes"],[qt_backend="no"])
fi
if test "x$qt_backend" = "xyes" ; then
AC_CHECK_LIB([GLU], [gluGetString],[QT_LIBS="-lGLU $QT_LIBS"; qt_backend="yes"],[qt_backend="no"])
fi
fi
AC_SUBST(qt_backend)
if test "x$qt_backend" = "xyes" ; then
programs="SkywaysQt $programs"
fi
AC_ARG_ENABLE([sdl], AS_HELP_STRING([--enable-sdl], [Enable SDL backend (default: test)]),
[ if test "x$enableval" = "xyes" ; then sdl_backend=yes
elif test "x$enableval" = "xtest" ; then sdl_backend=test
elif test "x$enableval" = "xno" ; then sdl_backend=no
else echo "Error: unknown --enable-sdl option $enableval" ; exit 1
fi
],
[ sdl_backend=test
])
if test "x$sdl_backend" == "xyes" ; then
PKG_CHECK_MODULES([SDL],[sdl >= 1.2.13])
elif test "x$sdl_backend" == "xtest" ; then
PKG_CHECK_MODULES([SDL],[sdl >= 1.2.13],[sdl_backend="yes"],[sdl_backend="no"])
fi
AC_SUBST(sdl_backend)
if test "x$sdl_backend" = "xyes" ; then
programs="SkywaysSdl $programs"
fi
AC_ARG_ENABLE([glut], AS_HELP_STRING([--enable-glut], [Enable GLUT backend (default: test)]),
[ if test "x$enableval" = "xyes" ; then glut_backend=yes
elif test "x$enableval" = "xtest" ; then glut_backend=test
elif test "x$enableval" = "xno" ; then glut_backend=no
else echo "Error: unknown --enable-glut option $enableval" ; exit 1
fi
],
[ glut_backend=test
])
if test "x$glut_backend" == "xyes" ; then
AC_CHECK_LIB([glut],[glutMainLoop],[GLUT_LIBS="-lglut"])
elif test "x$glut_backend" == "xtest" ; then
AC_CHECK_LIB([glut],[glutMainLoop],[GLUT_LIBS="-lglut"; glut_backend="yes"],[glut_backend="no"])
fi
AC_SUBST(glut_backend)
AC_SUBST(GLUT_LIBS)
if test "x$glut_backend" = "xyes" ; then
programs="SkywaysGlut $programs"
fi
if test -z "$programs" ; then
echo "Error: no backends will be built, aborting."
exit 1
fi
AC_SUBST(programs)
# Checks for header files.
# Checks for typedefs, structures, and compiler characteristics.
# Checks for library functions.
AC_CONFIG_FILES([Makefile])
AC_OUTPUT
echo "Configuration complete. Backends to be built:"
echo " Qt backend... $qt_backend"
echo " SDL backend... $sdl_backend"
echo " GLUT backend... $glut_backend"
|
devnev/skyways
|
380099b2720b4b928f69b0d6d1ca08fd5c0585a0
|
Added configuration status output to end of configure.ac.
|
diff --git a/configure.ac b/configure.ac
index ba681c2..bd31d8e 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,106 +1,111 @@
# -*- Autoconf -*-
# vim: ft=m4
# Process this file with autoconf to produce a configure script.
AC_PREREQ([2.63])
AC_INIT([skyways], [0.0.1], [[email protected]])
AC_CONFIG_MACRO_DIR([m4])
AC_CONFIG_SRCDIR([src/configuration.hpp])
AC_CONFIG_HEADERS([config.h])
# Checks for programs.
AC_PROG_CXX
PKG_PROG_PKG_CONFIG
# Checks for libraries.
AC_CHECK_LIB([GL], [glGetString])
AC_CHECK_LIB([GLEW], [glewInit])
PKG_CHECK_MODULES([FTGL],[ftgl >= 2.1])
dnl FIXME: check for boost
dnl AC_CHECK_LIB([boost_filesystem], [main])
dnl AC_CHECK_LIB([boost_program_options], [main])
programs=""
AC_ARG_ENABLE([qt], AS_HELP_STRING([--enable-qt], [Enable Qt backend (default: test)]),
[ if test "x$enableval" = "xyes" ; then qt_backend=yes
elif test "x$enableval" = "xtest" ; then qt_backend=test
elif test "x$enableval" = "xno" ; then qt_backend=no
else echo "Error: unknown --enable-qt option $enableval" ; exit 1
fi
],
[ qt_backend=test
])
if test "x$qt_backend" == "xyes" ; then
PKG_CHECK_MODULES([QT],[QtCore >= 4.5.0 QtGui >= 4.5.0 QtOpenGL >= 4.5.0])
AC_CHECK_LIB([pthread],[pthread_create],[QT_LIBS="-lpthread $QT_LIBS"])
AC_CHECK_LIB([GLU], [gluGetString],[QT_LIBS="-lGLU $QT_LIBS"])
elif test "x$qt_backend" == "xtest" ; then
PKG_CHECK_MODULES([QT],[QtCore >= 4.5.0 QtGui >= 4.5.0 QtOpenGL >= 4.5.0],[qt_backend="yes"],[qt_backend="no"])
if test "x$qt_backend" = "xyes" ; then
AC_CHECK_LIB([pthread],[pthread_create],[QT_LIBS="-lpthread $QT_LIBS"; qt_backend="yes"],[qt_backend="no"])
fi
if test "x$qt_backend" = "xyes" ; then
AC_CHECK_LIB([GLU], [gluGetString],[QT_LIBS="-lGLU $QT_LIBS"; qt_backend="yes"],[qt_backend="no"])
fi
fi
AC_SUBST(qt_backend)
if test "x$qt_backend" = "xyes" ; then
programs="SkywaysQt $programs"
fi
AC_ARG_ENABLE([sdl], AS_HELP_STRING([--enable-sdl], [Enable SDL backend (default: test)]),
[ if test "x$enableval" = "xyes" ; then sdl_backend=yes
elif test "x$enableval" = "xtest" ; then sdl_backend=test
elif test "x$enableval" = "xno" ; then sdl_backend=no
else echo "Error: unknown --enable-sdl option $enableval" ; exit 1
fi
],
[ sdl_backend=test
])
if test "x$sdl_backend" == "xyes" ; then
PKG_CHECK_MODULES([SDL],[sdl >= 1.2.13])
elif test "x$sdl_backend" == "xtest" ; then
PKG_CHECK_MODULES([SDL],[sdl >= 1.2.13],[sdl_backend="yes"],[sdl_backend="no"])
fi
AC_SUBST(sdl_backend)
if test "x$sdl_backend" = "xyes" ; then
programs="SkywaysSdl $programs"
fi
AC_ARG_ENABLE([glut], AS_HELP_STRING([--enable-glut], [Enable GLUT backend (default: test)]),
[ if test "x$enableval" = "xyes" ; then glut_backend=yes
elif test "x$enableval" = "xtest" ; then glut_backend=test
elif test "x$enableval" = "xno" ; then glut_backend=no
else echo "Error: unknown --enable-glut option $enableval" ; exit 1
fi
],
[ glut_backend=test
])
if test "x$glut_backend" == "xyes" ; then
AC_CHECK_LIB([glut],[glutMainLoop],[GLUT_LIBS="-lglut"])
elif test "x$glut_backend" == "xtest" ; then
AC_CHECK_LIB([glut],[glutMainLoop],[GLUT_LIBS="-lglut"; glut_backend="yes"],[glut_backend="no"])
fi
AC_SUBST(glut_backend)
AC_SUBST(GLUT_LIBS)
if test "x$glut_backend" = "xyes" ; then
programs="SkywaysGlut $programs"
fi
if test -z "$programs" ; then
echo "Error: no backends will be built, aborting."
exit 1
fi
AC_SUBST(programs)
# Checks for header files.
# Checks for typedefs, structures, and compiler characteristics.
# Checks for library functions.
AC_CONFIG_FILES([Makefile])
AC_OUTPUT
+
+echo "Configuration complete. Backends to be built:"
+echo " Qt backend... $qt_backend"
+echo " SDL backend... $sdl_backend"
+echo " GLUT backend... $glut_backend"
|
devnev/skyways
|
d77cfd908510a43f1e7b21d532b8adcd75a603fd
|
Various minor correctness and portability fixes to Makefile.in.
|
diff --git a/Makefile.in b/Makefile.in
index 29bf3f6..bc22738 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -1,158 +1,163 @@
#!/usr/bin/make
+# @configure_input@
+
######################################
# configuration: change things here. #
######################################
PROGRAMS?=@programs@
SkywaysGlut_BINARY=skyways.glut
SkywaysQt_BINARY=skyways.qt
SkywaysSdl_BINARY=skyways.sdl
Common_HEADERS= \
src/configuration.hpp \
src/controller.hpp \
src/display/shader.hpp \
src/display/textprinter.hpp \
src/display/uniform.hpp \
src/game.hpp \
src/loading/blockloader.hpp \
src/loading/mapgenerator.hpp \
src/loading/maploader.hpp \
src/loading/objmodel.hpp \
src/range.hpp \
src/vector.hpp \
src/world/aabb.hpp \
src/world/block.hpp \
src/world/collisionaccelerator.hpp \
src/world/element.hpp \
src/world/map.hpp \
src/world/model.hpp \
src/world/ship.hpp \
#
SkywaysGlut_HEADERS= $(Common_HEADERS) \
src/backends/configparser.hpp \
#
SkywaysQt_HEADERS= $(Common_HEADERS) \
src/backends/qtconfigparser.hpp \
src/backends/qtwindow.hpp \
#
SkywaysSdl_HEADERS= $(Common_HEADERS) \
src/backends/configparser.hpp \
#
Common_CXXSOURCES= \
src/configuration.cpp \
src/controller.cpp \
src/display/shader.cpp \
src/display/textprinter.cpp \
src/game.cpp \
src/loading/blockloader.cpp \
src/loading/mapgenerator.cpp \
src/loading/maploader.cpp \
src/loading/objmodel.cpp \
src/world/block.cpp \
src/world/collisionaccelerator.cpp \
src/world/element.cpp \
src/world/map.cpp \
src/world/ship.cpp \
#
SkywaysGlut_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/configparser.cpp \
src/backends/glutmain.cpp \
#
SkywaysQt_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/moc_qtwindow.cpp \
src/backends/qtconfigparser.cpp \
src/backends/qtmain.cpp \
src/backends/qtwindow.cpp \
#
SkywaysSdl_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/configparser.cpp \
src/backends/sdlmain.cpp \
#
-CPPFLAGS:= @CFLAGS@ -Wall @FTGL_CFLAGS@ $(CPPFLAGS) -Isrc
-LDFLAGS:= @LIBS@ -lboost_filesystem @FTGL_LIBS@ $(LDFLAGS)
+CFLAGS:= @CFLAGS@ -Wall $(CFLAGS)
+CXXFLAGS:= @CXXFLAGS@ -Wall $(CXXFLAGS)
+CPPFLAGS:= @CPPFLAGS@ -Wall @FTGL_CFLAGS@ $(CPPFLAGS) -Isrc
+LDFLAGS:= @LDFLAGS@ $(LDFLAGS)
+LIBS:=@LIBS@ @FTGL_LIBS@ -lboost_filesystem $(LIBS)
-SkywaysGlut_LDFLAGS=@GLUT_LIBS@ -lboost_program_options
-SkywaysQt_LDFLAGS=@QT_LIBS@
+SkywaysGlut_LIBS=@GLUT_LIBS@ -lboost_program_options
SkywaysQt_CPPFLAGS=-D_REENTRANT -DQT_NO_DEBUG -DQT_OPENGL_LIB -DQT_GUI_LIB -DQT_CORE_LIB @QT_CFLAGS@
-SkywaysSdl_LDFLAGS=@SDL_LIBS@ -lboost_program_options
+SkywaysQt_LIBS=@QT_LIBS@
SkywaysSdl_CPPFLAGS=@SDL_CFLAGS@
+SkywaysSdl_LIBS=@SDL_LIBS@ -lboost_program_options
EXTRADIST=
######################################
# auto-configuration: do not change! #
######################################
CWD:=$(shell pwd)
default: all
$(foreach prog,$(PROGRAMS),$(eval $(prog)_SOURCES=$($(prog)_CSOURCES) $($(prog)_CXXSOURCES)))
$(foreach prog,$(PROGRAMS),$(eval $(prog)_OBJECTS=$(patsubst %.c,%_$(prog).o,$($(prog)_CSOURCES)) $(patsubst %.cpp,%_$(prog).o,$($(prog)_CXXSOURCES))))
-$(foreach flag,CFLAGS CPPFLAGS CXXFLAGS LDFLAGS,$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_$(flag)=$($(flag)) $($(prog)_$(flag)))))
+$(foreach flag,CFLAGS CPPFLAGS CXXFLAGS LDFLAGS LIBS,$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_$(flag)=$($(flag)) $($(prog)_$(flag)))))
OBJECTS=$(foreach prog,$(PROGRAMS),$($(prog)_OBJECTS))
BINARIES=$(foreach prog,$(PROGRAMS),$($(prog)_BINARY))
DEPENDS=$(patsubst %.o,%.d,$(OBJECTS))
define CDEP_template
%_$(1).d: %.c $$($(1)_HEADERS)
@set -e; rm -f "$$@" || true; \
$$(CC) -MM -MQ "`echo "$$@" | sed 's/\.d$$$$/.o'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) "$$<" > $$@
- @echo -n .
+ @echo @ECHO_N@ ".@ECHO_C@"
endef
define CXXDEP_template
%_$(1).d: %.cpp $$($(1)_HEADERS)
@set -e; rm -f "$$@" || true; \
$$(CXX) -MM -MQ "`echo "$$<" | sed 's,\($$*\)\.cpp,\1_$(1).o,'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) "$$<" > $$@
- @echo -n .
+ @echo @ECHO_N@ ".@ECHO_C@"
endef
define CSRC_template
%_$(1).o: %.c
$$(CC) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) $$< -o $$@
endef
define CXXSRC_template
%_$(1).o: %.cpp
$$(CXX) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) $$< -o $$@
endef
define BINARY_template
$$($(1)_BINARY): $$($(1)_OBJECTS)
- $$(CC) $$($(1)_ALL_LDFLAGS) $$^ $$(LOADLIBS) $$(LDLIBS) -o $$@
+ $$(CC) $$($(1)_ALL_LDFLAGS) $$($(1)_ALL_LIBS) $$^ $$(LOADLIBS) $$(LDLIBS) -o $$@
endef
$(foreach template,CDEP CXXDEP CSRC CXXSRC BINARY,$(foreach prog,$(PROGRAMS),$(eval $(call $(template)_template,$(prog)))))
all: $(BINARIES)
# this rule is just to add a newline after the dots from deps calculation
Makefile: $(DEPENDS)
@echo
@touch $@
#################################
# extra stuff: change as needed #
#################################
clean:
rm -f $(OBJECTS) $(BINARIES) $(DEPENDS) $(DISTFILES) || true
moc_%.cpp: %.hpp
moc-qt4 $(SkywaysQt_CPPFLAGS) $(SkywaysQt_CXXFLAGS) $< -o $@
.PHONY: default clean
-include $(DEPENDS)
|
devnev/skyways
|
65d092546f59ab482e2503130340240a0f8ddd0c
|
Added check that something will be built to configure.ac.
|
diff --git a/configure.ac b/configure.ac
index e9f33ee..ba681c2 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,101 +1,106 @@
# -*- Autoconf -*-
# vim: ft=m4
# Process this file with autoconf to produce a configure script.
AC_PREREQ([2.63])
AC_INIT([skyways], [0.0.1], [[email protected]])
AC_CONFIG_MACRO_DIR([m4])
AC_CONFIG_SRCDIR([src/configuration.hpp])
AC_CONFIG_HEADERS([config.h])
# Checks for programs.
AC_PROG_CXX
PKG_PROG_PKG_CONFIG
# Checks for libraries.
AC_CHECK_LIB([GL], [glGetString])
AC_CHECK_LIB([GLEW], [glewInit])
PKG_CHECK_MODULES([FTGL],[ftgl >= 2.1])
dnl FIXME: check for boost
dnl AC_CHECK_LIB([boost_filesystem], [main])
dnl AC_CHECK_LIB([boost_program_options], [main])
programs=""
AC_ARG_ENABLE([qt], AS_HELP_STRING([--enable-qt], [Enable Qt backend (default: test)]),
[ if test "x$enableval" = "xyes" ; then qt_backend=yes
elif test "x$enableval" = "xtest" ; then qt_backend=test
elif test "x$enableval" = "xno" ; then qt_backend=no
else echo "Error: unknown --enable-qt option $enableval" ; exit 1
fi
],
[ qt_backend=test
])
if test "x$qt_backend" == "xyes" ; then
PKG_CHECK_MODULES([QT],[QtCore >= 4.5.0 QtGui >= 4.5.0 QtOpenGL >= 4.5.0])
AC_CHECK_LIB([pthread],[pthread_create],[QT_LIBS="-lpthread $QT_LIBS"])
AC_CHECK_LIB([GLU], [gluGetString],[QT_LIBS="-lGLU $QT_LIBS"])
elif test "x$qt_backend" == "xtest" ; then
PKG_CHECK_MODULES([QT],[QtCore >= 4.5.0 QtGui >= 4.5.0 QtOpenGL >= 4.5.0],[qt_backend="yes"],[qt_backend="no"])
if test "x$qt_backend" = "xyes" ; then
AC_CHECK_LIB([pthread],[pthread_create],[QT_LIBS="-lpthread $QT_LIBS"; qt_backend="yes"],[qt_backend="no"])
fi
if test "x$qt_backend" = "xyes" ; then
AC_CHECK_LIB([GLU], [gluGetString],[QT_LIBS="-lGLU $QT_LIBS"; qt_backend="yes"],[qt_backend="no"])
fi
fi
AC_SUBST(qt_backend)
if test "x$qt_backend" = "xyes" ; then
programs="SkywaysQt $programs"
fi
AC_ARG_ENABLE([sdl], AS_HELP_STRING([--enable-sdl], [Enable SDL backend (default: test)]),
[ if test "x$enableval" = "xyes" ; then sdl_backend=yes
elif test "x$enableval" = "xtest" ; then sdl_backend=test
elif test "x$enableval" = "xno" ; then sdl_backend=no
else echo "Error: unknown --enable-sdl option $enableval" ; exit 1
fi
],
[ sdl_backend=test
])
if test "x$sdl_backend" == "xyes" ; then
PKG_CHECK_MODULES([SDL],[sdl >= 1.2.13])
elif test "x$sdl_backend" == "xtest" ; then
PKG_CHECK_MODULES([SDL],[sdl >= 1.2.13],[sdl_backend="yes"],[sdl_backend="no"])
fi
AC_SUBST(sdl_backend)
if test "x$sdl_backend" = "xyes" ; then
programs="SkywaysSdl $programs"
fi
AC_ARG_ENABLE([glut], AS_HELP_STRING([--enable-glut], [Enable GLUT backend (default: test)]),
[ if test "x$enableval" = "xyes" ; then glut_backend=yes
elif test "x$enableval" = "xtest" ; then glut_backend=test
elif test "x$enableval" = "xno" ; then glut_backend=no
else echo "Error: unknown --enable-glut option $enableval" ; exit 1
fi
],
[ glut_backend=test
])
if test "x$glut_backend" == "xyes" ; then
AC_CHECK_LIB([glut],[glutMainLoop],[GLUT_LIBS="-lglut"])
elif test "x$glut_backend" == "xtest" ; then
AC_CHECK_LIB([glut],[glutMainLoop],[GLUT_LIBS="-lglut"; glut_backend="yes"],[glut_backend="no"])
fi
AC_SUBST(glut_backend)
AC_SUBST(GLUT_LIBS)
if test "x$glut_backend" = "xyes" ; then
programs="SkywaysGlut $programs"
fi
+if test -z "$programs" ; then
+ echo "Error: no backends will be built, aborting."
+ exit 1
+fi
+
AC_SUBST(programs)
# Checks for header files.
# Checks for typedefs, structures, and compiler characteristics.
# Checks for library functions.
AC_CONFIG_FILES([Makefile])
AC_OUTPUT
|
devnev/skyways
|
0e000681afddbac7a6b902474eead774ba303595
|
Fixed unadjusted AC_INIT parameters.
|
diff --git a/configure.ac b/configure.ac
index e2eed54..e9f33ee 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,101 +1,101 @@
# -*- Autoconf -*-
# vim: ft=m4
# Process this file with autoconf to produce a configure script.
AC_PREREQ([2.63])
-AC_INIT([FULL-PACKAGE-NAME], [VERSION], [BUG-REPORT-ADDRESS])
+AC_INIT([skyways], [0.0.1], [[email protected]])
AC_CONFIG_MACRO_DIR([m4])
AC_CONFIG_SRCDIR([src/configuration.hpp])
AC_CONFIG_HEADERS([config.h])
# Checks for programs.
AC_PROG_CXX
PKG_PROG_PKG_CONFIG
# Checks for libraries.
AC_CHECK_LIB([GL], [glGetString])
AC_CHECK_LIB([GLEW], [glewInit])
PKG_CHECK_MODULES([FTGL],[ftgl >= 2.1])
dnl FIXME: check for boost
dnl AC_CHECK_LIB([boost_filesystem], [main])
dnl AC_CHECK_LIB([boost_program_options], [main])
programs=""
AC_ARG_ENABLE([qt], AS_HELP_STRING([--enable-qt], [Enable Qt backend (default: test)]),
[ if test "x$enableval" = "xyes" ; then qt_backend=yes
elif test "x$enableval" = "xtest" ; then qt_backend=test
elif test "x$enableval" = "xno" ; then qt_backend=no
else echo "Error: unknown --enable-qt option $enableval" ; exit 1
fi
],
[ qt_backend=test
])
if test "x$qt_backend" == "xyes" ; then
PKG_CHECK_MODULES([QT],[QtCore >= 4.5.0 QtGui >= 4.5.0 QtOpenGL >= 4.5.0])
AC_CHECK_LIB([pthread],[pthread_create],[QT_LIBS="-lpthread $QT_LIBS"])
AC_CHECK_LIB([GLU], [gluGetString],[QT_LIBS="-lGLU $QT_LIBS"])
elif test "x$qt_backend" == "xtest" ; then
PKG_CHECK_MODULES([QT],[QtCore >= 4.5.0 QtGui >= 4.5.0 QtOpenGL >= 4.5.0],[qt_backend="yes"],[qt_backend="no"])
if test "x$qt_backend" = "xyes" ; then
AC_CHECK_LIB([pthread],[pthread_create],[QT_LIBS="-lpthread $QT_LIBS"; qt_backend="yes"],[qt_backend="no"])
fi
if test "x$qt_backend" = "xyes" ; then
AC_CHECK_LIB([GLU], [gluGetString],[QT_LIBS="-lGLU $QT_LIBS"; qt_backend="yes"],[qt_backend="no"])
fi
fi
AC_SUBST(qt_backend)
if test "x$qt_backend" = "xyes" ; then
programs="SkywaysQt $programs"
fi
AC_ARG_ENABLE([sdl], AS_HELP_STRING([--enable-sdl], [Enable SDL backend (default: test)]),
[ if test "x$enableval" = "xyes" ; then sdl_backend=yes
elif test "x$enableval" = "xtest" ; then sdl_backend=test
elif test "x$enableval" = "xno" ; then sdl_backend=no
else echo "Error: unknown --enable-sdl option $enableval" ; exit 1
fi
],
[ sdl_backend=test
])
if test "x$sdl_backend" == "xyes" ; then
PKG_CHECK_MODULES([SDL],[sdl >= 1.2.13])
elif test "x$sdl_backend" == "xtest" ; then
PKG_CHECK_MODULES([SDL],[sdl >= 1.2.13],[sdl_backend="yes"],[sdl_backend="no"])
fi
AC_SUBST(sdl_backend)
if test "x$sdl_backend" = "xyes" ; then
programs="SkywaysSdl $programs"
fi
AC_ARG_ENABLE([glut], AS_HELP_STRING([--enable-glut], [Enable GLUT backend (default: test)]),
[ if test "x$enableval" = "xyes" ; then glut_backend=yes
elif test "x$enableval" = "xtest" ; then glut_backend=test
elif test "x$enableval" = "xno" ; then glut_backend=no
else echo "Error: unknown --enable-glut option $enableval" ; exit 1
fi
],
[ glut_backend=test
])
if test "x$glut_backend" == "xyes" ; then
AC_CHECK_LIB([glut],[glutMainLoop],[GLUT_LIBS="-lglut"])
elif test "x$glut_backend" == "xtest" ; then
AC_CHECK_LIB([glut],[glutMainLoop],[GLUT_LIBS="-lglut"; glut_backend="yes"],[glut_backend="no"])
fi
AC_SUBST(glut_backend)
AC_SUBST(GLUT_LIBS)
if test "x$glut_backend" = "xyes" ; then
programs="SkywaysGlut $programs"
fi
AC_SUBST(programs)
# Checks for header files.
# Checks for typedefs, structures, and compiler characteristics.
# Checks for library functions.
AC_CONFIG_FILES([Makefile])
AC_OUTPUT
|
devnev/skyways
|
76f483bb7361a48fe2d579cba11f73186239a079
|
Added autoconf output to .gitignore.
|
diff --git a/.gitignore b/.gitignore
index 616b08a..04868c3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,6 +1,14 @@
*.o
*.d
skyways.glut
skyways.qt
skyways.sdl
moc_*.cpp
+Makefile
+aclocal.m4
+autom4te.cache/
+config.h
+config.h.in
+config.log
+config.status
+configure
|
devnev/skyways
|
5f27d3a986ce5f78cedf97086a6e47fee66a4b0e
|
Applied autoconf compile/link flag substitutions to Makefile.
|
diff --git a/Makefile.in b/Makefile.in
index a2f7db7..29bf3f6 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -1,158 +1,158 @@
#!/usr/bin/make
######################################
# configuration: change things here. #
######################################
PROGRAMS?=@programs@
SkywaysGlut_BINARY=skyways.glut
SkywaysQt_BINARY=skyways.qt
SkywaysSdl_BINARY=skyways.sdl
Common_HEADERS= \
src/configuration.hpp \
src/controller.hpp \
src/display/shader.hpp \
src/display/textprinter.hpp \
src/display/uniform.hpp \
src/game.hpp \
src/loading/blockloader.hpp \
src/loading/mapgenerator.hpp \
src/loading/maploader.hpp \
src/loading/objmodel.hpp \
src/range.hpp \
src/vector.hpp \
src/world/aabb.hpp \
src/world/block.hpp \
src/world/collisionaccelerator.hpp \
src/world/element.hpp \
src/world/map.hpp \
src/world/model.hpp \
src/world/ship.hpp \
#
SkywaysGlut_HEADERS= $(Common_HEADERS) \
src/backends/configparser.hpp \
#
SkywaysQt_HEADERS= $(Common_HEADERS) \
src/backends/qtconfigparser.hpp \
src/backends/qtwindow.hpp \
#
SkywaysSdl_HEADERS= $(Common_HEADERS) \
src/backends/configparser.hpp \
#
Common_CXXSOURCES= \
src/configuration.cpp \
src/controller.cpp \
src/display/shader.cpp \
src/display/textprinter.cpp \
src/game.cpp \
src/loading/blockloader.cpp \
src/loading/mapgenerator.cpp \
src/loading/maploader.cpp \
src/loading/objmodel.cpp \
src/world/block.cpp \
src/world/collisionaccelerator.cpp \
src/world/element.cpp \
src/world/map.cpp \
src/world/ship.cpp \
#
SkywaysGlut_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/configparser.cpp \
src/backends/glutmain.cpp \
#
SkywaysQt_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/moc_qtwindow.cpp \
src/backends/qtconfigparser.cpp \
src/backends/qtmain.cpp \
src/backends/qtwindow.cpp \
#
SkywaysSdl_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/configparser.cpp \
src/backends/sdlmain.cpp \
#
-CPPFLAGS:= -O2 -g -Wall -I/usr/include/FTGL -I/usr/include/freetype2 $(CPPFLAGS) -Isrc
-LDFLAGS:= -lGL -lboost_filesystem -lftgl -lGLEW $(LDFLAGS)
-
-SkywaysGlut_LDFLAGS=-lglut -lboost_program_options
-SkywaysQt_LDFLAGS=-lQtOpenGL -lQtGui -lQtCore -lGLU -lGL -lpthread
-SkywaysQt_CPPFLAGS=-D_REENTRANT -DQT_NO_DEBUG -DQT_OPENGL_LIB -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED -I/usr/include/qt4/QtCore -I/usr/include/qt4/QtGui -I/usr/include/qt4/QtOpenGL -I/usr/include/qt4
-SkywaysSdl_LDFLAGS=-lSDL -lboost_program_options
-SkywaysSdl_CPPFLAGS=-I/usr/include/SDL
+CPPFLAGS:= @CFLAGS@ -Wall @FTGL_CFLAGS@ $(CPPFLAGS) -Isrc
+LDFLAGS:= @LIBS@ -lboost_filesystem @FTGL_LIBS@ $(LDFLAGS)
+
+SkywaysGlut_LDFLAGS=@GLUT_LIBS@ -lboost_program_options
+SkywaysQt_LDFLAGS=@QT_LIBS@
+SkywaysQt_CPPFLAGS=-D_REENTRANT -DQT_NO_DEBUG -DQT_OPENGL_LIB -DQT_GUI_LIB -DQT_CORE_LIB @QT_CFLAGS@
+SkywaysSdl_LDFLAGS=@SDL_LIBS@ -lboost_program_options
+SkywaysSdl_CPPFLAGS=@SDL_CFLAGS@
EXTRADIST=
######################################
# auto-configuration: do not change! #
######################################
CWD:=$(shell pwd)
default: all
$(foreach prog,$(PROGRAMS),$(eval $(prog)_SOURCES=$($(prog)_CSOURCES) $($(prog)_CXXSOURCES)))
$(foreach prog,$(PROGRAMS),$(eval $(prog)_OBJECTS=$(patsubst %.c,%_$(prog).o,$($(prog)_CSOURCES)) $(patsubst %.cpp,%_$(prog).o,$($(prog)_CXXSOURCES))))
$(foreach flag,CFLAGS CPPFLAGS CXXFLAGS LDFLAGS,$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_$(flag)=$($(flag)) $($(prog)_$(flag)))))
OBJECTS=$(foreach prog,$(PROGRAMS),$($(prog)_OBJECTS))
BINARIES=$(foreach prog,$(PROGRAMS),$($(prog)_BINARY))
DEPENDS=$(patsubst %.o,%.d,$(OBJECTS))
define CDEP_template
%_$(1).d: %.c $$($(1)_HEADERS)
@set -e; rm -f "$$@" || true; \
$$(CC) -MM -MQ "`echo "$$@" | sed 's/\.d$$$$/.o'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) "$$<" > $$@
@echo -n .
endef
define CXXDEP_template
%_$(1).d: %.cpp $$($(1)_HEADERS)
@set -e; rm -f "$$@" || true; \
$$(CXX) -MM -MQ "`echo "$$<" | sed 's,\($$*\)\.cpp,\1_$(1).o,'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) "$$<" > $$@
@echo -n .
endef
define CSRC_template
%_$(1).o: %.c
$$(CC) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) $$< -o $$@
endef
define CXXSRC_template
%_$(1).o: %.cpp
$$(CXX) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) $$< -o $$@
endef
define BINARY_template
$$($(1)_BINARY): $$($(1)_OBJECTS)
$$(CC) $$($(1)_ALL_LDFLAGS) $$^ $$(LOADLIBS) $$(LDLIBS) -o $$@
endef
$(foreach template,CDEP CXXDEP CSRC CXXSRC BINARY,$(foreach prog,$(PROGRAMS),$(eval $(call $(template)_template,$(prog)))))
all: $(BINARIES)
# this rule is just to add a newline after the dots from deps calculation
Makefile: $(DEPENDS)
@echo
@touch $@
#################################
# extra stuff: change as needed #
#################################
clean:
rm -f $(OBJECTS) $(BINARIES) $(DEPENDS) $(DISTFILES) || true
moc_%.cpp: %.hpp
moc-qt4 $(SkywaysQt_CPPFLAGS) $(SkywaysQt_CXXFLAGS) $< -o $@
.PHONY: default clean
-include $(DEPENDS)
diff --git a/configure.ac b/configure.ac
index cd42a41..e2eed54 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,97 +1,101 @@
# -*- Autoconf -*-
# vim: ft=m4
# Process this file with autoconf to produce a configure script.
AC_PREREQ([2.63])
AC_INIT([FULL-PACKAGE-NAME], [VERSION], [BUG-REPORT-ADDRESS])
AC_CONFIG_MACRO_DIR([m4])
AC_CONFIG_SRCDIR([src/configuration.hpp])
AC_CONFIG_HEADERS([config.h])
# Checks for programs.
AC_PROG_CXX
PKG_PROG_PKG_CONFIG
# Checks for libraries.
AC_CHECK_LIB([GL], [glGetString])
AC_CHECK_LIB([GLEW], [glewInit])
-AC_CHECK_LIB([GLU], [gluGetString])
PKG_CHECK_MODULES([FTGL],[ftgl >= 2.1])
dnl FIXME: check for boost
dnl AC_CHECK_LIB([boost_filesystem], [main])
dnl AC_CHECK_LIB([boost_program_options], [main])
programs=""
AC_ARG_ENABLE([qt], AS_HELP_STRING([--enable-qt], [Enable Qt backend (default: test)]),
[ if test "x$enableval" = "xyes" ; then qt_backend=yes
elif test "x$enableval" = "xtest" ; then qt_backend=test
elif test "x$enableval" = "xno" ; then qt_backend=no
else echo "Error: unknown --enable-qt option $enableval" ; exit 1
fi
],
[ qt_backend=test
])
if test "x$qt_backend" == "xyes" ; then
- PKG_CHECK_MODULES([Qt],[QtCore >= 4.5.0 QtGui >= 4.5.0 QtOpenGL >= 4.5.0])
- AC_CHECK_LIB([pthread],[pthread_create])
+ PKG_CHECK_MODULES([QT],[QtCore >= 4.5.0 QtGui >= 4.5.0 QtOpenGL >= 4.5.0])
+ AC_CHECK_LIB([pthread],[pthread_create],[QT_LIBS="-lpthread $QT_LIBS"])
+ AC_CHECK_LIB([GLU], [gluGetString],[QT_LIBS="-lGLU $QT_LIBS"])
elif test "x$qt_backend" == "xtest" ; then
- PKG_CHECK_MODULES([Qt],[QtCore >= 4.5.0 QtGui >= 4.5.0 QtOpenGL >= 4.5.0],[qt_backend="yes"],[qt_backend="no"])
+ PKG_CHECK_MODULES([QT],[QtCore >= 4.5.0 QtGui >= 4.5.0 QtOpenGL >= 4.5.0],[qt_backend="yes"],[qt_backend="no"])
if test "x$qt_backend" = "xyes" ; then
- AC_CHECK_LIB([pthread],[pthread_create],[qt_backend="yes"],[qt_backend="no"])
+ AC_CHECK_LIB([pthread],[pthread_create],[QT_LIBS="-lpthread $QT_LIBS"; qt_backend="yes"],[qt_backend="no"])
+ fi
+ if test "x$qt_backend" = "xyes" ; then
+ AC_CHECK_LIB([GLU], [gluGetString],[QT_LIBS="-lGLU $QT_LIBS"; qt_backend="yes"],[qt_backend="no"])
fi
fi
AC_SUBST(qt_backend)
if test "x$qt_backend" = "xyes" ; then
programs="SkywaysQt $programs"
fi
AC_ARG_ENABLE([sdl], AS_HELP_STRING([--enable-sdl], [Enable SDL backend (default: test)]),
[ if test "x$enableval" = "xyes" ; then sdl_backend=yes
elif test "x$enableval" = "xtest" ; then sdl_backend=test
elif test "x$enableval" = "xno" ; then sdl_backend=no
else echo "Error: unknown --enable-sdl option $enableval" ; exit 1
fi
],
[ sdl_backend=test
])
if test "x$sdl_backend" == "xyes" ; then
PKG_CHECK_MODULES([SDL],[sdl >= 1.2.13])
elif test "x$sdl_backend" == "xtest" ; then
PKG_CHECK_MODULES([SDL],[sdl >= 1.2.13],[sdl_backend="yes"],[sdl_backend="no"])
fi
AC_SUBST(sdl_backend)
if test "x$sdl_backend" = "xyes" ; then
programs="SkywaysSdl $programs"
fi
AC_ARG_ENABLE([glut], AS_HELP_STRING([--enable-glut], [Enable GLUT backend (default: test)]),
[ if test "x$enableval" = "xyes" ; then glut_backend=yes
elif test "x$enableval" = "xtest" ; then glut_backend=test
elif test "x$enableval" = "xno" ; then glut_backend=no
else echo "Error: unknown --enable-glut option $enableval" ; exit 1
fi
],
[ glut_backend=test
])
if test "x$glut_backend" == "xyes" ; then
- AC_CHECK_LIB([glut],[glutMainLoop])
+ AC_CHECK_LIB([glut],[glutMainLoop],[GLUT_LIBS="-lglut"])
elif test "x$glut_backend" == "xtest" ; then
- AC_CHECK_LIB([glut],[glutMainLoop],[glut_backend="yes"],[glut_backend="no"])
+ AC_CHECK_LIB([glut],[glutMainLoop],[GLUT_LIBS="-lglut"; glut_backend="yes"],[glut_backend="no"])
fi
AC_SUBST(glut_backend)
+AC_SUBST(GLUT_LIBS)
if test "x$glut_backend" = "xyes" ; then
programs="SkywaysGlut $programs"
fi
AC_SUBST(programs)
# Checks for header files.
# Checks for typedefs, structures, and compiler characteristics.
# Checks for library functions.
AC_CONFIG_FILES([Makefile])
AC_OUTPUT
|
devnev/skyways
|
afb8d0935ce65807f0df7c635cd29d00eafbb463
|
Changed build to use autoconf.
|
diff --git a/Makefile b/Makefile.in
similarity index 99%
rename from Makefile
rename to Makefile.in
index c849b74..a2f7db7 100644
--- a/Makefile
+++ b/Makefile.in
@@ -1,158 +1,158 @@
#!/usr/bin/make
######################################
# configuration: change things here. #
######################################
-PROGRAMS=SkywaysGlut SkywaysQt SkywaysSdl
+PROGRAMS?=@programs@
SkywaysGlut_BINARY=skyways.glut
SkywaysQt_BINARY=skyways.qt
SkywaysSdl_BINARY=skyways.sdl
Common_HEADERS= \
src/configuration.hpp \
src/controller.hpp \
src/display/shader.hpp \
src/display/textprinter.hpp \
src/display/uniform.hpp \
src/game.hpp \
src/loading/blockloader.hpp \
src/loading/mapgenerator.hpp \
src/loading/maploader.hpp \
src/loading/objmodel.hpp \
src/range.hpp \
src/vector.hpp \
src/world/aabb.hpp \
src/world/block.hpp \
src/world/collisionaccelerator.hpp \
src/world/element.hpp \
src/world/map.hpp \
src/world/model.hpp \
src/world/ship.hpp \
#
SkywaysGlut_HEADERS= $(Common_HEADERS) \
src/backends/configparser.hpp \
#
SkywaysQt_HEADERS= $(Common_HEADERS) \
src/backends/qtconfigparser.hpp \
src/backends/qtwindow.hpp \
#
SkywaysSdl_HEADERS= $(Common_HEADERS) \
src/backends/configparser.hpp \
#
Common_CXXSOURCES= \
src/configuration.cpp \
src/controller.cpp \
src/display/shader.cpp \
src/display/textprinter.cpp \
src/game.cpp \
src/loading/blockloader.cpp \
src/loading/mapgenerator.cpp \
src/loading/maploader.cpp \
src/loading/objmodel.cpp \
src/world/block.cpp \
src/world/collisionaccelerator.cpp \
src/world/element.cpp \
src/world/map.cpp \
src/world/ship.cpp \
#
SkywaysGlut_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/configparser.cpp \
src/backends/glutmain.cpp \
#
SkywaysQt_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/moc_qtwindow.cpp \
src/backends/qtconfigparser.cpp \
src/backends/qtmain.cpp \
src/backends/qtwindow.cpp \
#
SkywaysSdl_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/configparser.cpp \
src/backends/sdlmain.cpp \
#
CPPFLAGS:= -O2 -g -Wall -I/usr/include/FTGL -I/usr/include/freetype2 $(CPPFLAGS) -Isrc
LDFLAGS:= -lGL -lboost_filesystem -lftgl -lGLEW $(LDFLAGS)
SkywaysGlut_LDFLAGS=-lglut -lboost_program_options
SkywaysQt_LDFLAGS=-lQtOpenGL -lQtGui -lQtCore -lGLU -lGL -lpthread
SkywaysQt_CPPFLAGS=-D_REENTRANT -DQT_NO_DEBUG -DQT_OPENGL_LIB -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED -I/usr/include/qt4/QtCore -I/usr/include/qt4/QtGui -I/usr/include/qt4/QtOpenGL -I/usr/include/qt4
SkywaysSdl_LDFLAGS=-lSDL -lboost_program_options
SkywaysSdl_CPPFLAGS=-I/usr/include/SDL
EXTRADIST=
######################################
# auto-configuration: do not change! #
######################################
CWD:=$(shell pwd)
default: all
$(foreach prog,$(PROGRAMS),$(eval $(prog)_SOURCES=$($(prog)_CSOURCES) $($(prog)_CXXSOURCES)))
$(foreach prog,$(PROGRAMS),$(eval $(prog)_OBJECTS=$(patsubst %.c,%_$(prog).o,$($(prog)_CSOURCES)) $(patsubst %.cpp,%_$(prog).o,$($(prog)_CXXSOURCES))))
$(foreach flag,CFLAGS CPPFLAGS CXXFLAGS LDFLAGS,$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_$(flag)=$($(flag)) $($(prog)_$(flag)))))
OBJECTS=$(foreach prog,$(PROGRAMS),$($(prog)_OBJECTS))
BINARIES=$(foreach prog,$(PROGRAMS),$($(prog)_BINARY))
DEPENDS=$(patsubst %.o,%.d,$(OBJECTS))
define CDEP_template
%_$(1).d: %.c $$($(1)_HEADERS)
@set -e; rm -f "$$@" || true; \
$$(CC) -MM -MQ "`echo "$$@" | sed 's/\.d$$$$/.o'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) "$$<" > $$@
@echo -n .
endef
define CXXDEP_template
%_$(1).d: %.cpp $$($(1)_HEADERS)
@set -e; rm -f "$$@" || true; \
$$(CXX) -MM -MQ "`echo "$$<" | sed 's,\($$*\)\.cpp,\1_$(1).o,'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) "$$<" > $$@
@echo -n .
endef
define CSRC_template
%_$(1).o: %.c
$$(CC) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) $$< -o $$@
endef
define CXXSRC_template
%_$(1).o: %.cpp
$$(CXX) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) $$< -o $$@
endef
define BINARY_template
$$($(1)_BINARY): $$($(1)_OBJECTS)
$$(CC) $$($(1)_ALL_LDFLAGS) $$^ $$(LOADLIBS) $$(LDLIBS) -o $$@
endef
$(foreach template,CDEP CXXDEP CSRC CXXSRC BINARY,$(foreach prog,$(PROGRAMS),$(eval $(call $(template)_template,$(prog)))))
all: $(BINARIES)
# this rule is just to add a newline after the dots from deps calculation
Makefile: $(DEPENDS)
@echo
@touch $@
#################################
# extra stuff: change as needed #
#################################
clean:
rm -f $(OBJECTS) $(BINARIES) $(DEPENDS) $(DISTFILES) || true
moc_%.cpp: %.hpp
moc-qt4 $(SkywaysQt_CPPFLAGS) $(SkywaysQt_CXXFLAGS) $< -o $@
.PHONY: default clean
-include $(DEPENDS)
diff --git a/configure.ac b/configure.ac
new file mode 100644
index 0000000..cd42a41
--- /dev/null
+++ b/configure.ac
@@ -0,0 +1,97 @@
+# -*- Autoconf -*-
+# vim: ft=m4
+# Process this file with autoconf to produce a configure script.
+
+AC_PREREQ([2.63])
+AC_INIT([FULL-PACKAGE-NAME], [VERSION], [BUG-REPORT-ADDRESS])
+AC_CONFIG_MACRO_DIR([m4])
+AC_CONFIG_SRCDIR([src/configuration.hpp])
+AC_CONFIG_HEADERS([config.h])
+
+# Checks for programs.
+AC_PROG_CXX
+PKG_PROG_PKG_CONFIG
+
+# Checks for libraries.
+
+AC_CHECK_LIB([GL], [glGetString])
+AC_CHECK_LIB([GLEW], [glewInit])
+AC_CHECK_LIB([GLU], [gluGetString])
+PKG_CHECK_MODULES([FTGL],[ftgl >= 2.1])
+dnl FIXME: check for boost
+dnl AC_CHECK_LIB([boost_filesystem], [main])
+dnl AC_CHECK_LIB([boost_program_options], [main])
+
+programs=""
+
+AC_ARG_ENABLE([qt], AS_HELP_STRING([--enable-qt], [Enable Qt backend (default: test)]),
+ [ if test "x$enableval" = "xyes" ; then qt_backend=yes
+ elif test "x$enableval" = "xtest" ; then qt_backend=test
+ elif test "x$enableval" = "xno" ; then qt_backend=no
+ else echo "Error: unknown --enable-qt option $enableval" ; exit 1
+ fi
+ ],
+ [ qt_backend=test
+ ])
+if test "x$qt_backend" == "xyes" ; then
+ PKG_CHECK_MODULES([Qt],[QtCore >= 4.5.0 QtGui >= 4.5.0 QtOpenGL >= 4.5.0])
+ AC_CHECK_LIB([pthread],[pthread_create])
+elif test "x$qt_backend" == "xtest" ; then
+ PKG_CHECK_MODULES([Qt],[QtCore >= 4.5.0 QtGui >= 4.5.0 QtOpenGL >= 4.5.0],[qt_backend="yes"],[qt_backend="no"])
+ if test "x$qt_backend" = "xyes" ; then
+ AC_CHECK_LIB([pthread],[pthread_create],[qt_backend="yes"],[qt_backend="no"])
+ fi
+fi
+AC_SUBST(qt_backend)
+if test "x$qt_backend" = "xyes" ; then
+ programs="SkywaysQt $programs"
+fi
+
+AC_ARG_ENABLE([sdl], AS_HELP_STRING([--enable-sdl], [Enable SDL backend (default: test)]),
+ [ if test "x$enableval" = "xyes" ; then sdl_backend=yes
+ elif test "x$enableval" = "xtest" ; then sdl_backend=test
+ elif test "x$enableval" = "xno" ; then sdl_backend=no
+ else echo "Error: unknown --enable-sdl option $enableval" ; exit 1
+ fi
+ ],
+ [ sdl_backend=test
+ ])
+if test "x$sdl_backend" == "xyes" ; then
+ PKG_CHECK_MODULES([SDL],[sdl >= 1.2.13])
+elif test "x$sdl_backend" == "xtest" ; then
+ PKG_CHECK_MODULES([SDL],[sdl >= 1.2.13],[sdl_backend="yes"],[sdl_backend="no"])
+fi
+AC_SUBST(sdl_backend)
+if test "x$sdl_backend" = "xyes" ; then
+ programs="SkywaysSdl $programs"
+fi
+
+AC_ARG_ENABLE([glut], AS_HELP_STRING([--enable-glut], [Enable GLUT backend (default: test)]),
+ [ if test "x$enableval" = "xyes" ; then glut_backend=yes
+ elif test "x$enableval" = "xtest" ; then glut_backend=test
+ elif test "x$enableval" = "xno" ; then glut_backend=no
+ else echo "Error: unknown --enable-glut option $enableval" ; exit 1
+ fi
+ ],
+ [ glut_backend=test
+ ])
+if test "x$glut_backend" == "xyes" ; then
+ AC_CHECK_LIB([glut],[glutMainLoop])
+elif test "x$glut_backend" == "xtest" ; then
+ AC_CHECK_LIB([glut],[glutMainLoop],[glut_backend="yes"],[glut_backend="no"])
+fi
+AC_SUBST(glut_backend)
+if test "x$glut_backend" = "xyes" ; then
+ programs="SkywaysGlut $programs"
+fi
+
+AC_SUBST(programs)
+
+# Checks for header files.
+
+# Checks for typedefs, structures, and compiler characteristics.
+
+# Checks for library functions.
+
+AC_CONFIG_FILES([Makefile])
+AC_OUTPUT
|
devnev/skyways
|
bff939fa6a7647b1e3963414dfefb062c70643ca
|
Improved Makefile.
|
diff --git a/Makefile b/Makefile
index a3e1e66..c849b74 100644
--- a/Makefile
+++ b/Makefile
@@ -1,157 +1,158 @@
#!/usr/bin/make
######################################
# configuration: change things here. #
######################################
PROGRAMS=SkywaysGlut SkywaysQt SkywaysSdl
SkywaysGlut_BINARY=skyways.glut
SkywaysQt_BINARY=skyways.qt
SkywaysSdl_BINARY=skyways.sdl
-HEADERS= \
+Common_HEADERS= \
src/configuration.hpp \
src/controller.hpp \
src/display/shader.hpp \
src/display/textprinter.hpp \
src/display/uniform.hpp \
src/game.hpp \
src/loading/blockloader.hpp \
src/loading/mapgenerator.hpp \
src/loading/maploader.hpp \
src/loading/objmodel.hpp \
src/range.hpp \
src/vector.hpp \
src/world/aabb.hpp \
src/world/block.hpp \
src/world/collisionaccelerator.hpp \
src/world/element.hpp \
src/world/map.hpp \
src/world/model.hpp \
src/world/ship.hpp \
#
-SkywasyGlut_HEADERS= $(HEADERS) \
+SkywaysGlut_HEADERS= $(Common_HEADERS) \
src/backends/configparser.hpp \
#
-SkywasyQt_HEADERS= $(HEADERS) \
+SkywaysQt_HEADERS= $(Common_HEADERS) \
src/backends/qtconfigparser.hpp \
src/backends/qtwindow.hpp \
#
-SkywaysSdl_HEADERS= $(HEADERS) \
+SkywaysSdl_HEADERS= $(Common_HEADERS) \
src/backends/configparser.hpp \
#
-CXXSOURCES= \
+Common_CXXSOURCES= \
src/configuration.cpp \
src/controller.cpp \
src/display/shader.cpp \
src/display/textprinter.cpp \
src/game.cpp \
src/loading/blockloader.cpp \
src/loading/mapgenerator.cpp \
src/loading/maploader.cpp \
src/loading/objmodel.cpp \
src/world/block.cpp \
src/world/collisionaccelerator.cpp \
src/world/element.cpp \
src/world/map.cpp \
src/world/ship.cpp \
#
-SkywaysGlut_CXXSOURCES= $(CXXSOURCES) \
+SkywaysGlut_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/configparser.cpp \
src/backends/glutmain.cpp \
#
-SkywaysQt_CXXSOURCES= $(CXXSOURCES) \
+SkywaysQt_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/moc_qtwindow.cpp \
src/backends/qtconfigparser.cpp \
src/backends/qtmain.cpp \
src/backends/qtwindow.cpp \
#
-SkywaysSdl_CXXSOURCES= $(CXXSOURCES) \
+SkywaysSdl_CXXSOURCES= $(Common_CXXSOURCES) \
src/backends/configparser.cpp \
src/backends/sdlmain.cpp \
#
CPPFLAGS:= -O2 -g -Wall -I/usr/include/FTGL -I/usr/include/freetype2 $(CPPFLAGS) -Isrc
LDFLAGS:= -lGL -lboost_filesystem -lftgl -lGLEW $(LDFLAGS)
SkywaysGlut_LDFLAGS=-lglut -lboost_program_options
SkywaysQt_LDFLAGS=-lQtOpenGL -lQtGui -lQtCore -lGLU -lGL -lpthread
SkywaysQt_CPPFLAGS=-D_REENTRANT -DQT_NO_DEBUG -DQT_OPENGL_LIB -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED -I/usr/include/qt4/QtCore -I/usr/include/qt4/QtGui -I/usr/include/qt4/QtOpenGL -I/usr/include/qt4
SkywaysSdl_LDFLAGS=-lSDL -lboost_program_options
SkywaysSdl_CPPFLAGS=-I/usr/include/SDL
EXTRADIST=
######################################
# auto-configuration: do not change! #
######################################
CWD:=$(shell pwd)
default: all
$(foreach prog,$(PROGRAMS),$(eval $(prog)_SOURCES=$($(prog)_CSOURCES) $($(prog)_CXXSOURCES)))
$(foreach prog,$(PROGRAMS),$(eval $(prog)_OBJECTS=$(patsubst %.c,%_$(prog).o,$($(prog)_CSOURCES)) $(patsubst %.cpp,%_$(prog).o,$($(prog)_CXXSOURCES))))
$(foreach flag,CFLAGS CPPFLAGS CXXFLAGS LDFLAGS,$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_$(flag)=$($(flag)) $($(prog)_$(flag)))))
-#CSOURCES=$(foreach prog,$(PROGRAMS),$($(prog)_CSOURCES))
-#CXXSOURCES=$(foreach prog,$(PROGRAMS),$($(prog)_CXXSOURCES))
-#SOURCES=$(CSOURCES) $(CXXSOURCES)
-#HEADERS=$(foreach prog,$(PROGRAMS),$($(prog)_HEADERS))
OBJECTS=$(foreach prog,$(PROGRAMS),$($(prog)_OBJECTS))
BINARIES=$(foreach prog,$(PROGRAMS),$($(prog)_BINARY))
DEPENDS=$(patsubst %.o,%.d,$(OBJECTS))
define CDEP_template
- %_$(1).d: %.c
- set -e; rm -f "$$@" || true; \
- $$(CC) -MM -MQ "`echo "$$<" | sed 's,\($$*\)\.c,\1_$(1).o,'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) "$$<" | \
- sed 's,\($$*_$(1)\).o *:,\1.o $$@:,' >$$@
+ %_$(1).d: %.c $$($(1)_HEADERS)
+ @set -e; rm -f "$$@" || true; \
+ $$(CC) -MM -MQ "`echo "$$@" | sed 's/\.d$$$$/.o'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) "$$<" > $$@
+ @echo -n .
endef
define CXXDEP_template
- %_$(1).d: %.cpp
- set -e; rm -f "$$@" || true; \
- $$(CXX) -MM -MQ "`echo "$$<" | sed 's,\($$*\)\.cpp,\1_$(1).o,'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) "$$<" | \
- sed 's,\($$*_$(1)\).o *:,\1.o $$@:,' >$$@
+ %_$(1).d: %.cpp $$($(1)_HEADERS)
+ @set -e; rm -f "$$@" || true; \
+ $$(CXX) -MM -MQ "`echo "$$<" | sed 's,\($$*\)\.cpp,\1_$(1).o,'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) "$$<" > $$@
+ @echo -n .
endef
define CSRC_template
%_$(1).o: %.c
$$(CC) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) $$< -o $$@
endef
define CXXSRC_template
%_$(1).o: %.cpp
$$(CXX) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) $$< -o $$@
endef
define BINARY_template
$$($(1)_BINARY): $$($(1)_OBJECTS)
$$(CC) $$($(1)_ALL_LDFLAGS) $$^ $$(LOADLIBS) $$(LDLIBS) -o $$@
endef
$(foreach template,CDEP CXXDEP CSRC CXXSRC BINARY,$(foreach prog,$(PROGRAMS),$(eval $(call $(template)_template,$(prog)))))
all: $(BINARIES)
+# this rule is just to add a newline after the dots from deps calculation
+Makefile: $(DEPENDS)
+ @echo
+ @touch $@
+
#################################
# extra stuff: change as needed #
#################################
clean:
- rm $(OBJECTS) $(BINARIES) $(DEPENDS) $(DISTFILES) || true
+ rm -f $(OBJECTS) $(BINARIES) $(DEPENDS) $(DISTFILES) || true
moc_%.cpp: %.hpp
moc-qt4 $(SkywaysQt_CPPFLAGS) $(SkywaysQt_CXXFLAGS) $< -o $@
.PHONY: default clean
-include $(DEPENDS)
|
devnev/skyways
|
1117cafe2587b2eefc1da5b9d5d2249c21caecfd
|
Added forgotten random seeding.
|
diff --git a/src/controller.cpp b/src/controller.cpp
index fb6e7cc..d47890e 100644
--- a/src/controller.cpp
+++ b/src/controller.cpp
@@ -1,211 +1,212 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <GL/glew.h>
#include <GL/gl.h>
#include <boost/format.hpp>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <display/textprinter.hpp>
#include <display/shader.hpp>
#include <loading/maploader.hpp>
#include <loading/mapgenerator.hpp>
#include <loading/blockloader.hpp>
#include "controller.hpp"
Controller::Controller(
std::auto_ptr< Game > game
, double cameraheight, double cameradistance, double camerarotation
, Controller::QuitCallback cbQuit
, std::auto_ptr< TextPrinter > printer
)
: _game( game )
, _camy( cameraheight ), _camz( cameradistance ), _camrot( camerarotation )
, _quitcb( cbQuit ), _printer( printer )
, _windowwidth( 1 ), _windowheight( 1 )
{
+ srand(time(0));
}
Controller::~Controller()
{
}
void Controller::keydown( int key )
{
switch ( key )
{
case STRAFE_L_KEY: _game->setStrafe( -1 ); break;
case STRAFE_R_KEY: _game->setStrafe( 1 ); break;
case ACCEL_KEY: _game->setAcceleration( 1 ); break;
case DECEL_KEY: _game->setAcceleration( -1 ); break;
case JUMP_KEY: _game->startJump(); break;
case QUIT_KEY:
if ( _game->dead() )
{
_quitcb();
}
else
{
_game->suicide();
}
break;
}
}
void Controller::keyup( int key )
{
switch ( key )
{
case STRAFE_L_KEY:
_game->setStrafe( 0 );
break;
case STRAFE_R_KEY:
_game->setStrafe( 0 );
break;
case ACCEL_KEY:
_game->setAcceleration( 0 );
break;
case DECEL_KEY:
_game->setAcceleration( 0 );
break;
}
}
void Controller::loadBlocks()
{
BlockLoader bl;
boost::ptr_map< std::string, Block > blocks;
bl.loadDirectory( "blocks", blocks );
_game->addBlocks( blocks );
}
void Controller::loadMap( std::string filename )
{
loadBlocks();
MapLoader ml( &_game->getBlocks() );
std::ifstream mapFile( filename.c_str() );
MapInfo mapinfo;
ml.loadMap( mapFile, mapinfo );
_game->setMap( mapinfo.map );
_game->setPos( mapinfo.startPos );
}
void Controller::generateMap()
{
loadBlocks();
MapGenerator mg( &_game->getBlocks() );
MapInfo mapinfo;
mg.generate( mapinfo );
_game->setMap( mapinfo.map );
_game->setPos( mapinfo.startPos );
}
void Controller::initialize()
{
GLenum err = glewInit();
if (err != GLEW_OK)
throw std::runtime_error((const char*)glewGetErrorString(err));
if (!GLEW_VERSION_2_0)
throw std::runtime_error("Nead OpenGL >= 2.0 for shaders. Update your graphics drivers!");
_shaderProgram = createShaderProgram("shaders/shader.glslv", "shaders/shader.glslf");
_game->setShader( *_shaderProgram );
glClearColor( 0.2, 0.2, 0.2, 0 );
glClearDepth( 1.0 );
glDepthFunc( GL_LEQUAL );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
glEnable( GL_LINE_SMOOTH );
glHint( GL_LINE_SMOOTH_HINT, GL_NICEST );
}
void Controller::resize( int width, int height )
{
glViewport( 0, 0, width, height );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
double fH = tan( 30.0 / 180.0 * 3.14159265358979323846 );
double fW = ( (double)width ) / ( (double)height ) * fH;
glFrustum( -fW, fW, -fH, fH, 1.0, 1000.0 );
glMatrixMode( GL_MODELVIEW );
_windowwidth = width;
_windowheight = height;
}
void Controller::draw()
{
glClear( GL_DEPTH_BUFFER_BIT );
// draw gradient background
glMatrixMode( GL_PROJECTION );
glPushMatrix();
glLoadIdentity();
glOrtho( 0, 1, 1, 0, -1, 1 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glDisable( GL_DEPTH_TEST );
glDisable( GL_BLEND );
glBegin( GL_QUADS );
glColor3f(0.1, 0.1, 0.1);
glVertex2f(0, 0);
glColor3f(0.15, 0.05, 0);
glVertex2f(0, 1);
glColor3f(0.15, 0.05, 0);
glVertex2f(1, 1);
glColor3f(0.1, 0.1, 0.1);
glVertex2f(1, 0);
glEnd();
glMatrixMode( GL_PROJECTION );
glPopMatrix();
glMatrixMode( GL_MODELVIEW );
glEnable( GL_DEPTH_TEST );
glEnable( GL_CULL_FACE );
glEnable( GL_BLEND );
glLoadIdentity();
glRotatef( _camrot, 1, 0, 0 );
glTranslated( 0.0, -_camy, -_camz );
_game->draw( _camz );
if ( _game->dead() )
{
glUseProgram(0);
_printer->print(
( boost::format( "%1% Distance Traveled: %2%" )
% _game->deathCause()
% _game->distanceTraveled() ).str(),
_windowwidth / 2, _windowheight / 4 * 3,
TextPrinter::ALIGN_CENTER
);
}
}
void Controller::update( int difference )
{
if ( _game->dead() )
return;
_game->update( difference );
}
|
devnev/skyways
|
99c19f987559bb29d6f4fc5b6ba180f5c4354052
|
Fixed gitignore for qt moc output.
|
diff --git a/.gitignore b/.gitignore
index 1cc84c3..616b08a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,6 +1,6 @@
*.o
*.d
skyways.glut
skyways.qt
skyways.sdl
-src/moc_qtwindow.cpp
+moc_*.cpp
|
devnev/skyways
|
08f616aaa6efdd81b5c0b7f64b4f6859d62d192d
|
Restructured src directory.
|
diff --git a/Makefile b/Makefile
index f1194e9..a3e1e66 100644
--- a/Makefile
+++ b/Makefile
@@ -1,161 +1,157 @@
-
-###########################
-# prelude: do not change! #
-###########################
-
-CWD:=$(shell pwd)
-
-default: all
-
-BUILDFLAGS=CFLAGS CPPFLAGS CXXFLAGS LDFLAGS
-
-define FLAGINIT_template
- ifndef $(1)
- $(1)=
- endif
-endef
-
-$(foreach flag,$(BUILDFLAGS),$(eval $(call FLAGINIT_template,$(flag))))
-
+#!/usr/bin/make
######################################
# configuration: change things here. #
######################################
PROGRAMS=SkywaysGlut SkywaysQt SkywaysSdl
SkywaysGlut_BINARY=skyways.glut
SkywaysQt_BINARY=skyways.qt
SkywaysSdl_BINARY=skyways.sdl
HEADERS= \
- src/aabb.hpp \
- src/block.hpp \
- src/blockloader.hpp \
- src/collisionaccelerator.hpp \
src/configuration.hpp \
src/controller.hpp \
- src/element.hpp \
- src/map.hpp \
- src/mapgenerator.hpp \
- src/maploader.hpp \
- src/model.hpp \
- src/objmodel.hpp \
- src/shader.hpp \
- src/ship.hpp \
- src/textprinter.hpp \
+ src/display/shader.hpp \
+ src/display/textprinter.hpp \
+ src/display/uniform.hpp \
+ src/game.hpp \
+ src/loading/blockloader.hpp \
+ src/loading/mapgenerator.hpp \
+ src/loading/maploader.hpp \
+ src/loading/objmodel.hpp \
+ src/range.hpp \
src/vector.hpp \
- src/game.hpp
+ src/world/aabb.hpp \
+ src/world/block.hpp \
+ src/world/collisionaccelerator.hpp \
+ src/world/element.hpp \
+ src/world/map.hpp \
+ src/world/model.hpp \
+ src/world/ship.hpp \
+ #
SkywasyGlut_HEADERS= $(HEADERS) \
- src/configparser.hpp
+ src/backends/configparser.hpp \
+ #
SkywasyQt_HEADERS= $(HEADERS) \
- src/qtconfigparser.hpp \
- src/qtwindow.hpp
+ src/backends/qtconfigparser.hpp \
+ src/backends/qtwindow.hpp \
+ #
SkywaysSdl_HEADERS= $(HEADERS) \
- src/configparser.hpp
+ src/backends/configparser.hpp \
+ #
CXXSOURCES= \
- src/block.cpp \
- src/blockloader.cpp \
- src/collisionaccelerator.cpp \
src/configuration.cpp \
src/controller.cpp \
- src/element.cpp \
- src/map.cpp \
- src/mapgenerator.cpp \
- src/maploader.cpp \
- src/objmodel.cpp \
- src/shader.cpp \
- src/ship.cpp \
- src/textprinter.cpp \
- src/game.cpp
+ src/display/shader.cpp \
+ src/display/textprinter.cpp \
+ src/game.cpp \
+ src/loading/blockloader.cpp \
+ src/loading/mapgenerator.cpp \
+ src/loading/maploader.cpp \
+ src/loading/objmodel.cpp \
+ src/world/block.cpp \
+ src/world/collisionaccelerator.cpp \
+ src/world/element.cpp \
+ src/world/map.cpp \
+ src/world/ship.cpp \
+ #
SkywaysGlut_CXXSOURCES= $(CXXSOURCES) \
- src/configparser.cpp \
- src/glutmain.cpp
+ src/backends/configparser.cpp \
+ src/backends/glutmain.cpp \
+ #
SkywaysQt_CXXSOURCES= $(CXXSOURCES) \
- src/moc_qtwindow.cpp \
- src/qtconfigparser.cpp \
- src/qtmain.cpp \
- src/qtwindow.cpp
+ src/backends/moc_qtwindow.cpp \
+ src/backends/qtconfigparser.cpp \
+ src/backends/qtmain.cpp \
+ src/backends/qtwindow.cpp \
+ #
SkywaysSdl_CXXSOURCES= $(CXXSOURCES) \
- src/configparser.cpp \
- src/sdlmain.cpp
+ src/backends/configparser.cpp \
+ src/backends/sdlmain.cpp \
+ #
-CPPFLAGS+= -O2 -g -Wall -I/usr/include/FTGL -I/usr/include/freetype2
-LDFLAGS+= -lGL -lboost_filesystem -lftgl -lGLEW
+CPPFLAGS:= -O2 -g -Wall -I/usr/include/FTGL -I/usr/include/freetype2 $(CPPFLAGS) -Isrc
+LDFLAGS:= -lGL -lboost_filesystem -lftgl -lGLEW $(LDFLAGS)
SkywaysGlut_LDFLAGS=-lglut -lboost_program_options
SkywaysQt_LDFLAGS=-lQtOpenGL -lQtGui -lQtCore -lGLU -lGL -lpthread
SkywaysQt_CPPFLAGS=-D_REENTRANT -DQT_NO_DEBUG -DQT_OPENGL_LIB -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED -I/usr/include/qt4/QtCore -I/usr/include/qt4/QtGui -I/usr/include/qt4/QtOpenGL -I/usr/include/qt4
SkywaysSdl_LDFLAGS=-lSDL -lboost_program_options
SkywaysSdl_CPPFLAGS=-I/usr/include/SDL
EXTRADIST=
######################################
# auto-configuration: do not change! #
######################################
+CWD:=$(shell pwd)
+
+default: all
+
$(foreach prog,$(PROGRAMS),$(eval $(prog)_SOURCES=$($(prog)_CSOURCES) $($(prog)_CXXSOURCES)))
$(foreach prog,$(PROGRAMS),$(eval $(prog)_OBJECTS=$(patsubst %.c,%_$(prog).o,$($(prog)_CSOURCES)) $(patsubst %.cpp,%_$(prog).o,$($(prog)_CXXSOURCES))))
$(foreach flag,CFLAGS CPPFLAGS CXXFLAGS LDFLAGS,$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_$(flag)=$($(flag)) $($(prog)_$(flag)))))
#CSOURCES=$(foreach prog,$(PROGRAMS),$($(prog)_CSOURCES))
#CXXSOURCES=$(foreach prog,$(PROGRAMS),$($(prog)_CXXSOURCES))
#SOURCES=$(CSOURCES) $(CXXSOURCES)
#HEADERS=$(foreach prog,$(PROGRAMS),$($(prog)_HEADERS))
OBJECTS=$(foreach prog,$(PROGRAMS),$($(prog)_OBJECTS))
BINARIES=$(foreach prog,$(PROGRAMS),$($(prog)_BINARY))
DEPENDS=$(patsubst %.o,%.d,$(OBJECTS))
define CDEP_template
%_$(1).d: %.c
set -e; rm -f "$$@" || true; \
$$(CC) -MM -MQ "`echo "$$<" | sed 's,\($$*\)\.c,\1_$(1).o,'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) "$$<" | \
sed 's,\($$*_$(1)\).o *:,\1.o $$@:,' >$$@
endef
define CXXDEP_template
%_$(1).d: %.cpp
set -e; rm -f "$$@" || true; \
$$(CXX) -MM -MQ "`echo "$$<" | sed 's,\($$*\)\.cpp,\1_$(1).o,'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) "$$<" | \
sed 's,\($$*_$(1)\).o *:,\1.o $$@:,' >$$@
endef
define CSRC_template
%_$(1).o: %.c
$$(CC) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) $$< -o $$@
endef
define CXXSRC_template
%_$(1).o: %.cpp
$$(CXX) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) $$< -o $$@
endef
define BINARY_template
$$($(1)_BINARY): $$($(1)_OBJECTS)
$$(CC) $$($(1)_ALL_LDFLAGS) $$^ $$(LOADLIBS) $$(LDLIBS) -o $$@
endef
$(foreach template,CDEP CXXDEP CSRC CXXSRC BINARY,$(foreach prog,$(PROGRAMS),$(eval $(call $(template)_template,$(prog)))))
all: $(BINARIES)
#################################
# extra stuff: change as needed #
#################################
clean:
rm $(OBJECTS) $(BINARIES) $(DEPENDS) $(DISTFILES) || true
moc_%.cpp: %.hpp
moc-qt4 $(SkywaysQt_CPPFLAGS) $(SkywaysQt_CXXFLAGS) $< -o $@
.PHONY: default clean
-include $(DEPENDS)
diff --git a/src/configparser.cpp b/src/backends/configparser.cpp
similarity index 100%
rename from src/configparser.cpp
rename to src/backends/configparser.cpp
diff --git a/src/configparser.hpp b/src/backends/configparser.hpp
similarity index 97%
rename from src/configparser.hpp
rename to src/backends/configparser.hpp
index 34eafab..0f00cba 100644
--- a/src/configparser.hpp
+++ b/src/backends/configparser.hpp
@@ -1,48 +1,48 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _CONFIGPARSER_HPP_
#define _CONFIGPARSER_HPP_
#ifdef _QTCONFIGPARSER_HPP_
#error "Invalid build: cannot include qtconfigparser.hpp and configparser.hpp"
#endif // _QTCONFIGPARSER_HPP_
#include <boost/program_options.hpp>
-#include "configuration.hpp"
+#include <configuration.hpp>
class ConfigParser
{
public:
ConfigParser( Configuration& config );
bool args(int argc, char * argv[]);
private:
Configuration& _config;
boost::program_options::options_description options;
boost::program_options::variables_map vm;
};
#endif // _CONFIGPARSER_HPP_
diff --git a/src/glutmain.cpp b/src/backends/glutmain.cpp
similarity index 98%
rename from src/glutmain.cpp
rename to src/backends/glutmain.cpp
index 3183354..963f10a 100644
--- a/src/glutmain.cpp
+++ b/src/backends/glutmain.cpp
@@ -1,149 +1,149 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#if defined(FREEGLUT)
# include <GL/freeglut_ext.h>
#elif defined(OPENGLUT)
# include <GL/openglut_ext.h>
#else
# error "Unknown GLUT implementation. Need glutLeaveMainLoop extension."
#endif
-#include "controller.hpp"
+#include <controller.hpp>
#include "configparser.hpp"
-#include "configuration.hpp"
+#include <configuration.hpp>
std::auto_ptr< Controller > controller;
static void resize( int width, int height )
{
controller->resize(width, height);
glutPostRedisplay();
}
static void display()
{
controller->draw();
glutSwapBuffers();
}
static void keyDown( unsigned char key, int x, int y )
{
switch ( key )
{
case ' ':
return controller->keydown( Controller::JUMP_KEY );
case 27: // ESCAPE
return controller->keydown( Controller::QUIT_KEY );
}
glutPostRedisplay();
}
static void specialKeyDown( int key, int x, int y )
{
switch ( key )
{
case GLUT_KEY_LEFT:
return controller->keydown( Controller::STRAFE_L_KEY );
case GLUT_KEY_RIGHT:
return controller->keydown( Controller::STRAFE_R_KEY );
case GLUT_KEY_UP:
return controller->keydown( Controller::ACCEL_KEY );
case GLUT_KEY_DOWN:
return controller->keydown( Controller::DECEL_KEY );
}
glutPostRedisplay();
}
static void keyUp( unsigned char key, int x, int y )
{
switch ( key )
{
case ' ':
return controller->keyup( Controller::JUMP_KEY );
}
glutPostRedisplay();
}
static void specialKeyUp( int key, int x, int y )
{
switch ( key )
{
case GLUT_KEY_LEFT:
return controller->keyup( Controller::STRAFE_L_KEY );
case GLUT_KEY_RIGHT:
return controller->keyup( Controller::STRAFE_R_KEY );
case GLUT_KEY_UP:
return controller->keyup( Controller::ACCEL_KEY );
case GLUT_KEY_DOWN:
return controller->keyup( Controller::DECEL_KEY );
}
glutPostRedisplay();
}
static void idle()
{
static int tick = glutGet( GLUT_ELAPSED_TIME );
int newTick = glutGet( GLUT_ELAPSED_TIME );
controller->update( newTick - tick );
tick = newTick;
glutPostRedisplay();
}
int main( int argc, char * argv[] )
{
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_DOUBLE | GLUT_DEPTH );
glutInitWindowSize( 800, 600 );
glutCreateWindow( "Skyways" );
Configuration config;
ConfigParser configParser( config );
if ( !configParser.args( argc, argv ) )
return 0;
controller = config.buildController( &glutLeaveMainLoop );
glutReshapeFunc( resize );
glutDisplayFunc( display );
glutKeyboardFunc( keyDown );
glutKeyboardUpFunc( keyUp );
glutSpecialFunc( specialKeyDown );
glutSpecialUpFunc( specialKeyUp );
glutIdleFunc( idle );
controller->initialize();
glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION);
glutMainLoop();
return 0;
}
diff --git a/src/qtconfigparser.cpp b/src/backends/qtconfigparser.cpp
similarity index 100%
rename from src/qtconfigparser.cpp
rename to src/backends/qtconfigparser.cpp
diff --git a/src/qtconfigparser.hpp b/src/backends/qtconfigparser.hpp
similarity index 97%
rename from src/qtconfigparser.hpp
rename to src/backends/qtconfigparser.hpp
index d532b74..9c9e763 100644
--- a/src/qtconfigparser.hpp
+++ b/src/backends/qtconfigparser.hpp
@@ -1,44 +1,44 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _QTCONFIGPARSER_HPP_
#define _QTCONFIGPARSER_HPP_
#ifdef _CONFIGPARSER_HPP_
#error "Invalid build: cannot include qtconfigparser.hpp and configparser.hpp"
#endif // _CONFIGPARSER_HPP_
-#include "configuration.hpp"
+#include <configuration.hpp>
class ConfigParser
{
public:
ConfigParser( Configuration& config );
void readSettings();
private:
Configuration& _config;
};
#endif // _QTCONFIGPARSER_HPP_
diff --git a/src/qtmain.cpp b/src/backends/qtmain.cpp
similarity index 100%
rename from src/qtmain.cpp
rename to src/backends/qtmain.cpp
diff --git a/src/qtwindow.cpp b/src/backends/qtwindow.cpp
similarity index 97%
rename from src/qtwindow.cpp
rename to src/backends/qtwindow.cpp
index 5c43537..b345ed7 100644
--- a/src/qtwindow.cpp
+++ b/src/backends/qtwindow.cpp
@@ -1,115 +1,115 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <QCoreApplication>
#include <QKeyEvent>
#include <QTimer>
#include <QTime>
#include <iostream>
#include <cmath>
#include "qtconfigparser.hpp"
-#include "configuration.hpp"
-#include "controller.hpp"
+#include <configuration.hpp>
+#include <controller.hpp>
#include "qtwindow.hpp"
void quitFunc()
{
qApp->quit();
}
Window::Window( QWidget * parent )
: QGLWidget( parent )
{
timer = new QTimer( this );
connect( timer, SIGNAL(timeout()), this, SLOT(update()) );
timer->start( 0 );
time = new QTime();
setFocusPolicy( Qt::StrongFocus );
Configuration config;
ConfigParser configParser( config );
configParser.readSettings();
controller = config.buildController( &quitFunc );
}
Window::~Window()
{
}
void Window::update()
{
if ( time->isNull() )
{
time->start();
return;
}
else
{
controller->update( time->restart() );
}
( (QWidget*)this )->update();
}
int Window::mapKey( int key )
{
switch ( key )
{
case Qt::Key_Left: return Controller::STRAFE_L_KEY;
case Qt::Key_Right: return Controller::STRAFE_R_KEY;
case Qt::Key_Up: return Controller::ACCEL_KEY;
case Qt::Key_Down: return Controller::DECEL_KEY;
case Qt::Key_Space: return Controller::JUMP_KEY;
case Qt::Key_Escape: return Controller::QUIT_KEY;
default: return 0;
}
}
void Window::keyPressEvent( QKeyEvent * event )
{
if ( !event->isAutoRepeat() )
{
int key = mapKey( event->key() );
if ( key > 0 )
controller->keydown( key );
}
}
void Window::keyReleaseEvent( QKeyEvent * event )
{
if ( !event->isAutoRepeat() )
{
int key = mapKey( event->key() );
if ( key > 0 )
controller->keyup( key );
}
}
void Window::initializeGL()
{
controller->initialize();
}
void Window::resizeGL( int width, int height )
{
controller->resize( width, height );
}
void Window::paintGL()
{
controller->draw();
}
diff --git a/src/qtwindow.hpp b/src/backends/qtwindow.hpp
similarity index 100%
rename from src/qtwindow.hpp
rename to src/backends/qtwindow.hpp
diff --git a/src/sdlmain.cpp b/src/backends/sdlmain.cpp
similarity index 98%
rename from src/sdlmain.cpp
rename to src/backends/sdlmain.cpp
index baeff0d..3865e6d 100644
--- a/src/sdlmain.cpp
+++ b/src/backends/sdlmain.cpp
@@ -1,115 +1,115 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <stdexcept>
#include <boost/format.hpp>
#include <SDL.h>
-#include "controller.hpp"
+#include <controller.hpp>
#include "configparser.hpp"
-#include "configuration.hpp"
+#include <configuration.hpp>
void SdlThrowError( const char * message )
{
throw new std::runtime_error( (
boost::format("%1%: %2%") % message % SDL_GetError()
).str() );
}
class SdlInit
{
public:
SdlInit()
{
if ( SDL_Init(SDL_INIT_VIDEO) < 0 )
SdlThrowError( "Unable to init SDL" );
}
~SdlInit() { SDL_Quit(); }
};
class SdlScreen
{
public:
SdlScreen( SDL_Surface * screen )
{
_screen = screen;
if ( !_screen )
SdlThrowError( "Unable to set video mode" );
}
private:
SDL_Surface * _screen;
};
int mapSdlKey( SDLKey key )
{
switch ( key )
{
case SDLK_ESCAPE: return Controller::QUIT_KEY;
case SDLK_SPACE: return Controller::JUMP_KEY;
case SDLK_LEFT: return Controller::STRAFE_L_KEY;
case SDLK_RIGHT: return Controller::STRAFE_R_KEY;
case SDLK_UP: return Controller::ACCEL_KEY;
case SDLK_DOWN: return Controller::DECEL_KEY;
default: return -1;
}
}
std::auto_ptr< Controller > controller;
bool g_running;
void endMainLoop() { g_running = false; }
int main(int argc, char* argv[])
{
SdlInit init;
SdlScreen screen( SDL_SetVideoMode( 800, 600, 32, SDL_OPENGL ) );
Configuration config;
ConfigParser configParser( config );
if ( !configParser.args( argc, argv ) )
return 0;
controller = config.buildController( &endMainLoop );
controller->initialize();
controller->resize( 800, 600 );
g_running = true;
int time = SDL_GetTicks();
while ( g_running )
{
int newTime = SDL_GetTicks();
controller->update( newTime - time );
time = newTime;
controller->draw();
SDL_GL_SwapBuffers();
SDL_Event event;
int key;
while ( SDL_PollEvent(&event) )
{
if ( event.type == SDL_QUIT )
endMainLoop();
else if ( event.type == SDL_KEYDOWN && ( key = mapSdlKey( event.key.keysym.sym ) ) != -1 )
controller->keydown( key );
else if ( event.type == SDL_KEYUP && ( key = mapSdlKey( event.key.keysym.sym ) ) != -1 )
controller->keyup( key );
}
}
}
diff --git a/src/configuration.cpp b/src/configuration.cpp
index 0a7b234..de22c3d 100644
--- a/src/configuration.cpp
+++ b/src/configuration.cpp
@@ -1,42 +1,42 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
-#include "textprinter.hpp"
+#include <display/textprinter.hpp>
#include "controller.hpp"
#include "configuration.hpp"
Configuration::Configuration()
{
}
std::auto_ptr< Controller > Configuration::buildController( Controller::QuitCallback cbquit )
{
std::auto_ptr< TextPrinter > printer( new TextPrinter( "DejaVuSans.ttf" ) );
std::auto_ptr< Game > game( new Game(
10, 5, 100, 20, 1.5
) );
std::auto_ptr< Controller > controller( new Controller (
game, 3.5, 6, 10, cbquit, printer
) );
if ( _map.length() )
controller->loadMap( _map );
else
controller->generateMap();
return controller;
}
diff --git a/src/controller.cpp b/src/controller.cpp
index 2ac6fd2..fb6e7cc 100644
--- a/src/controller.cpp
+++ b/src/controller.cpp
@@ -1,211 +1,211 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <GL/glew.h>
#include <GL/gl.h>
#include <boost/format.hpp>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <cmath>
-#include "textprinter.hpp"
-#include "shader.hpp"
-#include "maploader.hpp"
-#include "mapgenerator.hpp"
-#include "blockloader.hpp"
+#include <display/textprinter.hpp>
+#include <display/shader.hpp>
+#include <loading/maploader.hpp>
+#include <loading/mapgenerator.hpp>
+#include <loading/blockloader.hpp>
#include "controller.hpp"
Controller::Controller(
std::auto_ptr< Game > game
, double cameraheight, double cameradistance, double camerarotation
, Controller::QuitCallback cbQuit
, std::auto_ptr< TextPrinter > printer
)
: _game( game )
, _camy( cameraheight ), _camz( cameradistance ), _camrot( camerarotation )
, _quitcb( cbQuit ), _printer( printer )
, _windowwidth( 1 ), _windowheight( 1 )
{
}
Controller::~Controller()
{
}
void Controller::keydown( int key )
{
switch ( key )
{
case STRAFE_L_KEY: _game->setStrafe( -1 ); break;
case STRAFE_R_KEY: _game->setStrafe( 1 ); break;
case ACCEL_KEY: _game->setAcceleration( 1 ); break;
case DECEL_KEY: _game->setAcceleration( -1 ); break;
case JUMP_KEY: _game->startJump(); break;
case QUIT_KEY:
if ( _game->dead() )
{
_quitcb();
}
else
{
_game->suicide();
}
break;
}
}
void Controller::keyup( int key )
{
switch ( key )
{
case STRAFE_L_KEY:
_game->setStrafe( 0 );
break;
case STRAFE_R_KEY:
_game->setStrafe( 0 );
break;
case ACCEL_KEY:
_game->setAcceleration( 0 );
break;
case DECEL_KEY:
_game->setAcceleration( 0 );
break;
}
}
void Controller::loadBlocks()
{
BlockLoader bl;
boost::ptr_map< std::string, Block > blocks;
bl.loadDirectory( "blocks", blocks );
_game->addBlocks( blocks );
}
void Controller::loadMap( std::string filename )
{
loadBlocks();
MapLoader ml( &_game->getBlocks() );
std::ifstream mapFile( filename.c_str() );
MapInfo mapinfo;
ml.loadMap( mapFile, mapinfo );
_game->setMap( mapinfo.map );
_game->setPos( mapinfo.startPos );
}
void Controller::generateMap()
{
loadBlocks();
MapGenerator mg( &_game->getBlocks() );
MapInfo mapinfo;
mg.generate( mapinfo );
_game->setMap( mapinfo.map );
_game->setPos( mapinfo.startPos );
}
void Controller::initialize()
{
GLenum err = glewInit();
if (err != GLEW_OK)
throw std::runtime_error((const char*)glewGetErrorString(err));
if (!GLEW_VERSION_2_0)
throw std::runtime_error("Nead OpenGL >= 2.0 for shaders. Update your graphics drivers!");
_shaderProgram = createShaderProgram("shaders/shader.glslv", "shaders/shader.glslf");
_game->setShader( *_shaderProgram );
glClearColor( 0.2, 0.2, 0.2, 0 );
glClearDepth( 1.0 );
glDepthFunc( GL_LEQUAL );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
glEnable( GL_LINE_SMOOTH );
glHint( GL_LINE_SMOOTH_HINT, GL_NICEST );
}
void Controller::resize( int width, int height )
{
glViewport( 0, 0, width, height );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
double fH = tan( 30.0 / 180.0 * 3.14159265358979323846 );
double fW = ( (double)width ) / ( (double)height ) * fH;
glFrustum( -fW, fW, -fH, fH, 1.0, 1000.0 );
glMatrixMode( GL_MODELVIEW );
_windowwidth = width;
_windowheight = height;
}
void Controller::draw()
{
glClear( GL_DEPTH_BUFFER_BIT );
// draw gradient background
glMatrixMode( GL_PROJECTION );
glPushMatrix();
glLoadIdentity();
glOrtho( 0, 1, 1, 0, -1, 1 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glDisable( GL_DEPTH_TEST );
glDisable( GL_BLEND );
glBegin( GL_QUADS );
glColor3f(0.1, 0.1, 0.1);
glVertex2f(0, 0);
glColor3f(0.15, 0.05, 0);
glVertex2f(0, 1);
glColor3f(0.15, 0.05, 0);
glVertex2f(1, 1);
glColor3f(0.1, 0.1, 0.1);
glVertex2f(1, 0);
glEnd();
glMatrixMode( GL_PROJECTION );
glPopMatrix();
glMatrixMode( GL_MODELVIEW );
glEnable( GL_DEPTH_TEST );
glEnable( GL_CULL_FACE );
glEnable( GL_BLEND );
glLoadIdentity();
glRotatef( _camrot, 1, 0, 0 );
glTranslated( 0.0, -_camy, -_camz );
_game->draw( _camz );
if ( _game->dead() )
{
glUseProgram(0);
_printer->print(
( boost::format( "%1% Distance Traveled: %2%" )
% _game->deathCause()
% _game->distanceTraveled() ).str(),
_windowwidth / 2, _windowheight / 4 * 3,
TextPrinter::ALIGN_CENTER
);
}
}
void Controller::update( int difference )
{
if ( _game->dead() )
return;
_game->update( difference );
}
diff --git a/src/controller.hpp b/src/controller.hpp
index dac7a00..736953b 100644
--- a/src/controller.hpp
+++ b/src/controller.hpp
@@ -1,76 +1,76 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _CONTROLLER_HPP_
#define _CONTROLLER_HPP_
#include <memory>
-#include "map.hpp"
+#include <world/map.hpp>
#include "game.hpp"
class TextPrinter;
class ShaderProgram;
class Controller
{
public:
typedef void (*QuitCallback)();
Controller(
std::auto_ptr< Game > game
, double cameraheight, double cameradistance, double camerarotation
, QuitCallback cbQuit
, std::auto_ptr< TextPrinter > printer
);
~Controller();
enum {
JUMP_KEY = 1,
STRAFE_L_KEY = 2,
STRAFE_R_KEY = 3,
ACCEL_KEY = 4,
DECEL_KEY = 5,
QUIT_KEY = 6,
};
void keydown( int key );
void keyup( int key );
void loadBlocks();
void loadMap( std::string filename );
void generateMap();
void initialize();
void resize( int width, int height );
void draw();
void update( int difference );
private:
std::auto_ptr< Game > _game;
double _camy, _camz, _camrot;
QuitCallback _quitcb;
std::auto_ptr< TextPrinter > _printer;
size_t _windowwidth, _windowheight;
std::auto_ptr< ShaderProgram > _shaderProgram;
};
#endif // _CONTROLLER_HPP_
diff --git a/src/shader.cpp b/src/display/shader.cpp
similarity index 100%
rename from src/shader.cpp
rename to src/display/shader.cpp
diff --git a/src/shader.hpp b/src/display/shader.hpp
similarity index 100%
rename from src/shader.hpp
rename to src/display/shader.hpp
diff --git a/src/textprinter.cpp b/src/display/textprinter.cpp
similarity index 100%
rename from src/textprinter.cpp
rename to src/display/textprinter.cpp
diff --git a/src/textprinter.hpp b/src/display/textprinter.hpp
similarity index 100%
rename from src/textprinter.hpp
rename to src/display/textprinter.hpp
diff --git a/src/uniform.hpp b/src/display/uniform.hpp
similarity index 100%
rename from src/uniform.hpp
rename to src/display/uniform.hpp
diff --git a/src/game.cpp b/src/game.cpp
index 3a4cd94..794f2e1 100644
--- a/src/game.cpp
+++ b/src/game.cpp
@@ -1,152 +1,152 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <cstdlib>
#include <ctime>
#include <cmath>
-#include "shader.hpp"
+#include <display/shader.hpp>
#include "game.hpp"
Game::Game(
double acceleration, double strafespeed, double speedlimit
, double gravity, double jumpstrength
, ShaderProgram * shader
)
: _ship(), _map( 0 ), _shader( shader )
, _currAcc( 0 ), _maxAcc( acceleration )
, _currStrafe( 0 ), _maxStrafe( strafespeed )
, _maxSpeed( speedlimit ), _zspeed( 0 )
, _yapex( 0 ), _tapex( 0 ), _gravity( gravity )
, _jstrength( jumpstrength ), _grounded( true )
{
_ship.initialize();
_ship.pos().x = 0.5;
std::string empty;
_blocks.insert( empty, new Block() );
}
void Game::startJump()
{
if ( _grounded ||
_map->collide( AABB(
_ship.pos().offset(0, -0.2, 0),
_ship.pos().offset(0, -0.2, 0).offset(_ship.size())
) ) )
{
_yapex = _ship.ypos() + _jstrength;
_tapex = sqrt( _jstrength / _gravity );
}
}
void Game::draw( double zminClip )
{
_shader->use();
glPushMatrix();
glTranslated( _ship.xpos() - 0.5, _ship.ypos(), 0.0 );
glColor4f( 1, 0, 0, 0.25 );
_ship.drawDl();
glPopMatrix();
glColor3f( 0.8f, 1, 1 );
glTranslatef( -0.5, 0.0, _ship.zpos() );
_map->glDraw( _ship.zpos() - zminClip );
}
void Game::update( int difference )
{
double multiplier = ( (double)difference ) / 1000;
Vector3 newPos = _ship.pos();
AABB shipAabb(
Vector3( -_ship.size().x/2, 0, 0 ),
Vector3( _ship.size().x/2, _ship.size().y, _ship.size().z )
);
if ( _currAcc < -_maxAcc ) _currAcc = -_maxAcc;
else if ( _currAcc > _maxAcc ) _currAcc = _maxAcc;
_zspeed += _currAcc*multiplier;
if ( _zspeed < 0 ) _zspeed = 0;
if ( _zspeed > _maxSpeed ) _zspeed = _maxSpeed;
newPos.z += multiplier * _zspeed;
if ( _map->collide( shipAabb.offset( newPos ) ) )
{
newPos.z = _ship.pos().z;
_zspeed = 0;
}
else
_ship.pos().z = newPos.z;
if ( _currStrafe < -_maxStrafe ) _currStrafe = -_maxStrafe;
if ( _currStrafe > _maxStrafe ) _currStrafe = _maxStrafe;
if ( _currStrafe != 0 )
{
newPos.x += _currStrafe*multiplier;
if ( _map->collide( shipAabb.offset( newPos ) ) )
newPos.x = _ship.pos().x;
else
_ship.pos().x = newPos.x;
}
if ( _tapex <= 0 && _grounded )
{
_tapex = 0;
_yapex = _ship.pos().y;
}
_tapex -= multiplier;
newPos.y = _yapex - _gravity * ( _tapex*_tapex );
const Element * collision;
if ( ( collision = _map->collide( shipAabb.offset( newPos ) ) ) )
{
newPos.y = _ship.pos().y;
if (_tapex < 0) {
_grounded = true;
collision->trigger( *this );
}
_tapex = 0;
_yapex = _ship.pos().y;
}
else
{
_ship.pos().y = newPos.y;
_grounded = false;
}
if ( droppedOut() )
{
kill( "You dropped into the void!" );
}
}
void Game::suicide()
{
kill( "You committed suicide!" );
}
void Game::explode()
{
kill( "You exploded!" );
}
void Game::kill( const std::string & cause )
{
_death = cause;
}
diff --git a/src/game.hpp b/src/game.hpp
index 84048ff..292d244 100644
--- a/src/game.hpp
+++ b/src/game.hpp
@@ -1,78 +1,78 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _WORLD_HPP_
#define _WORLD_HPP_
-#include "ship.hpp"
-#include "map.hpp"
+#include <world/ship.hpp>
+#include <world/map.hpp>
class ShaderProgram;
class Game
{
public:
Game(
double acceleration, double strafespeed, double speedlimit
, double gravity, double jumpstrength
, ShaderProgram * shader = 0
);
void addBlocks(boost::ptr_map< std::string, Block >& blocks) { _blocks.transfer( blocks ); }
void setMap(std::auto_ptr<Map> map) throw() { _map = map; _map->optimize(); }
void setPos(const Vector3& pos) throw() { _ship.pos() = pos; }
void setShader(ShaderProgram& shader) throw() { _shader = &shader; }
const boost::ptr_map< std::string, Block >& getBlocks() { return _blocks; }
void setAcceleration( double accel ) { _currAcc = accel*_maxAcc; }
void setStrafe( double strafe ) { _currStrafe = strafe*_maxStrafe; }
void startJump();
void draw( double zminClip );
void update( int difference );
double distanceTraveled() const throw() { return _ship.pos().z; }
bool droppedOut() const throw() {
return _ship.pos().y < _map->lowestPoint() - 1;
}
void kill( const std::string & cause );
void suicide();
void explode();
bool dead() const throw() { return !_death.empty(); }
const std::string& deathCause() const { return _death; }
private:
boost::ptr_map< std::string, Block > _blocks;
Ship _ship;
std::auto_ptr< Map > _map;
ShaderProgram * _shader;
double _currAcc, _maxAcc;
double _currStrafe, _maxStrafe;
double _maxSpeed, _zspeed;
double _yapex, _tapex, _gravity;
double _jstrength;
bool _grounded;
std::string _death;
};
#endif // _WORLD_HPP_
diff --git a/src/blockloader.cpp b/src/loading/blockloader.cpp
similarity index 100%
rename from src/blockloader.cpp
rename to src/loading/blockloader.cpp
diff --git a/src/blockloader.hpp b/src/loading/blockloader.hpp
similarity index 97%
rename from src/blockloader.hpp
rename to src/loading/blockloader.hpp
index 45debf5..eddc844 100644
--- a/src/blockloader.hpp
+++ b/src/loading/blockloader.hpp
@@ -1,38 +1,38 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _BLOCKLOADER_HPP_
#define _BLOCKLOADER_HPP_
#include <memory>
#include <string>
#include <boost/ptr_container/ptr_map.hpp>
-#include "block.hpp"
+#include <world/block.hpp>
class BlockLoader
{
public:
void loadDirectory( const char * directory, boost::ptr_map< std::string, Block >& block );
std::auto_ptr< Block > load( const std::string& filename );
};
#endif // _BLOCKLOADER_HPP_
diff --git a/src/mapgenerator.cpp b/src/loading/mapgenerator.cpp
similarity index 100%
rename from src/mapgenerator.cpp
rename to src/loading/mapgenerator.cpp
diff --git a/src/mapgenerator.hpp b/src/loading/mapgenerator.hpp
similarity index 100%
rename from src/mapgenerator.hpp
rename to src/loading/mapgenerator.hpp
diff --git a/src/maploader.cpp b/src/loading/maploader.cpp
similarity index 98%
rename from src/maploader.cpp
rename to src/loading/maploader.cpp
index cc2777f..52cb962 100644
--- a/src/maploader.cpp
+++ b/src/loading/maploader.cpp
@@ -1,200 +1,200 @@
#include <cctype>
#include <functional>
#include <istream>
#include <list>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
-#include "block.hpp"
-#include "element.hpp"
-#include "game.hpp"
+#include <world/block.hpp>
+#include <world/element.hpp>
+#include <game.hpp>
#include "maploader.hpp"
struct Row
{
std::string data;
double start, length;
};
struct Column
{
char key;
double start, length;
};
struct BlockPos
{
BlockPos() : block(0), ypos(0.0) { }
const Block * block;
double ypos;
Element::TriggerFn tfn;
};
void parseAlias(
std::istream& is
, const boost::ptr_map< std::string, Block >& blocks
, std::vector< std::list< BlockPos > >& aliases
)
{
char key;
is >> key;
if ( key < 0 )
throw std::runtime_error( std::string("Invalid alias name ") + key );
BlockPos pos;
std::string blockName;
while ( is >> blockName )
{
if ( blocks.find( blockName ) == blocks.end() )
throw std::runtime_error( "Unknown block " + blockName );
else
pos.block = blocks.find( blockName )->second;
std::string tmp;
if (!( is >> tmp ))
throw std::runtime_error( "Unexpected end of line." );
if (tmp.size() == 1 && std::isalpha(tmp[0]))
{
switch ( tmp[0] )
{
case 'd': pos.tfn = std::mem_fun_ref( &Game::explode ); break;
default: pos.tfn = 0; break;
}
if (!( is >> tmp ))
throw std::runtime_error( "Unexpected end of line." );
}
else
pos.tfn = 0;
std::istringstream( tmp ) >> pos.ypos;
aliases[ key ].push_back( pos );
}
}
void parseRow( size_t columns, const Row& row
, std::vector< Column >& runningdata
, const std::vector< std::list< BlockPos > >& aliases
, std::vector< Element >& elements
)
{
for (size_t i = 0; i < columns; ++i)
{
char key = ' ';
if ( !row.data.empty() )
{
key = row.data[i];
if ( key < 0 || ( key != ' ' && aliases[key].empty() ) )
throw std::runtime_error( std::string("Invalid alias name ") + key );
if ( key == runningdata[i].key )
{
runningdata[i].length += row.length;
continue;
}
}
if ( runningdata[i].key != ' ' )
{
for ( std::list< BlockPos >::const_iterator posIter = aliases[runningdata[i].key].begin();
posIter != aliases[runningdata[i].key].end(); ++posIter)
{
elements.push_back(Element(
( (double)i ) - ( (double)columns ) / 2,
posIter->ypos, runningdata[i].start, runningdata[i].length,
posIter->block,
Vector3(
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX
),
posIter->tfn
));
}
}
if ( !row.data.empty() )
{
runningdata[i].key = key;
runningdata[i].start = row.start;
runningdata[i].length = row.length;
}
}
}
void parseMap( size_t columns
, const std::vector< std::string >& maplines
, const std::vector< std::list< BlockPos > >& aliases
, std::vector< Element >& elements
)
{
Column emptyColumn = { ' ', 0, 0 };
Row row;
std::vector< Column > runningdata(columns, emptyColumn);
row.start = 0;
for ( std::vector< std::string >::const_iterator mapiter = maplines.begin();
mapiter != maplines.end(); ++mapiter )
{
const std::string& line = *mapiter;
size_t seperator = line.find(':');
if ( seperator == std::string::npos )
throw std::runtime_error( "Missing seperator in map row." );
if ( sscanf( line.substr(0, seperator).c_str(), " %lf ", &row.length ) != 1 )
throw std::runtime_error( "Invalid row length in map row." );
row.data = line.substr( seperator+1 );
if ( row.data.length() > columns )
throw std::runtime_error( "Bad row size." );
else if ( row.data.length() < columns )
row.data.resize( columns, ' ' );
parseRow( columns, row, runningdata, aliases, elements );
row.start += row.length;
}
row.data.clear();
parseRow( columns, row, runningdata, aliases, elements );
}
void MapLoader::loadMap( std::istream& is, MapInfo& mapinfo )
{
std::string line;
std::vector< std::list< BlockPos > > aliases(256);
std::vector< Element > elements;
size_t columns = 0;
std::vector< std::string > maplines;
Vector3 startPos = Vector3( 0.5, 0, 0 );
while ( std::getline( is, line ) )
{
std::istringstream iss( line );
std::string cmd;
if (!( iss >> cmd ))
continue;
else if ( cmd == "alias" )
{
parseAlias( iss, *_blocks, aliases );
}
else if ( cmd == "start" )
{
if (!( iss >> startPos.x >> startPos.y ))
throw std::runtime_error( "Unexpected end of line in start coordinates." );
}
else if ( cmd == "map" )
{
std::string delim;
if (!( iss >> columns ))
throw std::runtime_error( "Unexpected end of line before map width." );
if (!( iss >> delim ))
throw std::runtime_error( "Unexpected end of line before map delim." );
while ( is && std::getline( is, line ) && line != delim )
maplines.push_back(line);
if ( line != delim )
throw std::runtime_error( "Unexpected eof during map block." );
}
}
if ( maplines.empty() )
throw std::runtime_error( "Missing/empty map block." );
parseMap( columns, maplines, aliases, elements );
mapinfo.map.reset( new Map( 10, elements ) );
mapinfo.startPos = startPos;
}
diff --git a/src/maploader.hpp b/src/loading/maploader.hpp
similarity index 90%
rename from src/maploader.hpp
rename to src/loading/maploader.hpp
index f627c1f..c8e71c3 100644
--- a/src/maploader.hpp
+++ b/src/loading/maploader.hpp
@@ -1,35 +1,35 @@
#ifndef _MAPLOADER_HPP_
#define _MAPLOADER_HPP_
#include <memory>
#include <istream>
#include <boost/ptr_container/ptr_map.hpp>
-#include "vector.hpp"
-#include "map.hpp"
+#include <vector.hpp>
+#include <world/map.hpp>
struct MapInfo
{
std::auto_ptr< Map > map;
Vector3 startPos;
};
class MapLoader
{
public:
MapLoader( const boost::ptr_map< std::string, Block > * blocks )
: _blocks( blocks )
{
}
void loadMap( std::istream& is, MapInfo& mapinfo );
private:
const boost::ptr_map< std::string, Block > * _blocks;
};
#endif // _MAPLOADER_HPP_
diff --git a/src/objmodel.cpp b/src/loading/objmodel.cpp
similarity index 99%
rename from src/objmodel.cpp
rename to src/loading/objmodel.cpp
index 04accfa..38e7133 100644
--- a/src/objmodel.cpp
+++ b/src/loading/objmodel.cpp
@@ -1,281 +1,281 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <fstream>
#include <string>
#include <sstream>
#include <iostream>
#include <stdexcept>
#include <set>
-#include "vector.hpp"
-#include "range.hpp"
+#include <vector.hpp>
+#include <range.hpp>
#include "objmodel.hpp"
static bool parseFacePoint(const char* str, size_t& v, size_t& vt, size_t& vn)
{
// parse 3 numbers from string, seperated by slashes.
// missing numbers are set to 0, e.g. "3//2"->3,0,2
// only 1 slash means only vertex and texture
// 0 slashes means only vertex
v = vt = vn = 0;
for ( ; (*str) && (*str) != '/'; ++str)
v = v*10 + ((*str)-'0');
if (!(*str)) return true; else ++str;
for ( ; (*str) && (*str) != '/'; ++str)
vt = vt*10 + ((*str)-'0');
if (!(*str)) return true; else ++str;
for ( ; (*str); ++str)
vn = vn*10 + ((*str)-'0');
return true;
}
void loadObjModel(const char* filename, Model& model, bool unify,
std::vector< std::pair< std::string, std::string > >* unknowns,
const char * expectedUnknowns)
{
// Loading the mesh.
// Lines begin with either '#' to indicate a comment, 'v' to indicate a vertex
// ('vt' indicating skin vertex and 'vn' a vector normal) or 'f' to indicat a face.
// ** Comments are ignored.
// ** Vertex indices (in 'f' lines) are one based, so they start with one and not zero.
// ** Faces may have three or four indices so they must be triangles or quads.
// ** Any other tag in the file is ignored.
std::vector< Vector3 >& vertices = model.vertices;
std::vector< Vector3 >& normals = model.normals;
std::vector< Face<3> >& triangles = model.trifaces;
std::vector< Face<4> >& quads = model.quadfaces;
// open file
std::ifstream file(filename);
if (!file.is_open())
throw std::runtime_error(std::string("Unable to open OBJ file ") + filename);
std::string line;
bool unknownWarning = false;
Range<size_t> vertexRange = makeInvalidRange<size_t>()
#if 0
, textureRange = makeInvalidRange<size_t>()
#endif
, normalRange = makeInvalidRange<size_t>()
;
std::vector< Vector3 > _vertices;
std::vector< Vector3 > _normals;
std::vector< Face<3> > _triangles;
std::vector< Face<4> > _quads;
Range<double> xrange, yrange, zrange;
std::set<std::string> _expectedUnknowns;
if (expectedUnknowns)
{
const char * eubeg = expectedUnknowns;
while (*eubeg)
{
std::string eucur(eubeg);
_expectedUnknowns.insert(eucur);
eubeg += eucur.length();
}
}
while (getline(file, line))
{
std::istringstream iss(line);
std::string cmd;
// ignore empty lines and lines with '#' as first non-space char
if (!(iss >> cmd) || cmd[0] == '#')
continue;
else if (cmd == "vn")
{
double x, y, z;
if (!(iss >> x >> y >> z))
throw std::runtime_error("Invalid vertex normal: " + line);
_normals.push_back(Vector3(x, y, z));
}
else if (cmd == "vt")
{
#if 0
double tx, ty;
if (!(iss >> tx >> ty))
throw std::runtime_error("Invalid vertex texcoord: " + line);
m_texpoints.push_back(SkinVertex(tx, ty));
#endif
}
else if (cmd == "v")
{
double x, y, z;
if (!(iss >> x >> y >> z))
throw std::runtime_error("Invalid vertex: " + line);
xrange.include(x); yrange.include(y), zrange.include(z);
_vertices.push_back(Vector3(x, y, z));
}
else if (cmd == "f")
{
std::string fp[3];
if (!(iss >> fp[0] >> fp[1] >> fp[2]))
throw std::runtime_error("Invalid face: " + line);
Face<3> triangle; size_t it; // it: dummy
for (size_t i = 0; i < 3; ++i)
{
// parse indices from triplets
// note that even though indices are 1-based in the file, they
// are not decremented here. this is so the min/max ranges can
// be used for validation
if (!parseFacePoint(fp[i].c_str(), triangle.vertices[i], it, triangle.normals[i]))
throw std::runtime_error("Invalid face: " + line);
vertexRange.include(triangle.vertices[i]);
#if 0
textureRange.include(face.it[i]);
#endif
normalRange.include(triangle.normals[i]);
}
if (iss >> fp[0]) // theres a fourth corner -> it's a quad
{
Face<4> quad;
for (size_t i = 0; i < 3; ++i)
{
quad.vertices[i] = triangle.vertices[i];
quad.normals[i] = triangle.normals[i];
}
if (!parseFacePoint(fp[0].c_str(), quad.vertices[3], it, quad.normals[3]))
throw std::runtime_error("Invalid face: " + line);
vertexRange.include(quad.vertices[3]);
#if 0
textureRange.include(quad.it[3]);
#endif
normalRange.include(quad.normals[3]);
if (quad.valid())
_quads.push_back(quad);
}
else if (triangle.valid())
_triangles.push_back(triangle);
}
else
{
if (!unknownWarning && _expectedUnknowns.find(cmd) == _expectedUnknowns.end())
{
std::cerr << "Unknown token \"" << cmd << "\" encountered. (Additional warnings suppressed.)\n";
unknownWarning = true;
}
if (unknowns)
{
unknowns->push_back( make_pair(cmd, line) );
}
}
}
file.close();
// validate loaded object
if (_vertices.size() == 0) // must have vertices
throw std::runtime_error("Bad OBJ file: no vertices");
if (_triangles.size() == 0 && _quads.size() == 0) // must have faces
throw std::runtime_error("Bad OBJ file: no faces");
if (vertexRange.min == 0)
throw std::runtime_error("Bad OBJ file: faces with invalid vertex indices");
if (vertexRange.max > _vertices.size())
throw std::runtime_error("Bad OBJ file: out-of-range vertex indices");
#if 0
if (textureRange.max > m_texpoints.size())
throw std::runtime_error("Bad OBJ file: out-of-range texture indices");
if (textureRange.min == 0 && textureRange.max != 0)
throw std::runtime_error("Bad OBJ file: mixed texture usage on faces");
#endif
if (normalRange.max > _normals.size())
throw std::runtime_error("Bad OBJ file: out-of-range normal indices");
if (normalRange.min == 0 && normalRange.max != 0)
throw std::runtime_error("Bad OBJ file: mixed normal usage on faces");
if (normalRange.max == 0)
_normals.clear();
#if 0
// this is currently hardcoded, it may be parametrized later on
bool recalculateNormals = false;
// if there are no normals, force normal recalculation
if (m_normals.size() == 0 || normalRange.max == 0)
recalculateNormals = true;
if (recalculateNormals)
{
// recalculate normals, one normal per vertex
m_normals.clear();
m_normals.resize(m_vertices.size(), Vector3(0, 0, 0));
for (std::vector<Face>::iterator face = m_faces.begin(); face != m_faces.end(); ++face)
{
const Vector3 faceNormal((m_vertices[face->i[1]-1] - m_vertices[face->i[0]-1]).cross(m_vertices[face->i[2]-1] - m_vertices[face->i[0]-1]).normalized());
m_normals[face->i[0]-1] += faceNormal;
m_normals[face->i[1]-1] += faceNormal;
m_normals[face->i[2]-1] += faceNormal;
std::copy(face->i, face->i+3, face->in);
}
// normalize generated normals
for (std::vector<Vector3>::iterator normal = m_normals.begin(); normal != m_normals.end(); ++normal)
{
// only normalize normals that have been set (i.e. unused vertices will still have 0-length normals)
if (normal->lengthSquared() > 0)
normal->normalize();
}
}
#endif
#if 0
// turn on textures if used
m_textures = textureRange.min > 0;
#endif
if (unify)
{
double scale =
std::max( xrange.difference(),
std::max( yrange.difference(), zrange.difference() ) );
for ( size_t i = 0; i < _vertices.size(); ++i )
{
_vertices[i].x -= xrange.center();
_vertices[i].x /= scale;
_vertices[i].y -= yrange.center();
_vertices[i].y /= scale;
_vertices[i].z -= zrange.center();
_vertices[i].z /= scale;
}
}
for ( size_t i = 0; i < _triangles.size(); ++i )
{
for ( size_t j = 0; j < 3; ++j )
{
_triangles[i].vertices[j] -= 1;
_triangles[i].normals[j] -= 1;
}
}
for ( size_t i = 0; i < _quads.size(); ++i )
{
for ( size_t j = 0; j < 4; ++j )
{
_quads[i].vertices[j] -= 1;
_quads[i].normals[j] -= 1;
}
}
using std::swap;
swap( vertices, _vertices );
swap( normals, _normals );
swap( triangles, _triangles );
swap( quads, _quads );
}
diff --git a/src/objmodel.hpp b/src/loading/objmodel.hpp
similarity index 95%
rename from src/objmodel.hpp
rename to src/loading/objmodel.hpp
index f7f7f60..51a9ccb 100644
--- a/src/objmodel.hpp
+++ b/src/loading/objmodel.hpp
@@ -1,33 +1,33 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _OBJMODEL_HPP_
#define _OBJMODEL_HPP_
#include <vector>
#include <utility>
-#include "vector.hpp"
-#include "model.hpp"
+#include <vector.hpp>
+#include <world/model.hpp>
typedef std::vector< std::pair< std::string, std::string > > ObjUnknownsList;
void loadObjModel(const char* filename, Model& model, bool unify = true,
ObjUnknownsList* unknowns = 0, const char * expectedUnknowns = 0);
#endif
diff --git a/src/aabb.hpp b/src/world/aabb.hpp
similarity index 100%
rename from src/aabb.hpp
rename to src/world/aabb.hpp
diff --git a/src/block.cpp b/src/world/block.cpp
similarity index 99%
rename from src/block.cpp
rename to src/world/block.cpp
index 955bc94..0b48868 100644
--- a/src/block.cpp
+++ b/src/world/block.cpp
@@ -1,106 +1,105 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <GL/gl.h>
#include <stdexcept>
#include <sstream>
#include <fstream>
#include <string>
-#include "objmodel.hpp"
#include "block.hpp"
void Block::draw() const
{
if ( _model.get() )
{
glScalef( 1, 1, -1 );
_model->draw();
glScalef( 1, 1, -1 );
}
else
{
glBegin( GL_QUADS );
glNormal3f( 0, 0, 1 );
glVertex3f( 0, 0, 0 );
glVertex3f( 1, 0, 0 );
glVertex3f( 1, 1, 0 );
glVertex3f( 0, 1, 0 );
glNormal3f( 1, 0, 0 );
glVertex3f( 1, 0, 0 );
glVertex3f( 1, 0, -1 );
glVertex3f( 1, 1, -1 );
glVertex3f( 1, 1, 0 );
glNormal3f( 0, 0, -1 );
glVertex3f( 1, 0, -1 );
glVertex3f( 0, 0, -1 );
glVertex3f( 0, 1, -1 );
glVertex3f( 1, 1, -1 );
glNormal3f( -1, 0, 0 );
glVertex3f( 0, 0, -1 );
glVertex3f( 0, 0, 0 );
glVertex3f( 0, 1, 0 );
glVertex3f( 0, 1, -1 );
glNormal3f( 0, -1, 0 );
glVertex3f( 0, 0, 0 );
glVertex3f( 0, 0, -1 );
glVertex3f( 1, 0, -1 );
glVertex3f( 1, 0, 0 );
glNormal3f( 0, 1, 0 );
glVertex3f( 0, 1, 0 );
glVertex3f( 1, 1, 0 );
glVertex3f( 1, 1, -1 );
glVertex3f( 0, 1, -1 );
glEnd();
}
}
void Block::drawDl() const
{
if ( _blockDl == 0 )
{
_blockDl = glGenLists( 1 );
glNewList( _blockDl, GL_COMPILE_AND_EXECUTE );
draw();
glEndList();
}
else
{
glCallList( _blockDl );
}
}
bool Block::collide( const AABB& aabb ) const throw()
{
if ( !_model.get() )
{
return aabb.collide( AABB( Vector3( 0, 0, 0 ), Vector3( 1, 1, 1 ) ) );
}
for ( AabbList::const_iterator iter = _bounds.begin();
iter != _bounds.end(); ++iter )
{
if ( aabb.collide( *iter ) )
return true;
}
return false;
}
diff --git a/src/block.hpp b/src/world/block.hpp
similarity index 98%
rename from src/block.hpp
rename to src/world/block.hpp
index d789e1f..cf1e374 100644
--- a/src/block.hpp
+++ b/src/world/block.hpp
@@ -1,65 +1,65 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _BLOCK_HPP_
#define _BLOCK_HPP_
#include <memory>
#include <vector>
#include <istream>
#include <GL/gl.h>
-#include "vector.hpp"
+#include <vector.hpp>
#include "model.hpp"
#include "aabb.hpp"
class Block
{
public:
Block()
: _model( 0 )
, _bounds()
, _blockDl( 0 )
{
}
Block( std::auto_ptr<Model> model, std::vector< AABB > bounds)
: _model( model )
, _bounds( bounds )
, _blockDl( 0 )
{
}
void draw() const;
void drawDl() const;
bool collide( const AABB& aabb ) const throw();
private:
std::auto_ptr< Model > _model;
typedef std::vector< AABB > AabbList;
AabbList _bounds;
mutable GLuint _blockDl;
};
#endif // _BLOCK_HPP_
diff --git a/src/collisionaccelerator.cpp b/src/world/collisionaccelerator.cpp
similarity index 100%
rename from src/collisionaccelerator.cpp
rename to src/world/collisionaccelerator.cpp
index 3c6b3fe..860d685 100644
--- a/src/collisionaccelerator.cpp
+++ b/src/world/collisionaccelerator.cpp
@@ -1,92 +1,92 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
-#include "collisionaccelerator.hpp"
#include <cmath>
+#include "collisionaccelerator.hpp"
CollisionAccelerator::CollisionAccelerator( double sectionSize )
: _sectionSize( sectionSize )
{
}
void CollisionAccelerator::addElement( const Element& e )
{
const Element * const pe = &e;
const double beginDistance = pe->zoff();
size_t beginSection = (size_t)(beginDistance / _sectionSize);
size_t sectionCount = (size_t)((pe->length() + fmod(beginDistance, _sectionSize)) / _sectionSize);
// make sure section array has sufficient space
if ( sections.size() <= ( beginSection + sectionCount ) )
sections.resize( beginSection + sectionCount + 1 );
if ( sectionCount == 0 ) // fully contained in one section
{
sections[ beginSection ].complete.push_back( pe );
return;
}
sections[ beginSection ].beginning.push_back( pe );
++beginSection; --sectionCount;
for ( ; sectionCount > 0 ; --sectionCount, ++beginSection )
{
sections[ beginSection ].running.push_back( pe );
}
sections[ beginSection ].ending.push_back( pe );
}
const Element * CollisionAccelerator::collide(const AABB& aabb) const
{
size_t section1 = ( (size_t)aabb.p1.z ) / _sectionSize,
section2 = ( (size_t)aabb.p2.z ) / _sectionSize;
if ( section1 >= sections.size() )
return 0;
const Element * result = collide(aabb, sections[ section1 ]);
if ( !result && section2 != section1 && section2 < sections.size() )
result = collide(aabb, sections[ section2 ]);
return result;
}
const Element * CollisionAccelerator::collide(const AABB& aabb, const MapSection& section) const
{
const Element * result = 0;
(result = collide(aabb, section.beginning)) ||
(result = collide(aabb, section.running)) ||
(result = collide(aabb, section.ending)) ||
(result = collide(aabb, section.complete));
return result;
}
const Element * CollisionAccelerator::collide(const AABB& aabb, const std::vector< const Element* >& elemreflist) const
{
typedef std::vector< const Element* > ElemRefList;
typedef ElemRefList::const_iterator ElemRefIter;
for ( ElemRefIter elemref = elemreflist.begin() ;
elemref != elemreflist.end(); ++elemref )
{
if ( (*elemref)->collide( aabb ) )
return *elemref;
}
return 0;
}
diff --git a/src/collisionaccelerator.hpp b/src/world/collisionaccelerator.hpp
similarity index 100%
rename from src/collisionaccelerator.hpp
rename to src/world/collisionaccelerator.hpp
diff --git a/src/element.cpp b/src/world/element.cpp
similarity index 100%
rename from src/element.cpp
rename to src/world/element.cpp
diff --git a/src/element.hpp b/src/world/element.hpp
similarity index 100%
rename from src/element.hpp
rename to src/world/element.hpp
index 9388ef2..93cd51f 100644
--- a/src/element.hpp
+++ b/src/world/element.hpp
@@ -1,60 +1,60 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _ELEMENT_HPP_
#define _ELEMENT_HPP_
-#include "block.hpp"
#include <boost/function.hpp>
+#include "block.hpp"
class Game;
class Element
{
public:
typedef boost::function1<void, Game&> TriggerFn;
Element( double x, double y, double z, double l, const Block * b, const Vector3& color, TriggerFn trigger = 0 )
: _pos(Vector3( x, y, z)), _length( l ), _block( b ), _color( color ), _trigger( trigger )
{
}
void glDraw();
void trigger(Game& game) const { if (_trigger) _trigger(game); }
const Vector3& pos() const throw() { return _pos; }
double xoff() const throw() { return _pos.x; }
double yoff() const throw() { return _pos.y; }
double zoff() const throw() { return _pos.z; }
double length() const throw() { return _length; }
bool collide( const AABB& aabb ) const;
private:
Vector3 _pos;
double _length;
const Block * _block;
Vector3 _color;
TriggerFn _trigger;
};
#endif // _ELEMENT_HPP_
diff --git a/src/map.cpp b/src/world/map.cpp
similarity index 98%
rename from src/map.cpp
rename to src/world/map.cpp
index 95faba0..6be9073 100644
--- a/src/map.cpp
+++ b/src/world/map.cpp
@@ -1,64 +1,64 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <algorithm>
#include <functional>
#include <fstream>
#include <string>
#include <sstream>
#include <list>
#include <cctype>
-#include "game.hpp"
+#include <game.hpp>
#include "map.hpp"
Map::Map( size_t sectionSize )
: _accelerator( sectionSize )
{
}
Map::Map( size_t sectionSize, std::vector< Element >& elements )
: _accelerator( sectionSize )
{
using std::swap;
swap ( elements, _elements );
}
void Map::glDraw( double )
{
for ( ElementList::iterator elem = _elements.begin() ;
elem != _elements.end(); ++elem )
{
elem->glDraw();
}
_elementsDrawn = _elements.size();
}
void Map::optimize()
{
for ( ElementList::iterator elem = _elements.begin() ;
elem != _elements.end(); ++elem )
{
_accelerator.addElement( *elem );
}
}
const Element * Map::collide( const AABB& aabb )
{
return _accelerator.collide( aabb );
}
diff --git a/src/map.hpp b/src/world/map.hpp
similarity index 100%
rename from src/map.hpp
rename to src/world/map.hpp
diff --git a/src/model.hpp b/src/world/model.hpp
similarity index 98%
rename from src/model.hpp
rename to src/world/model.hpp
index e0d5a70..486fb54 100644
--- a/src/model.hpp
+++ b/src/world/model.hpp
@@ -1,105 +1,105 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _MODEL_HPP_
#define _MODEL_HPP_
#include <vector>
#include <GL/gl.h>
-#include "vector.hpp"
+#include <vector.hpp>
typedef struct
{
size_t ix[3];
} Triangle;
typedef struct
{
size_t ix[4];
} Quad;
template<size_t N>
struct Face
{
size_t vertices[N];
size_t normals[N];
bool valid()
{
for (size_t i = 0; i < N; ++i)
{
if ( vertices[i] == vertices[(i+1)%N] )
return false;
}
return true;
}
};
typedef struct
{
std::vector< Vector3 > vertices;
std::vector< Vector3 > normals;
std::vector< Face<3> > trifaces;
std::vector< Face<4> > quadfaces;
void draw() const
{
glBegin( GL_TRIANGLES );
for ( size_t i = 0; i < trifaces.size(); ++i )
drawFace( trifaces[i] );
glEnd();
glBegin( GL_QUADS );
for ( size_t i = 0; i < quadfaces.size(); ++i )
drawFace( quadfaces[i] );
glEnd();
}
private:
template<size_t N>
void drawFace( const Face<N>& face ) const
{
for ( size_t i = 0; i < N; ++i )
{
if ( normals.size() > 0 )
{
glNormal3d(
normals[face.normals[i]].x,
normals[face.normals[i]].y,
normals[face.normals[i]].z
);
}
glVertex3d(
vertices[face.vertices[i]].x,
vertices[face.vertices[i]].y,
vertices[face.vertices[i]].z
);
}
}
} Model;
#endif // _MODEL_HPP_
diff --git a/src/ship.cpp b/src/world/ship.cpp
similarity index 98%
rename from src/ship.cpp
rename to src/world/ship.cpp
index 639de7e..6e7b7b7 100644
--- a/src/ship.cpp
+++ b/src/world/ship.cpp
@@ -1,122 +1,122 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <GL/gl.h>
#include <cmath>
#include <iostream>
#include <stdexcept>
+#include <loading/objmodel.hpp>
#include "ship.hpp"
-#include "objmodel.hpp"
Ship::Ship()
: _pos(Vector3(0, 0, 0))
, _size(Vector3(0.8, 0.5, 1.0))
, _shipDl(0)
{
}
Ship::~Ship()
{
}
void Ship::initialize()
{
try
{
loadObjModel("ship.obj", _model, true, 0, "mtl\0");
std::cout << "loaded "
<< _model.vertices.size() << " vertices and "
<< _model.trifaces.size() + _model.quadfaces.size()
<< " faces for ship." << std::endl;
}
catch (std::runtime_error& e)
{
std::cerr <<
"Warning: failed to load ship model, "
"falling back to box ship.\n"
"Exception caught was: "
<< e.what() << '\n';
}
}
void Ship::draw()
{
glTranslated( 0, _size.y / 2, -_size.z / 2 );
if ( _model.vertices.size() && _model.trifaces.size() )
{
glScaled( _size.x, _size.y, -_size.z );
_model.draw();
}
else
{
glScaled( _size.x, _size.y, _size.z );
glEnable( GL_POLYGON_OFFSET_FILL );
glPolygonOffset( 0.01f, 0.01f );
drawSimple();
glDisable( GL_POLYGON_OFFSET_FILL );
}
}
void Ship::drawDl()
{
if ( _shipDl == 0 )
{
_shipDl = glGenLists( 1 );
glNewList( _shipDl, GL_COMPILE_AND_EXECUTE );
draw();
glEndList();
}
else
{
glCallList( _shipDl );
}
}
void Ship::drawSimple()
{
glBegin( GL_QUADS );
glNormal3d( 0, 0, 1 );
glVertex3d( -0.5, 0.5, 0.5 );
glVertex3d( -0.5, -0.5, 0.5 );
glVertex3d( 0.5, -0.5, 0.5 );
glVertex3d( 0.5, 0.5, 0.5 );
glEnd();
glBegin( GL_TRIANGLES );
glNormal3d( -1, 0, -0.5 );
glVertex3d( -0.5, -0.5, 0.5 );
glVertex3d( -0.5, 0.5, 0.5 );
glVertex3d( 0, 0, -1.0 );
glNormal3d( 0, 1, -0.5 );
glVertex3d( -0.5, 0.5, 0.5 );
glVertex3d( 0.5, 0.5, 0.5 );
glVertex3d( 0, 0, -1.0 );
glNormal3d( 1, 0, -0.5 );
glVertex3d( 0.5, 0.5, 0.5 );
glVertex3d( 0.5, -0.5, 0.5 );
glVertex3d( 0, 0, -1.0 );
glNormal3d( 0, -1, -0.5 );
glVertex3d( 0.5, -0.5, 0.5 );
glVertex3d( -0.5, -0.5, 0.5 );
glVertex3d( 0, 0, -1.0 );
glEnd();
}
diff --git a/src/ship.hpp b/src/world/ship.hpp
similarity index 100%
rename from src/ship.hpp
rename to src/world/ship.hpp
|
devnev/skyways
|
335db70cc43457ca22f0d4c3b2a523887188284a
|
Seperated map loading out of map container classes.
|
diff --git a/Makefile b/Makefile
index d25e263..f1194e9 100644
--- a/Makefile
+++ b/Makefile
@@ -1,155 +1,161 @@
###########################
# prelude: do not change! #
###########################
CWD:=$(shell pwd)
default: all
BUILDFLAGS=CFLAGS CPPFLAGS CXXFLAGS LDFLAGS
define FLAGINIT_template
ifndef $(1)
$(1)=
endif
endef
$(foreach flag,$(BUILDFLAGS),$(eval $(call FLAGINIT_template,$(flag))))
######################################
# configuration: change things here. #
######################################
PROGRAMS=SkywaysGlut SkywaysQt SkywaysSdl
SkywaysGlut_BINARY=skyways.glut
SkywaysQt_BINARY=skyways.qt
SkywaysSdl_BINARY=skyways.sdl
HEADERS= \
src/aabb.hpp \
src/block.hpp \
+ src/blockloader.hpp \
src/collisionaccelerator.hpp \
src/configuration.hpp \
src/controller.hpp \
src/element.hpp \
src/map.hpp \
+ src/mapgenerator.hpp \
+ src/maploader.hpp \
src/model.hpp \
src/objmodel.hpp \
src/shader.hpp \
src/ship.hpp \
src/textprinter.hpp \
src/vector.hpp \
src/game.hpp
SkywasyGlut_HEADERS= $(HEADERS) \
src/configparser.hpp
SkywasyQt_HEADERS= $(HEADERS) \
src/qtconfigparser.hpp \
src/qtwindow.hpp
SkywaysSdl_HEADERS= $(HEADERS) \
src/configparser.hpp
CXXSOURCES= \
src/block.cpp \
+ src/blockloader.cpp \
src/collisionaccelerator.cpp \
src/configuration.cpp \
src/controller.cpp \
src/element.cpp \
src/map.cpp \
+ src/mapgenerator.cpp \
+ src/maploader.cpp \
src/objmodel.cpp \
src/shader.cpp \
src/ship.cpp \
src/textprinter.cpp \
src/game.cpp
SkywaysGlut_CXXSOURCES= $(CXXSOURCES) \
src/configparser.cpp \
src/glutmain.cpp
SkywaysQt_CXXSOURCES= $(CXXSOURCES) \
src/moc_qtwindow.cpp \
src/qtconfigparser.cpp \
src/qtmain.cpp \
src/qtwindow.cpp
SkywaysSdl_CXXSOURCES= $(CXXSOURCES) \
src/configparser.cpp \
src/sdlmain.cpp
CPPFLAGS+= -O2 -g -Wall -I/usr/include/FTGL -I/usr/include/freetype2
LDFLAGS+= -lGL -lboost_filesystem -lftgl -lGLEW
SkywaysGlut_LDFLAGS=-lglut -lboost_program_options
SkywaysQt_LDFLAGS=-lQtOpenGL -lQtGui -lQtCore -lGLU -lGL -lpthread
SkywaysQt_CPPFLAGS=-D_REENTRANT -DQT_NO_DEBUG -DQT_OPENGL_LIB -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED -I/usr/include/qt4/QtCore -I/usr/include/qt4/QtGui -I/usr/include/qt4/QtOpenGL -I/usr/include/qt4
SkywaysSdl_LDFLAGS=-lSDL -lboost_program_options
SkywaysSdl_CPPFLAGS=-I/usr/include/SDL
EXTRADIST=
######################################
# auto-configuration: do not change! #
######################################
$(foreach prog,$(PROGRAMS),$(eval $(prog)_SOURCES=$($(prog)_CSOURCES) $($(prog)_CXXSOURCES)))
$(foreach prog,$(PROGRAMS),$(eval $(prog)_OBJECTS=$(patsubst %.c,%_$(prog).o,$($(prog)_CSOURCES)) $(patsubst %.cpp,%_$(prog).o,$($(prog)_CXXSOURCES))))
$(foreach flag,CFLAGS CPPFLAGS CXXFLAGS LDFLAGS,$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_$(flag)=$($(flag)) $($(prog)_$(flag)))))
#CSOURCES=$(foreach prog,$(PROGRAMS),$($(prog)_CSOURCES))
#CXXSOURCES=$(foreach prog,$(PROGRAMS),$($(prog)_CXXSOURCES))
#SOURCES=$(CSOURCES) $(CXXSOURCES)
#HEADERS=$(foreach prog,$(PROGRAMS),$($(prog)_HEADERS))
OBJECTS=$(foreach prog,$(PROGRAMS),$($(prog)_OBJECTS))
BINARIES=$(foreach prog,$(PROGRAMS),$($(prog)_BINARY))
DEPENDS=$(patsubst %.o,%.d,$(OBJECTS))
define CDEP_template
%_$(1).d: %.c
set -e; rm -f "$$@" || true; \
$$(CC) -MM -MQ "`echo "$$<" | sed 's,\($$*\)\.c,\1_$(1).o,'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) "$$<" | \
sed 's,\($$*_$(1)\).o *:,\1.o $$@:,' >$$@
endef
define CXXDEP_template
%_$(1).d: %.cpp
set -e; rm -f "$$@" || true; \
$$(CXX) -MM -MQ "`echo "$$<" | sed 's,\($$*\)\.cpp,\1_$(1).o,'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) "$$<" | \
sed 's,\($$*_$(1)\).o *:,\1.o $$@:,' >$$@
endef
define CSRC_template
%_$(1).o: %.c
$$(CC) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) $$< -o $$@
endef
define CXXSRC_template
%_$(1).o: %.cpp
$$(CXX) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) $$< -o $$@
endef
define BINARY_template
$$($(1)_BINARY): $$($(1)_OBJECTS)
$$(CC) $$($(1)_ALL_LDFLAGS) $$^ $$(LOADLIBS) $$(LDLIBS) -o $$@
endef
$(foreach template,CDEP CXXDEP CSRC CXXSRC BINARY,$(foreach prog,$(PROGRAMS),$(eval $(call $(template)_template,$(prog)))))
all: $(BINARIES)
#################################
# extra stuff: change as needed #
#################################
clean:
rm $(OBJECTS) $(BINARIES) $(DEPENDS) $(DISTFILES) || true
moc_%.cpp: %.hpp
moc-qt4 $(SkywaysQt_CPPFLAGS) $(SkywaysQt_CXXFLAGS) $< -o $@
.PHONY: default clean
-include $(DEPENDS)
diff --git a/src/block.cpp b/src/block.cpp
index e222e5a..955bc94 100644
--- a/src/block.cpp
+++ b/src/block.cpp
@@ -1,131 +1,106 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <GL/gl.h>
#include <stdexcept>
#include <sstream>
#include <fstream>
#include <string>
#include "objmodel.hpp"
#include "block.hpp"
void Block::draw() const
{
- if (model.vertices.size() > 0)
+ if ( _model.get() )
{
glScalef( 1, 1, -1 );
- model.draw();
+ _model->draw();
glScalef( 1, 1, -1 );
}
else
{
glBegin( GL_QUADS );
glNormal3f( 0, 0, 1 );
glVertex3f( 0, 0, 0 );
glVertex3f( 1, 0, 0 );
glVertex3f( 1, 1, 0 );
glVertex3f( 0, 1, 0 );
glNormal3f( 1, 0, 0 );
glVertex3f( 1, 0, 0 );
glVertex3f( 1, 0, -1 );
glVertex3f( 1, 1, -1 );
glVertex3f( 1, 1, 0 );
glNormal3f( 0, 0, -1 );
glVertex3f( 1, 0, -1 );
glVertex3f( 0, 0, -1 );
glVertex3f( 0, 1, -1 );
glVertex3f( 1, 1, -1 );
glNormal3f( -1, 0, 0 );
glVertex3f( 0, 0, -1 );
glVertex3f( 0, 0, 0 );
glVertex3f( 0, 1, 0 );
glVertex3f( 0, 1, -1 );
glNormal3f( 0, -1, 0 );
glVertex3f( 0, 0, 0 );
glVertex3f( 0, 0, -1 );
glVertex3f( 1, 0, -1 );
glVertex3f( 1, 0, 0 );
glNormal3f( 0, 1, 0 );
glVertex3f( 0, 1, 0 );
glVertex3f( 1, 1, 0 );
glVertex3f( 1, 1, -1 );
glVertex3f( 0, 1, -1 );
glEnd();
}
}
void Block::drawDl() const
{
if ( _blockDl == 0 )
{
_blockDl = glGenLists( 1 );
glNewList( _blockDl, GL_COMPILE_AND_EXECUTE );
draw();
glEndList();
}
else
{
glCallList( _blockDl );
}
}
-std::auto_ptr< Block > Block::fromFile( const std::string& filename )
-{
- std::auto_ptr< Block > block( new Block() );
- ObjUnknownsList objunknowns;
-
- loadObjModel( filename.c_str(), block->model, false, &objunknowns, "b\0" );
-
- for ( ObjUnknownsList::iterator unknown = objunknowns.begin();
- unknown != objunknowns.end(); ++unknown )
- {
- if ( unknown->first == "b" )
- {
- std::istringstream iss( unknown->second );
- std::string cmd;
- iss >> cmd;
-
- AABB aabb;
- iss >> aabb.p1.x >> aabb.p1.y >> aabb.p1.z
- >> aabb.p2.x >> aabb.p2.y >> aabb.p2.z;
- block->bounds.push_back( aabb );
- }
- }
- return block;
-}
-
bool Block::collide( const AABB& aabb ) const throw()
{
- if ( model.vertices.size() == 0 )
+ if ( !_model.get() )
{
return aabb.collide( AABB( Vector3( 0, 0, 0 ), Vector3( 1, 1, 1 ) ) );
}
- for ( AabbList::const_iterator iter = bounds.begin();
- iter != bounds.end(); ++iter )
+ for ( AabbList::const_iterator iter = _bounds.begin();
+ iter != _bounds.end(); ++iter )
{
if ( aabb.collide( *iter ) )
return true;
}
return false;
}
diff --git a/src/block.hpp b/src/block.hpp
index 1eeb21f..d789e1f 100644
--- a/src/block.hpp
+++ b/src/block.hpp
@@ -1,56 +1,65 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _BLOCK_HPP_
#define _BLOCK_HPP_
#include <memory>
#include <vector>
#include <istream>
#include <GL/gl.h>
#include "vector.hpp"
#include "model.hpp"
#include "aabb.hpp"
class Block
{
public:
- Block() : _blockDl( 0 ) { }
+ Block()
+ : _model( 0 )
+ , _bounds()
+ , _blockDl( 0 )
+ {
+ }
+
+ Block( std::auto_ptr<Model> model, std::vector< AABB > bounds)
+ : _model( model )
+ , _bounds( bounds )
+ , _blockDl( 0 )
+ {
+ }
void draw() const;
void drawDl() const;
- static std::auto_ptr< Block > fromStream( std::istream& is );
- static std::auto_ptr< Block > fromFile( const std::string& filename );
-
bool collide( const AABB& aabb ) const throw();
private:
- Model model;
+ std::auto_ptr< Model > _model;
typedef std::vector< AABB > AabbList;
- AabbList bounds;
+ AabbList _bounds;
mutable GLuint _blockDl;
};
#endif // _BLOCK_HPP_
diff --git a/src/blockloader.cpp b/src/blockloader.cpp
new file mode 100644
index 0000000..4bf54f8
--- /dev/null
+++ b/src/blockloader.cpp
@@ -0,0 +1,59 @@
+#include <sstream>
+#include <vector>
+#include <boost/filesystem.hpp>
+#include <boost/filesystem/fstream.hpp>
+#include "objmodel.hpp"
+#include "blockloader.hpp"
+
+void BlockLoader::loadDirectory( const char * directory, boost::ptr_map< std::string, Block >& blocks )
+{
+ boost::ptr_map< std::string, Block > newBlocks;
+
+ using namespace boost::filesystem;
+ path block_dir( directory );
+ if ( !exists( block_dir ) )
+ return;
+ for ( recursive_directory_iterator block_fs_entry( block_dir ) ;
+ block_fs_entry != recursive_directory_iterator() ;
+ ++block_fs_entry )
+ {
+ if ( is_directory( block_fs_entry->status() ) )
+ continue;
+ std::string block_path;
+ path::iterator iter = block_fs_entry->path().begin();
+ ++iter;
+ if ( iter != block_fs_entry->path().end() )
+ block_path = *iter;
+ for ( ++iter ; iter != block_fs_entry->path().end() ; ++iter )
+ block_path = block_path + "/" + *iter;
+ newBlocks.insert( block_path, load( block_fs_entry->path().string() ) );
+ }
+
+ blocks.transfer( newBlocks );
+}
+
+std::auto_ptr< Block > BlockLoader::load( const std::string& filename )
+{
+ ObjUnknownsList objunknowns;
+ std::auto_ptr< Model > model( new Model() );
+ loadObjModel( filename.c_str(), *model, false, &objunknowns, "b\0" );
+ std::vector< AABB > bounds;
+
+ for ( ObjUnknownsList::iterator unknown = objunknowns.begin();
+ unknown != objunknowns.end(); ++unknown )
+ {
+ if ( unknown->first == "b" )
+ {
+ std::istringstream iss( unknown->second );
+ std::string cmd;
+ iss >> cmd;
+
+ AABB aabb;
+ iss >> aabb.p1.x >> aabb.p1.y >> aabb.p1.z
+ >> aabb.p2.x >> aabb.p2.y >> aabb.p2.z;
+ bounds.push_back( aabb );
+ }
+ }
+ return std::auto_ptr< Block >( new Block( model, bounds ) );
+}
+
diff --git a/src/blockloader.hpp b/src/blockloader.hpp
new file mode 100644
index 0000000..45debf5
--- /dev/null
+++ b/src/blockloader.hpp
@@ -0,0 +1,38 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#ifndef _BLOCKLOADER_HPP_
+#define _BLOCKLOADER_HPP_
+
+#include <memory>
+#include <string>
+#include <boost/ptr_container/ptr_map.hpp>
+#include "block.hpp"
+
+class BlockLoader
+{
+
+public:
+
+ void loadDirectory( const char * directory, boost::ptr_map< std::string, Block >& block );
+ std::auto_ptr< Block > load( const std::string& filename );
+
+};
+
+#endif // _BLOCKLOADER_HPP_
diff --git a/src/controller.cpp b/src/controller.cpp
index f09deee..2ac6fd2 100644
--- a/src/controller.cpp
+++ b/src/controller.cpp
@@ -1,197 +1,211 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <GL/glew.h>
#include <GL/gl.h>
#include <boost/format.hpp>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include "textprinter.hpp"
#include "shader.hpp"
+#include "maploader.hpp"
+#include "mapgenerator.hpp"
+#include "blockloader.hpp"
#include "controller.hpp"
Controller::Controller(
std::auto_ptr< Game > game
, double cameraheight, double cameradistance, double camerarotation
, Controller::QuitCallback cbQuit
, std::auto_ptr< TextPrinter > printer
)
- : _game( game ), _map( 10 )
+ : _game( game )
, _camy( cameraheight ), _camz( cameradistance ), _camrot( camerarotation )
, _quitcb( cbQuit ), _printer( printer )
, _windowwidth( 1 ), _windowheight( 1 )
{
}
Controller::~Controller()
{
}
void Controller::keydown( int key )
{
switch ( key )
{
case STRAFE_L_KEY: _game->setStrafe( -1 ); break;
case STRAFE_R_KEY: _game->setStrafe( 1 ); break;
case ACCEL_KEY: _game->setAcceleration( 1 ); break;
case DECEL_KEY: _game->setAcceleration( -1 ); break;
case JUMP_KEY: _game->startJump(); break;
case QUIT_KEY:
if ( _game->dead() )
{
_quitcb();
}
else
{
_game->suicide();
}
break;
}
}
void Controller::keyup( int key )
{
switch ( key )
{
case STRAFE_L_KEY:
_game->setStrafe( 0 );
break;
case STRAFE_R_KEY:
_game->setStrafe( 0 );
break;
case ACCEL_KEY:
_game->setAcceleration( 0 );
break;
case DECEL_KEY:
_game->setAcceleration( 0 );
break;
}
}
+void Controller::loadBlocks()
+{
+ BlockLoader bl;
+ boost::ptr_map< std::string, Block > blocks;
+ bl.loadDirectory( "blocks", blocks );
+ _game->addBlocks( blocks );
+}
+
void Controller::loadMap( std::string filename )
{
- _map.loadBlocks();
+ loadBlocks();
+ MapLoader ml( &_game->getBlocks() );
std::ifstream mapFile( filename.c_str() );
- _map.loadMap( mapFile );
- _game->setMap( _map );
+ MapInfo mapinfo;
+ ml.loadMap( mapFile, mapinfo );
+ _game->setMap( mapinfo.map );
+ _game->setPos( mapinfo.startPos );
}
void Controller::generateMap()
{
- _map.loadBlocks();
- srand(time(0));
- _map.generateMap();
- _game->setMap( _map );
+ loadBlocks();
+ MapGenerator mg( &_game->getBlocks() );
+ MapInfo mapinfo;
+ mg.generate( mapinfo );
+ _game->setMap( mapinfo.map );
+ _game->setPos( mapinfo.startPos );
}
void Controller::initialize()
{
GLenum err = glewInit();
if (err != GLEW_OK)
throw std::runtime_error((const char*)glewGetErrorString(err));
if (!GLEW_VERSION_2_0)
throw std::runtime_error("Nead OpenGL >= 2.0 for shaders. Update your graphics drivers!");
_shaderProgram = createShaderProgram("shaders/shader.glslv", "shaders/shader.glslf");
_game->setShader( *_shaderProgram );
glClearColor( 0.2, 0.2, 0.2, 0 );
glClearDepth( 1.0 );
glDepthFunc( GL_LEQUAL );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
glEnable( GL_LINE_SMOOTH );
glHint( GL_LINE_SMOOTH_HINT, GL_NICEST );
-
- _map.optimize();
}
void Controller::resize( int width, int height )
{
glViewport( 0, 0, width, height );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
double fH = tan( 30.0 / 180.0 * 3.14159265358979323846 );
double fW = ( (double)width ) / ( (double)height ) * fH;
glFrustum( -fW, fW, -fH, fH, 1.0, 1000.0 );
glMatrixMode( GL_MODELVIEW );
_windowwidth = width;
_windowheight = height;
}
void Controller::draw()
{
glClear( GL_DEPTH_BUFFER_BIT );
// draw gradient background
glMatrixMode( GL_PROJECTION );
glPushMatrix();
glLoadIdentity();
glOrtho( 0, 1, 1, 0, -1, 1 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glDisable( GL_DEPTH_TEST );
glDisable( GL_BLEND );
glBegin( GL_QUADS );
glColor3f(0.1, 0.1, 0.1);
glVertex2f(0, 0);
glColor3f(0.15, 0.05, 0);
glVertex2f(0, 1);
glColor3f(0.15, 0.05, 0);
glVertex2f(1, 1);
glColor3f(0.1, 0.1, 0.1);
glVertex2f(1, 0);
glEnd();
glMatrixMode( GL_PROJECTION );
glPopMatrix();
glMatrixMode( GL_MODELVIEW );
glEnable( GL_DEPTH_TEST );
glEnable( GL_CULL_FACE );
glEnable( GL_BLEND );
glLoadIdentity();
glRotatef( _camrot, 1, 0, 0 );
glTranslated( 0.0, -_camy, -_camz );
_game->draw( _camz );
if ( _game->dead() )
{
glUseProgram(0);
_printer->print(
( boost::format( "%1% Distance Traveled: %2%" )
% _game->deathCause()
% _game->distanceTraveled() ).str(),
_windowwidth / 2, _windowheight / 4 * 3,
TextPrinter::ALIGN_CENTER
);
}
}
void Controller::update( int difference )
{
if ( _game->dead() )
return;
_game->update( difference );
}
diff --git a/src/controller.hpp b/src/controller.hpp
index 34c6d52..dac7a00 100644
--- a/src/controller.hpp
+++ b/src/controller.hpp
@@ -1,76 +1,76 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _CONTROLLER_HPP_
#define _CONTROLLER_HPP_
#include <memory>
#include "map.hpp"
#include "game.hpp"
class TextPrinter;
class ShaderProgram;
class Controller
{
public:
typedef void (*QuitCallback)();
Controller(
std::auto_ptr< Game > game
, double cameraheight, double cameradistance, double camerarotation
, QuitCallback cbQuit
, std::auto_ptr< TextPrinter > printer
);
~Controller();
enum {
JUMP_KEY = 1,
STRAFE_L_KEY = 2,
STRAFE_R_KEY = 3,
ACCEL_KEY = 4,
DECEL_KEY = 5,
QUIT_KEY = 6,
};
void keydown( int key );
void keyup( int key );
+ void loadBlocks();
void loadMap( std::string filename );
void generateMap();
void initialize();
void resize( int width, int height );
void draw();
void update( int difference );
private:
std::auto_ptr< Game > _game;
- Map _map;
double _camy, _camz, _camrot;
QuitCallback _quitcb;
std::auto_ptr< TextPrinter > _printer;
size_t _windowwidth, _windowheight;
std::auto_ptr< ShaderProgram > _shaderProgram;
};
#endif // _CONTROLLER_HPP_
diff --git a/src/game.cpp b/src/game.cpp
index f11eb11..3a4cd94 100644
--- a/src/game.cpp
+++ b/src/game.cpp
@@ -1,150 +1,152 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <cstdlib>
#include <ctime>
#include <cmath>
#include "shader.hpp"
#include "game.hpp"
Game::Game(
double acceleration, double strafespeed, double speedlimit
, double gravity, double jumpstrength
, ShaderProgram * shader
)
: _ship(), _map( 0 ), _shader( shader )
, _currAcc( 0 ), _maxAcc( acceleration )
, _currStrafe( 0 ), _maxStrafe( strafespeed )
, _maxSpeed( speedlimit ), _zspeed( 0 )
, _yapex( 0 ), _tapex( 0 ), _gravity( gravity )
, _jstrength( jumpstrength ), _grounded( true )
{
_ship.initialize();
_ship.pos().x = 0.5;
+ std::string empty;
+ _blocks.insert( empty, new Block() );
}
void Game::startJump()
{
if ( _grounded ||
_map->collide( AABB(
_ship.pos().offset(0, -0.2, 0),
_ship.pos().offset(0, -0.2, 0).offset(_ship.size())
) ) )
{
_yapex = _ship.ypos() + _jstrength;
_tapex = sqrt( _jstrength / _gravity );
}
}
void Game::draw( double zminClip )
{
_shader->use();
glPushMatrix();
glTranslated( _ship.xpos() - 0.5, _ship.ypos(), 0.0 );
glColor4f( 1, 0, 0, 0.25 );
_ship.drawDl();
glPopMatrix();
glColor3f( 0.8f, 1, 1 );
glTranslatef( -0.5, 0.0, _ship.zpos() );
_map->glDraw( _ship.zpos() - zminClip );
}
void Game::update( int difference )
{
double multiplier = ( (double)difference ) / 1000;
Vector3 newPos = _ship.pos();
AABB shipAabb(
Vector3( -_ship.size().x/2, 0, 0 ),
Vector3( _ship.size().x/2, _ship.size().y, _ship.size().z )
);
if ( _currAcc < -_maxAcc ) _currAcc = -_maxAcc;
else if ( _currAcc > _maxAcc ) _currAcc = _maxAcc;
_zspeed += _currAcc*multiplier;
if ( _zspeed < 0 ) _zspeed = 0;
if ( _zspeed > _maxSpeed ) _zspeed = _maxSpeed;
newPos.z += multiplier * _zspeed;
if ( _map->collide( shipAabb.offset( newPos ) ) )
{
newPos.z = _ship.pos().z;
_zspeed = 0;
}
else
_ship.pos().z = newPos.z;
if ( _currStrafe < -_maxStrafe ) _currStrafe = -_maxStrafe;
if ( _currStrafe > _maxStrafe ) _currStrafe = _maxStrafe;
if ( _currStrafe != 0 )
{
newPos.x += _currStrafe*multiplier;
if ( _map->collide( shipAabb.offset( newPos ) ) )
newPos.x = _ship.pos().x;
else
_ship.pos().x = newPos.x;
}
if ( _tapex <= 0 && _grounded )
{
_tapex = 0;
_yapex = _ship.pos().y;
}
_tapex -= multiplier;
newPos.y = _yapex - _gravity * ( _tapex*_tapex );
const Element * collision;
if ( ( collision = _map->collide( shipAabb.offset( newPos ) ) ) )
{
newPos.y = _ship.pos().y;
if (_tapex < 0) {
_grounded = true;
collision->trigger( *this );
}
_tapex = 0;
_yapex = _ship.pos().y;
}
else
{
_ship.pos().y = newPos.y;
_grounded = false;
}
if ( droppedOut() )
{
kill( "You dropped into the void!" );
}
}
void Game::suicide()
{
kill( "You committed suicide!" );
}
void Game::explode()
{
kill( "You exploded!" );
}
void Game::kill( const std::string & cause )
{
_death = cause;
}
diff --git a/src/game.hpp b/src/game.hpp
index 73df8b1..84048ff 100644
--- a/src/game.hpp
+++ b/src/game.hpp
@@ -1,74 +1,78 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _WORLD_HPP_
#define _WORLD_HPP_
#include "ship.hpp"
#include "map.hpp"
class ShaderProgram;
class Game
{
public:
Game(
double acceleration, double strafespeed, double speedlimit
, double gravity, double jumpstrength
, ShaderProgram * shader = 0
);
- void setMap(Map& map) throw() { _map = ↦ _ship.pos() = _map->startPoint(); }
+ void addBlocks(boost::ptr_map< std::string, Block >& blocks) { _blocks.transfer( blocks ); }
+ void setMap(std::auto_ptr<Map> map) throw() { _map = map; _map->optimize(); }
+ void setPos(const Vector3& pos) throw() { _ship.pos() = pos; }
void setShader(ShaderProgram& shader) throw() { _shader = &shader; }
+ const boost::ptr_map< std::string, Block >& getBlocks() { return _blocks; }
void setAcceleration( double accel ) { _currAcc = accel*_maxAcc; }
void setStrafe( double strafe ) { _currStrafe = strafe*_maxStrafe; }
void startJump();
void draw( double zminClip );
void update( int difference );
double distanceTraveled() const throw() { return _ship.pos().z; }
bool droppedOut() const throw() {
return _ship.pos().y < _map->lowestPoint() - 1;
}
void kill( const std::string & cause );
void suicide();
void explode();
bool dead() const throw() { return !_death.empty(); }
const std::string& deathCause() const { return _death; }
private:
+ boost::ptr_map< std::string, Block > _blocks;
Ship _ship;
- Map* _map;
+ std::auto_ptr< Map > _map;
ShaderProgram * _shader;
double _currAcc, _maxAcc;
double _currStrafe, _maxStrafe;
double _maxSpeed, _zspeed;
double _yapex, _tapex, _gravity;
double _jstrength;
bool _grounded;
std::string _death;
};
#endif // _WORLD_HPP_
diff --git a/src/map.cpp b/src/map.cpp
index 746d90b..95faba0 100644
--- a/src/map.cpp
+++ b/src/map.cpp
@@ -1,318 +1,64 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
-#include <boost/filesystem.hpp>
-#include <boost/filesystem/fstream.hpp>
#include <algorithm>
#include <functional>
#include <fstream>
#include <string>
#include <sstream>
#include <list>
#include <cctype>
#include "game.hpp"
#include "map.hpp"
Map::Map( size_t sectionSize )
: _accelerator( sectionSize )
{
- std::string empty;
- blocks.insert( empty, new Block() );
}
-void Map::glDraw( double )
+Map::Map( size_t sectionSize, std::vector< Element >& elements )
+ : _accelerator( sectionSize )
{
- for ( ElementList::iterator elem = elements.begin() ;
- elem != elements.end(); ++elem )
- {
- elem->glDraw();
- }
- _elementsDrawn = elements.size();
+ using std::swap;
+ swap ( elements, _elements );
}
-void Map::loadBlocks()
+void Map::glDraw( double )
{
- using namespace boost::filesystem;
- path block_dir( "blocks" );
- if ( !exists( block_dir ) )
- return;
- for ( recursive_directory_iterator block_fs_entry( block_dir ) ;
- block_fs_entry != recursive_directory_iterator() ;
- ++block_fs_entry )
+ for ( ElementList::iterator elem = _elements.begin() ;
+ elem != _elements.end(); ++elem )
{
- if ( is_directory( block_fs_entry->status() ) )
- continue;
- std::string block_path;
- path::iterator iter = block_fs_entry->path().begin();
- ++iter;
- if ( iter != block_fs_entry->path().end() )
- block_path = *iter;
- for ( ++iter ; iter != block_fs_entry->path().end() ; ++iter )
- block_path = block_path + "/" + *iter;
- blocks.insert( block_path, Block::fromFile( block_fs_entry->path().string() ) );
+ elem->glDraw();
}
+ _elementsDrawn = _elements.size();
}
void Map::optimize()
{
- for ( ElementList::iterator elem = elements.begin() ;
- elem != elements.end(); ++elem )
+ for ( ElementList::iterator elem = _elements.begin() ;
+ elem != _elements.end(); ++elem )
{
_accelerator.addElement( *elem );
}
}
const Element * Map::collide( const AABB& aabb )
{
return _accelerator.collide( aabb );
}
-
-void Map::generateMap()
-{
- _accelerator.clear();
- elements.clear();
- elements.push_back(Element(
- 0, -1, 0, 20, block( "" ), Vector3( 1, 1, 1 )
- ));
-
- size_t width = 7;
- size_t base = 0;
- std::vector< size_t > running(width, 0);
- running[width/2] = 20;
-
- for (size_t i = 0; i < 100; ++i)
- {
- size_t distance = rand()%18+8;
- size_t length = rand()%20+2;
- size_t col;
- do {
- col = rand()%width;
- } while (running[col] > 0);
- elements.push_back(Element(
- (int)col - ((int)width)/2,
- ((double)(rand() % 5))/4 - 0.5,
- base + distance,
- length,
- block( "" ),
- Vector3(
- ( (double)rand() ) / RAND_MAX,
- ( (double)rand() ) / RAND_MAX,
- ( (double)rand() ) / RAND_MAX
- )
- ));
- running[col] += distance + length;
- size_t mindist = distance + length;
- for (size_t j = 0; j < width; ++j)
- mindist = std::min(mindist, running[j]);
- for (size_t j = 0; j < width; ++j)
- running[j] -= mindist;
- base += mindist;
- }
- _startPoint = Vector3(0.5, 0, 0);
-}
-
-struct Row
-{
- std::string data;
- double start, length;
-};
-
-struct Column
-{
- char key;
- double start, length;
-};
-
-struct BlockPos
-{
- BlockPos() : block(0), ypos(0.0) { }
- const Block * block;
- double ypos;
- Element::TriggerFn tfn;
-};
-
-void parseAlias(
- std::istream& is
- , const boost::ptr_map< std::string, Block >& blocks
- , std::vector< std::list< BlockPos > >& aliases
- )
-{
- char key;
- is >> key;
- if ( key < 0 )
- throw std::runtime_error( std::string("Invalid alias name ") + key );
- BlockPos pos;
- std::string blockName;
- while ( is >> blockName )
- {
- if ( blocks.find( blockName ) == blocks.end() )
- throw std::runtime_error( "Unknown block " + blockName );
- else
- pos.block = blocks.find( blockName )->second;
-
- std::string tmp;
- if (!( is >> tmp ))
- throw std::runtime_error( "Unexpected end of line." );
- if (tmp.size() == 1 && std::isalpha(tmp[0]))
- {
- switch ( tmp[0] )
- {
- case 'd': pos.tfn = std::mem_fun_ref( &Game::explode ); break;
- default: pos.tfn = 0; break;
- }
- if (!( is >> tmp ))
- throw std::runtime_error( "Unexpected end of line." );
- }
- else
- pos.tfn = 0;
- std::istringstream( tmp ) >> pos.ypos;
-
- aliases[ key ].push_back( pos );
- }
-}
-
-void parseRow( size_t columns, const Row& row
- , std::vector< Column >& runningdata
- , const std::vector< std::list< BlockPos > >& aliases
- , std::vector< Element >& elements
- )
-{
- for (size_t i = 0; i < columns; ++i)
- {
- char key = ' ';
- if ( !row.data.empty() )
- {
- key = row.data[i];
- if ( key < 0 || ( key != ' ' && aliases[key].empty() ) )
- throw std::runtime_error( std::string("Invalid alias name ") + key );
- if ( key == runningdata[i].key )
- {
- runningdata[i].length += row.length;
- continue;
- }
- }
-
- if ( runningdata[i].key != ' ' )
- {
- for ( std::list< BlockPos >::const_iterator posIter = aliases[runningdata[i].key].begin();
- posIter != aliases[runningdata[i].key].end(); ++posIter)
- {
- elements.push_back(Element(
- ( (double)i ) - ( (double)columns ) / 2,
- posIter->ypos, runningdata[i].start, runningdata[i].length,
- posIter->block,
- Vector3(
- ( (double)rand() ) / RAND_MAX,
- ( (double)rand() ) / RAND_MAX,
- ( (double)rand() ) / RAND_MAX
- ),
- posIter->tfn
- ));
- }
- }
-
- if ( !row.data.empty() )
- {
- runningdata[i].key = key;
- runningdata[i].start = row.start;
- runningdata[i].length = row.length;
- }
- }
-}
-
-void parseMap( size_t columns
- , const std::vector< std::string >& maplines
- , const std::vector< std::list< BlockPos > >& aliases
- , std::vector< Element >& elements
- )
-{
- Column emptyColumn = { ' ', 0, 0 };
- Row row;
- std::vector< Column > runningdata(columns, emptyColumn);
- row.start = 0;
-
- for ( std::vector< std::string >::const_iterator mapiter = maplines.begin();
- mapiter != maplines.end(); ++mapiter )
- {
- const std::string& line = *mapiter;
- size_t seperator = line.find(':');
- if ( seperator == std::string::npos )
- throw std::runtime_error( "Missing seperator in map row." );
- if ( sscanf( line.substr(0, seperator).c_str(), " %lf ", &row.length ) != 1 )
- throw std::runtime_error( "Invalid row length in map row." );
- row.data = line.substr( seperator+1 );
- if ( row.data.length() > columns )
- throw std::runtime_error( "Bad row size." );
- else if ( row.data.length() < columns )
- row.data.resize( columns, ' ' );
- parseRow( columns, row, runningdata, aliases, elements );
- row.start += row.length;
- }
- row.data.clear();
- parseRow( columns, row, runningdata, aliases, elements );
-}
-
-void Map::loadMap( std::istream& is )
-{
- std::string line;
- std::vector< std::list< BlockPos > > aliases(256);
- std::vector< Element > newElements;
- size_t columns = 0;
- Vector3 startPoint = Vector3( 0.5, 0, 0 );
- std::vector< std::string > maplines;
-
- while ( std::getline( is, line ) )
- {
- std::istringstream iss( line );
- std::string cmd;
- if (!( iss >> cmd ))
- continue;
- else if ( cmd == "alias" )
- {
- parseAlias( iss, blocks, aliases );
- }
- else if ( cmd == "start" )
- {
- if (!( iss >> startPoint.x >> startPoint.y ))
- throw std::runtime_error( "Unexpected end of line in start coordinates." );
- }
- else if ( cmd == "map" )
- {
- std::string delim;
- if (!( iss >> columns ))
- throw std::runtime_error( "Unexpected end of line before map width." );
- if (!( iss >> delim ))
- throw std::runtime_error( "Unexpected end of line before map delim." );
- while ( is && std::getline( is, line ) && line != delim )
- maplines.push_back(line);
- if ( line != delim )
- throw std::runtime_error( "Unexpected eof during map block." );
- }
- }
-
- if ( maplines.empty() )
- throw std::runtime_error( "Missing/empty map block." );
-
- parseMap( columns, maplines, aliases, newElements );
-
- _accelerator.clear();
- using std::swap;
- swap( elements, newElements );
- _startPoint = startPoint;
-}
diff --git a/src/map.hpp b/src/map.hpp
index 7141287..a336096 100644
--- a/src/map.hpp
+++ b/src/map.hpp
@@ -1,72 +1,61 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _MAP_HPP_
#define _MAP_HPP_
#include <vector>
#include <istream>
#include <boost/ptr_container/ptr_map.hpp>
#include "element.hpp"
#include "aabb.hpp"
#include "collisionaccelerator.hpp"
class Map
{
public:
Map( size_t sectionSize );
+ Map( size_t sectionSize, std::vector< Element >& elements );
void glDraw( double zmin = 0 );
- void loadBlocks();
-
- void generateMap();
- void loadMap( std::istream& is );
void optimize();
- Block * block( const char * name ) { return &blocks.at( name ); }
-
// statistic functions
size_t elementsDrawn() const throw() { return _elementsDrawn; }
- size_t blocksLoaded() const throw() { return blocks.size(); }
double lowestPoint() const throw() { return -1; /* TODO: calculate */ }
- const Vector3& startPoint() const throw() { return _startPoint; }
// collide AABB with map.
// assumes aabb.size().z<sectionSize
const Element * collide( const AABB& aabb );
private:
CollisionAccelerator _accelerator;
typedef std::vector< Element > ElementList;
- ElementList elements;
+ ElementList _elements;
size_t _elementsDrawn; // for statistics
- boost::ptr_map< std::string, Block > blocks;
-
- Vector3 _startPoint;
-
};
#endif // _MAP_HPP_
diff --git a/src/mapgenerator.cpp b/src/mapgenerator.cpp
new file mode 100644
index 0000000..bc18ef4
--- /dev/null
+++ b/src/mapgenerator.cpp
@@ -0,0 +1,47 @@
+
+#include "mapgenerator.hpp"
+
+void MapGenerator::generate( MapInfo& mapinfo )
+{
+ std::vector< Element > elements;
+ elements.clear();
+ elements.push_back(Element(
+ 0, -1, 0, 20, &_blocks->at( "" ), Vector3( 1, 1, 1 )
+ ));
+
+ size_t width = 7;
+ size_t base = 0;
+ std::vector< size_t > running(width, 0);
+ running[width/2] = 20;
+
+ for (size_t i = 0; i < 100; ++i)
+ {
+ size_t distance = rand()%18+8;
+ size_t length = rand()%20+2;
+ size_t col;
+ do {
+ col = rand()%width;
+ } while (running[col] > 0);
+ elements.push_back(Element(
+ (int)col - ((int)width)/2,
+ ((double)(rand() % 5))/4 - 0.5,
+ base + distance,
+ length,
+ &_blocks->at( "" ),
+ Vector3(
+ ( (double)rand() ) / RAND_MAX,
+ ( (double)rand() ) / RAND_MAX,
+ ( (double)rand() ) / RAND_MAX
+ )
+ ));
+ running[col] += distance + length;
+ size_t mindist = distance + length;
+ for (size_t j = 0; j < width; ++j)
+ mindist = std::min(mindist, running[j]);
+ for (size_t j = 0; j < width; ++j)
+ running[j] -= mindist;
+ base += mindist;
+ }
+ mapinfo.map.reset( new Map( 10, elements ) );
+ mapinfo.startPos = Vector3(0.5, 0, 0);
+}
diff --git a/src/mapgenerator.hpp b/src/mapgenerator.hpp
new file mode 100644
index 0000000..050d0d9
--- /dev/null
+++ b/src/mapgenerator.hpp
@@ -0,0 +1,20 @@
+
+#include "maploader.hpp"
+
+class MapGenerator
+{
+
+public:
+
+ MapGenerator( const boost::ptr_map< std::string, Block > * blocks )
+ : _blocks( blocks )
+ {
+ }
+
+ void generate( MapInfo& mapinfo );
+
+private:
+
+ const boost::ptr_map< std::string, Block > * _blocks;
+
+};
diff --git a/src/maploader.cpp b/src/maploader.cpp
new file mode 100644
index 0000000..cc2777f
--- /dev/null
+++ b/src/maploader.cpp
@@ -0,0 +1,200 @@
+#include <cctype>
+#include <functional>
+#include <istream>
+#include <list>
+#include <sstream>
+#include <stdexcept>
+#include <string>
+#include <vector>
+#include "block.hpp"
+#include "element.hpp"
+#include "game.hpp"
+#include "maploader.hpp"
+
+struct Row
+{
+ std::string data;
+ double start, length;
+};
+
+struct Column
+{
+ char key;
+ double start, length;
+};
+
+struct BlockPos
+{
+ BlockPos() : block(0), ypos(0.0) { }
+ const Block * block;
+ double ypos;
+ Element::TriggerFn tfn;
+};
+
+void parseAlias(
+ std::istream& is
+ , const boost::ptr_map< std::string, Block >& blocks
+ , std::vector< std::list< BlockPos > >& aliases
+ )
+{
+ char key;
+ is >> key;
+ if ( key < 0 )
+ throw std::runtime_error( std::string("Invalid alias name ") + key );
+ BlockPos pos;
+ std::string blockName;
+ while ( is >> blockName )
+ {
+ if ( blocks.find( blockName ) == blocks.end() )
+ throw std::runtime_error( "Unknown block " + blockName );
+ else
+ pos.block = blocks.find( blockName )->second;
+
+ std::string tmp;
+ if (!( is >> tmp ))
+ throw std::runtime_error( "Unexpected end of line." );
+ if (tmp.size() == 1 && std::isalpha(tmp[0]))
+ {
+ switch ( tmp[0] )
+ {
+ case 'd': pos.tfn = std::mem_fun_ref( &Game::explode ); break;
+ default: pos.tfn = 0; break;
+ }
+ if (!( is >> tmp ))
+ throw std::runtime_error( "Unexpected end of line." );
+ }
+ else
+ pos.tfn = 0;
+ std::istringstream( tmp ) >> pos.ypos;
+
+ aliases[ key ].push_back( pos );
+ }
+}
+
+void parseRow( size_t columns, const Row& row
+ , std::vector< Column >& runningdata
+ , const std::vector< std::list< BlockPos > >& aliases
+ , std::vector< Element >& elements
+ )
+{
+ for (size_t i = 0; i < columns; ++i)
+ {
+ char key = ' ';
+ if ( !row.data.empty() )
+ {
+ key = row.data[i];
+ if ( key < 0 || ( key != ' ' && aliases[key].empty() ) )
+ throw std::runtime_error( std::string("Invalid alias name ") + key );
+ if ( key == runningdata[i].key )
+ {
+ runningdata[i].length += row.length;
+ continue;
+ }
+ }
+
+ if ( runningdata[i].key != ' ' )
+ {
+ for ( std::list< BlockPos >::const_iterator posIter = aliases[runningdata[i].key].begin();
+ posIter != aliases[runningdata[i].key].end(); ++posIter)
+ {
+ elements.push_back(Element(
+ ( (double)i ) - ( (double)columns ) / 2,
+ posIter->ypos, runningdata[i].start, runningdata[i].length,
+ posIter->block,
+ Vector3(
+ ( (double)rand() ) / RAND_MAX,
+ ( (double)rand() ) / RAND_MAX,
+ ( (double)rand() ) / RAND_MAX
+ ),
+ posIter->tfn
+ ));
+ }
+ }
+
+ if ( !row.data.empty() )
+ {
+ runningdata[i].key = key;
+ runningdata[i].start = row.start;
+ runningdata[i].length = row.length;
+ }
+ }
+}
+
+void parseMap( size_t columns
+ , const std::vector< std::string >& maplines
+ , const std::vector< std::list< BlockPos > >& aliases
+ , std::vector< Element >& elements
+ )
+{
+ Column emptyColumn = { ' ', 0, 0 };
+ Row row;
+ std::vector< Column > runningdata(columns, emptyColumn);
+ row.start = 0;
+
+ for ( std::vector< std::string >::const_iterator mapiter = maplines.begin();
+ mapiter != maplines.end(); ++mapiter )
+ {
+ const std::string& line = *mapiter;
+ size_t seperator = line.find(':');
+ if ( seperator == std::string::npos )
+ throw std::runtime_error( "Missing seperator in map row." );
+ if ( sscanf( line.substr(0, seperator).c_str(), " %lf ", &row.length ) != 1 )
+ throw std::runtime_error( "Invalid row length in map row." );
+ row.data = line.substr( seperator+1 );
+ if ( row.data.length() > columns )
+ throw std::runtime_error( "Bad row size." );
+ else if ( row.data.length() < columns )
+ row.data.resize( columns, ' ' );
+ parseRow( columns, row, runningdata, aliases, elements );
+ row.start += row.length;
+ }
+ row.data.clear();
+ parseRow( columns, row, runningdata, aliases, elements );
+}
+
+void MapLoader::loadMap( std::istream& is, MapInfo& mapinfo )
+{
+ std::string line;
+ std::vector< std::list< BlockPos > > aliases(256);
+ std::vector< Element > elements;
+ size_t columns = 0;
+ std::vector< std::string > maplines;
+ Vector3 startPos = Vector3( 0.5, 0, 0 );
+
+ while ( std::getline( is, line ) )
+ {
+ std::istringstream iss( line );
+ std::string cmd;
+ if (!( iss >> cmd ))
+ continue;
+ else if ( cmd == "alias" )
+ {
+ parseAlias( iss, *_blocks, aliases );
+ }
+ else if ( cmd == "start" )
+ {
+ if (!( iss >> startPos.x >> startPos.y ))
+ throw std::runtime_error( "Unexpected end of line in start coordinates." );
+ }
+ else if ( cmd == "map" )
+ {
+ std::string delim;
+ if (!( iss >> columns ))
+ throw std::runtime_error( "Unexpected end of line before map width." );
+ if (!( iss >> delim ))
+ throw std::runtime_error( "Unexpected end of line before map delim." );
+ while ( is && std::getline( is, line ) && line != delim )
+ maplines.push_back(line);
+ if ( line != delim )
+ throw std::runtime_error( "Unexpected eof during map block." );
+ }
+ }
+
+ if ( maplines.empty() )
+ throw std::runtime_error( "Missing/empty map block." );
+
+ parseMap( columns, maplines, aliases, elements );
+
+ mapinfo.map.reset( new Map( 10, elements ) );
+ mapinfo.startPos = startPos;
+}
diff --git a/src/maploader.hpp b/src/maploader.hpp
new file mode 100644
index 0000000..f627c1f
--- /dev/null
+++ b/src/maploader.hpp
@@ -0,0 +1,35 @@
+
+#ifndef _MAPLOADER_HPP_
+#define _MAPLOADER_HPP_
+
+#include <memory>
+#include <istream>
+#include <boost/ptr_container/ptr_map.hpp>
+#include "vector.hpp"
+#include "map.hpp"
+
+struct MapInfo
+{
+ std::auto_ptr< Map > map;
+ Vector3 startPos;
+};
+
+class MapLoader
+{
+
+public:
+
+ MapLoader( const boost::ptr_map< std::string, Block > * blocks )
+ : _blocks( blocks )
+ {
+ }
+
+ void loadMap( std::istream& is, MapInfo& mapinfo );
+
+private:
+
+ const boost::ptr_map< std::string, Block > * _blocks;
+
+};
+
+#endif // _MAPLOADER_HPP_
|
devnev/skyways
|
8b9adae3be119bea6620be6aa8e40f32c56137b4
|
Created seperate method to parse individual map rows.
|
diff --git a/src/map.cpp b/src/map.cpp
index ea48de1..746d90b 100644
--- a/src/map.cpp
+++ b/src/map.cpp
@@ -1,322 +1,318 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <algorithm>
#include <functional>
#include <fstream>
#include <string>
#include <sstream>
#include <list>
#include <cctype>
#include "game.hpp"
#include "map.hpp"
Map::Map( size_t sectionSize )
: _accelerator( sectionSize )
{
std::string empty;
blocks.insert( empty, new Block() );
}
void Map::glDraw( double )
{
for ( ElementList::iterator elem = elements.begin() ;
elem != elements.end(); ++elem )
{
elem->glDraw();
}
_elementsDrawn = elements.size();
}
void Map::loadBlocks()
{
using namespace boost::filesystem;
path block_dir( "blocks" );
if ( !exists( block_dir ) )
return;
for ( recursive_directory_iterator block_fs_entry( block_dir ) ;
block_fs_entry != recursive_directory_iterator() ;
++block_fs_entry )
{
if ( is_directory( block_fs_entry->status() ) )
continue;
std::string block_path;
path::iterator iter = block_fs_entry->path().begin();
++iter;
if ( iter != block_fs_entry->path().end() )
block_path = *iter;
for ( ++iter ; iter != block_fs_entry->path().end() ; ++iter )
block_path = block_path + "/" + *iter;
blocks.insert( block_path, Block::fromFile( block_fs_entry->path().string() ) );
}
}
void Map::optimize()
{
for ( ElementList::iterator elem = elements.begin() ;
elem != elements.end(); ++elem )
{
_accelerator.addElement( *elem );
}
}
const Element * Map::collide( const AABB& aabb )
{
return _accelerator.collide( aabb );
}
void Map::generateMap()
{
_accelerator.clear();
elements.clear();
elements.push_back(Element(
0, -1, 0, 20, block( "" ), Vector3( 1, 1, 1 )
));
size_t width = 7;
size_t base = 0;
std::vector< size_t > running(width, 0);
running[width/2] = 20;
for (size_t i = 0; i < 100; ++i)
{
size_t distance = rand()%18+8;
size_t length = rand()%20+2;
size_t col;
do {
col = rand()%width;
} while (running[col] > 0);
elements.push_back(Element(
(int)col - ((int)width)/2,
((double)(rand() % 5))/4 - 0.5,
base + distance,
length,
block( "" ),
Vector3(
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX
)
));
running[col] += distance + length;
size_t mindist = distance + length;
for (size_t j = 0; j < width; ++j)
mindist = std::min(mindist, running[j]);
for (size_t j = 0; j < width; ++j)
running[j] -= mindist;
base += mindist;
}
_startPoint = Vector3(0.5, 0, 0);
}
+struct Row
+{
+ std::string data;
+ double start, length;
+};
+
struct Column
{
char key;
double start, length;
};
struct BlockPos
{
BlockPos() : block(0), ypos(0.0) { }
const Block * block;
double ypos;
Element::TriggerFn tfn;
};
void parseAlias(
std::istream& is
, const boost::ptr_map< std::string, Block >& blocks
, std::vector< std::list< BlockPos > >& aliases
)
{
char key;
is >> key;
if ( key < 0 )
throw std::runtime_error( std::string("Invalid alias name ") + key );
BlockPos pos;
std::string blockName;
while ( is >> blockName )
{
if ( blocks.find( blockName ) == blocks.end() )
throw std::runtime_error( "Unknown block " + blockName );
else
pos.block = blocks.find( blockName )->second;
std::string tmp;
if (!( is >> tmp ))
throw std::runtime_error( "Unexpected end of line." );
if (tmp.size() == 1 && std::isalpha(tmp[0]))
{
switch ( tmp[0] )
{
case 'd': pos.tfn = std::mem_fun_ref( &Game::explode ); break;
default: pos.tfn = 0; break;
}
if (!( is >> tmp ))
throw std::runtime_error( "Unexpected end of line." );
}
else
pos.tfn = 0;
std::istringstream( tmp ) >> pos.ypos;
aliases[ key ].push_back( pos );
}
}
-void parseMap( size_t columns
- , const std::vector< std::string >& maplines
+void parseRow( size_t columns, const Row& row
+ , std::vector< Column >& runningdata
, const std::vector< std::list< BlockPos > >& aliases
, std::vector< Element >& elements
)
{
- Column emptyColumn = { ' ', 0, 0 };
- std::vector< Column > runningdata(columns, emptyColumn);
- double rowlength, position = 0.0;
-
- for ( std::vector< std::string >::const_iterator mapiter = maplines.begin();
- mapiter != maplines.end(); ++mapiter )
+ for (size_t i = 0; i < columns; ++i)
{
- const std::string& line = *mapiter;
- size_t seperator = line.find(':');
- if ( seperator == std::string::npos )
- throw std::runtime_error( "Missing seperator in map row." );
- if ( sscanf( line.substr(0, seperator).c_str(), " %lf ", &rowlength ) != 1 )
- throw std::runtime_error( "Invalid row length in map row." );
- std::string row = line.substr( seperator+1 );
- if ( row.length() > columns )
- throw std::runtime_error( "Bad row size." );
- else if ( row.length() < columns )
- row.resize( columns, ' ' );
- for (size_t i = 0; i < columns; ++i)
+ char key = ' ';
+ if ( !row.data.empty() )
{
- char key = row[i];
+ key = row.data[i];
if ( key < 0 || ( key != ' ' && aliases[key].empty() ) )
throw std::runtime_error( std::string("Invalid alias name ") + key );
if ( key == runningdata[i].key )
{
- runningdata[i].length += rowlength;
- }
- else
- {
- if ( runningdata[i].key != ' ' )
- {
- for ( std::list< BlockPos >::const_iterator posIter =
- aliases[runningdata[i].key].begin();
- posIter != aliases[runningdata[i].key].end();
- ++posIter)
- {
- elements.push_back(Element(
- ( (double)i ) - ( (double)columns ) / 2,
- posIter->ypos,
- runningdata[i].start,
- runningdata[i].length,
- posIter->block,
- Vector3(
- ( (double)rand() ) / RAND_MAX,
- ( (double)rand() ) / RAND_MAX,
- ( (double)rand() ) / RAND_MAX
- ),
- posIter->tfn
- ));
- }
- }
- runningdata[i].key = key;
- runningdata[i].start = position;
- runningdata[i].length = rowlength;
+ runningdata[i].length += row.length;
+ continue;
}
}
- position += rowlength;
- }
- for (size_t i = 0; i < columns; ++i)
- {
+
if ( runningdata[i].key != ' ' )
{
- for ( std::list< BlockPos >::const_iterator posIter =
- aliases[runningdata[i].key].begin();
- posIter != aliases[runningdata[i].key].end();
- ++posIter)
+ for ( std::list< BlockPos >::const_iterator posIter = aliases[runningdata[i].key].begin();
+ posIter != aliases[runningdata[i].key].end(); ++posIter)
{
elements.push_back(Element(
( (double)i ) - ( (double)columns ) / 2,
- posIter->ypos,
- runningdata[i].start,
- runningdata[i].length,
+ posIter->ypos, runningdata[i].start, runningdata[i].length,
posIter->block,
Vector3(
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX
),
posIter->tfn
));
}
}
+
+ if ( !row.data.empty() )
+ {
+ runningdata[i].key = key;
+ runningdata[i].start = row.start;
+ runningdata[i].length = row.length;
+ }
+ }
+}
+
+void parseMap( size_t columns
+ , const std::vector< std::string >& maplines
+ , const std::vector< std::list< BlockPos > >& aliases
+ , std::vector< Element >& elements
+ )
+{
+ Column emptyColumn = { ' ', 0, 0 };
+ Row row;
+ std::vector< Column > runningdata(columns, emptyColumn);
+ row.start = 0;
+
+ for ( std::vector< std::string >::const_iterator mapiter = maplines.begin();
+ mapiter != maplines.end(); ++mapiter )
+ {
+ const std::string& line = *mapiter;
+ size_t seperator = line.find(':');
+ if ( seperator == std::string::npos )
+ throw std::runtime_error( "Missing seperator in map row." );
+ if ( sscanf( line.substr(0, seperator).c_str(), " %lf ", &row.length ) != 1 )
+ throw std::runtime_error( "Invalid row length in map row." );
+ row.data = line.substr( seperator+1 );
+ if ( row.data.length() > columns )
+ throw std::runtime_error( "Bad row size." );
+ else if ( row.data.length() < columns )
+ row.data.resize( columns, ' ' );
+ parseRow( columns, row, runningdata, aliases, elements );
+ row.start += row.length;
}
+ row.data.clear();
+ parseRow( columns, row, runningdata, aliases, elements );
}
void Map::loadMap( std::istream& is )
{
std::string line;
std::vector< std::list< BlockPos > > aliases(256);
std::vector< Element > newElements;
size_t columns = 0;
Vector3 startPoint = Vector3( 0.5, 0, 0 );
std::vector< std::string > maplines;
while ( std::getline( is, line ) )
{
std::istringstream iss( line );
std::string cmd;
if (!( iss >> cmd ))
continue;
else if ( cmd == "alias" )
{
parseAlias( iss, blocks, aliases );
}
else if ( cmd == "start" )
{
if (!( iss >> startPoint.x >> startPoint.y ))
throw std::runtime_error( "Unexpected end of line in start coordinates." );
}
else if ( cmd == "map" )
{
std::string delim;
if (!( iss >> columns ))
throw std::runtime_error( "Unexpected end of line before map width." );
if (!( iss >> delim ))
throw std::runtime_error( "Unexpected end of line before map delim." );
while ( is && std::getline( is, line ) && line != delim )
maplines.push_back(line);
if ( line != delim )
throw std::runtime_error( "Unexpected eof during map block." );
}
}
if ( maplines.empty() )
throw std::runtime_error( "Missing/empty map block." );
parseMap( columns, maplines, aliases, newElements );
_accelerator.clear();
using std::swap;
swap( elements, newElements );
_startPoint = startPoint;
}
|
devnev/skyways
|
da88ae4e11e7a3e2a025067292b1302c5fd5c199
|
Seperated parsing map tiles out of loadMap method.
|
diff --git a/src/map.cpp b/src/map.cpp
index bfc55e2..ea48de1 100644
--- a/src/map.cpp
+++ b/src/map.cpp
@@ -1,313 +1,322 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <algorithm>
#include <functional>
#include <fstream>
#include <string>
#include <sstream>
#include <list>
#include <cctype>
#include "game.hpp"
#include "map.hpp"
Map::Map( size_t sectionSize )
: _accelerator( sectionSize )
{
std::string empty;
blocks.insert( empty, new Block() );
}
void Map::glDraw( double )
{
for ( ElementList::iterator elem = elements.begin() ;
elem != elements.end(); ++elem )
{
elem->glDraw();
}
_elementsDrawn = elements.size();
}
void Map::loadBlocks()
{
using namespace boost::filesystem;
path block_dir( "blocks" );
if ( !exists( block_dir ) )
return;
for ( recursive_directory_iterator block_fs_entry( block_dir ) ;
block_fs_entry != recursive_directory_iterator() ;
++block_fs_entry )
{
if ( is_directory( block_fs_entry->status() ) )
continue;
std::string block_path;
path::iterator iter = block_fs_entry->path().begin();
++iter;
if ( iter != block_fs_entry->path().end() )
block_path = *iter;
for ( ++iter ; iter != block_fs_entry->path().end() ; ++iter )
block_path = block_path + "/" + *iter;
blocks.insert( block_path, Block::fromFile( block_fs_entry->path().string() ) );
}
}
void Map::optimize()
{
for ( ElementList::iterator elem = elements.begin() ;
elem != elements.end(); ++elem )
{
_accelerator.addElement( *elem );
}
}
const Element * Map::collide( const AABB& aabb )
{
return _accelerator.collide( aabb );
}
void Map::generateMap()
{
_accelerator.clear();
elements.clear();
elements.push_back(Element(
0, -1, 0, 20, block( "" ), Vector3( 1, 1, 1 )
));
size_t width = 7;
size_t base = 0;
std::vector< size_t > running(width, 0);
running[width/2] = 20;
for (size_t i = 0; i < 100; ++i)
{
size_t distance = rand()%18+8;
size_t length = rand()%20+2;
size_t col;
do {
col = rand()%width;
} while (running[col] > 0);
elements.push_back(Element(
(int)col - ((int)width)/2,
((double)(rand() % 5))/4 - 0.5,
base + distance,
length,
block( "" ),
Vector3(
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX
)
));
running[col] += distance + length;
size_t mindist = distance + length;
for (size_t j = 0; j < width; ++j)
mindist = std::min(mindist, running[j]);
for (size_t j = 0; j < width; ++j)
running[j] -= mindist;
base += mindist;
}
_startPoint = Vector3(0.5, 0, 0);
}
struct Column
{
char key;
double start, length;
};
struct BlockPos
{
BlockPos() : block(0), ypos(0.0) { }
const Block * block;
double ypos;
Element::TriggerFn tfn;
};
void parseAlias(
std::istream& is
, const boost::ptr_map< std::string, Block >& blocks
, std::vector< std::list< BlockPos > >& aliases
)
{
char key;
is >> key;
if ( key < 0 )
throw std::runtime_error( std::string("Invalid alias name ") + key );
BlockPos pos;
std::string blockName;
while ( is >> blockName )
{
if ( blocks.find( blockName ) == blocks.end() )
throw std::runtime_error( "Unknown block " + blockName );
else
pos.block = blocks.find( blockName )->second;
std::string tmp;
if (!( is >> tmp ))
throw std::runtime_error( "Unexpected end of line." );
if (tmp.size() == 1 && std::isalpha(tmp[0]))
{
switch ( tmp[0] )
{
case 'd': pos.tfn = std::mem_fun_ref( &Game::explode ); break;
default: pos.tfn = 0; break;
}
if (!( is >> tmp ))
throw std::runtime_error( "Unexpected end of line." );
}
else
pos.tfn = 0;
std::istringstream( tmp ) >> pos.ypos;
aliases[ key ].push_back( pos );
}
}
-void Map::loadMap( std::istream& is )
+void parseMap( size_t columns
+ , const std::vector< std::string >& maplines
+ , const std::vector< std::list< BlockPos > >& aliases
+ , std::vector< Element >& elements
+ )
{
- std::string line;
- std::vector< std::list< BlockPos > > aliases(256);
- std::vector< Element > newElements;
- size_t columns = 0;
- Vector3 startPoint = Vector3( 0.5, 0, 0 );
- std::vector< std::string > maplines;
-
- while ( std::getline( is, line ) )
- {
- std::istringstream iss( line );
- std::string cmd;
- if (!( iss >> cmd ))
- continue;
- else if ( cmd == "alias" )
- {
- parseAlias( iss, blocks, aliases );
- }
- else if ( cmd == "start" )
- {
- if (!( iss >> startPoint.x >> startPoint.y ))
- throw std::runtime_error( "Unexpected end of line in start coordinates." );
- }
- else if ( cmd == "map" )
- {
- std::string delim;
- if (!( iss >> columns ))
- throw std::runtime_error( "Unexpected end of line before map width." );
- if (!( iss >> delim ))
- throw std::runtime_error( "Unexpected end of line before map delim." );
- while ( is && std::getline( is, line ) && line != delim )
- maplines.push_back(line);
- if ( line != delim )
- throw std::runtime_error( "Unexpected eof during map block." );
- }
- }
-
- if ( maplines.empty() )
- throw std::runtime_error( "Missing/empty map block." );
-
Column emptyColumn = { ' ', 0, 0 };
std::vector< Column > runningdata(columns, emptyColumn);
double rowlength, position = 0.0;
- for ( std::vector< std::string >::iterator mapiter = maplines.begin();
+ for ( std::vector< std::string >::const_iterator mapiter = maplines.begin();
mapiter != maplines.end(); ++mapiter )
{
const std::string& line = *mapiter;
size_t seperator = line.find(':');
if ( seperator == std::string::npos )
throw std::runtime_error( "Missing seperator in map row." );
if ( sscanf( line.substr(0, seperator).c_str(), " %lf ", &rowlength ) != 1 )
throw std::runtime_error( "Invalid row length in map row." );
std::string row = line.substr( seperator+1 );
if ( row.length() > columns )
throw std::runtime_error( "Bad row size." );
else if ( row.length() < columns )
row.resize( columns, ' ' );
for (size_t i = 0; i < columns; ++i)
{
char key = row[i];
if ( key < 0 || ( key != ' ' && aliases[key].empty() ) )
throw std::runtime_error( std::string("Invalid alias name ") + key );
if ( key == runningdata[i].key )
{
runningdata[i].length += rowlength;
}
else
{
if ( runningdata[i].key != ' ' )
{
- for ( std::list< BlockPos >::iterator posIter =
+ for ( std::list< BlockPos >::const_iterator posIter =
aliases[runningdata[i].key].begin();
posIter != aliases[runningdata[i].key].end();
++posIter)
{
- newElements.push_back(Element(
+ elements.push_back(Element(
( (double)i ) - ( (double)columns ) / 2,
posIter->ypos,
runningdata[i].start,
runningdata[i].length,
posIter->block,
Vector3(
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX
),
posIter->tfn
));
}
}
runningdata[i].key = key;
runningdata[i].start = position;
runningdata[i].length = rowlength;
}
}
position += rowlength;
}
for (size_t i = 0; i < columns; ++i)
{
if ( runningdata[i].key != ' ' )
{
- for ( std::list< BlockPos >::iterator posIter =
+ for ( std::list< BlockPos >::const_iterator posIter =
aliases[runningdata[i].key].begin();
posIter != aliases[runningdata[i].key].end();
++posIter)
{
- newElements.push_back(Element(
+ elements.push_back(Element(
( (double)i ) - ( (double)columns ) / 2,
posIter->ypos,
runningdata[i].start,
runningdata[i].length,
posIter->block,
Vector3(
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX
),
posIter->tfn
));
}
}
}
+}
+
+void Map::loadMap( std::istream& is )
+{
+ std::string line;
+ std::vector< std::list< BlockPos > > aliases(256);
+ std::vector< Element > newElements;
+ size_t columns = 0;
+ Vector3 startPoint = Vector3( 0.5, 0, 0 );
+ std::vector< std::string > maplines;
+
+ while ( std::getline( is, line ) )
+ {
+ std::istringstream iss( line );
+ std::string cmd;
+ if (!( iss >> cmd ))
+ continue;
+ else if ( cmd == "alias" )
+ {
+ parseAlias( iss, blocks, aliases );
+ }
+ else if ( cmd == "start" )
+ {
+ if (!( iss >> startPoint.x >> startPoint.y ))
+ throw std::runtime_error( "Unexpected end of line in start coordinates." );
+ }
+ else if ( cmd == "map" )
+ {
+ std::string delim;
+ if (!( iss >> columns ))
+ throw std::runtime_error( "Unexpected end of line before map width." );
+ if (!( iss >> delim ))
+ throw std::runtime_error( "Unexpected end of line before map delim." );
+ while ( is && std::getline( is, line ) && line != delim )
+ maplines.push_back(line);
+ if ( line != delim )
+ throw std::runtime_error( "Unexpected eof during map block." );
+ }
+ }
+
+ if ( maplines.empty() )
+ throw std::runtime_error( "Missing/empty map block." );
+
+ parseMap( columns, maplines, aliases, newElements );
_accelerator.clear();
using std::swap;
swap( elements, newElements );
_startPoint = startPoint;
}
|
devnev/skyways
|
dc44f62a7c921f19963ee4e5c611017ed0b7a324
|
Seperated alias parsing out of loadMap.
|
diff --git a/src/map.cpp b/src/map.cpp
index 4282ddf..bfc55e2 100644
--- a/src/map.cpp
+++ b/src/map.cpp
@@ -1,304 +1,313 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <algorithm>
#include <functional>
#include <fstream>
#include <string>
#include <sstream>
#include <list>
#include <cctype>
#include "game.hpp"
#include "map.hpp"
Map::Map( size_t sectionSize )
: _accelerator( sectionSize )
{
std::string empty;
blocks.insert( empty, new Block() );
}
void Map::glDraw( double )
{
for ( ElementList::iterator elem = elements.begin() ;
elem != elements.end(); ++elem )
{
elem->glDraw();
}
_elementsDrawn = elements.size();
}
void Map::loadBlocks()
{
using namespace boost::filesystem;
path block_dir( "blocks" );
if ( !exists( block_dir ) )
return;
for ( recursive_directory_iterator block_fs_entry( block_dir ) ;
block_fs_entry != recursive_directory_iterator() ;
++block_fs_entry )
{
if ( is_directory( block_fs_entry->status() ) )
continue;
std::string block_path;
path::iterator iter = block_fs_entry->path().begin();
++iter;
if ( iter != block_fs_entry->path().end() )
block_path = *iter;
for ( ++iter ; iter != block_fs_entry->path().end() ; ++iter )
block_path = block_path + "/" + *iter;
blocks.insert( block_path, Block::fromFile( block_fs_entry->path().string() ) );
}
}
void Map::optimize()
{
for ( ElementList::iterator elem = elements.begin() ;
elem != elements.end(); ++elem )
{
_accelerator.addElement( *elem );
}
}
const Element * Map::collide( const AABB& aabb )
{
return _accelerator.collide( aabb );
}
void Map::generateMap()
{
_accelerator.clear();
elements.clear();
elements.push_back(Element(
0, -1, 0, 20, block( "" ), Vector3( 1, 1, 1 )
));
size_t width = 7;
size_t base = 0;
std::vector< size_t > running(width, 0);
running[width/2] = 20;
for (size_t i = 0; i < 100; ++i)
{
size_t distance = rand()%18+8;
size_t length = rand()%20+2;
size_t col;
do {
col = rand()%width;
} while (running[col] > 0);
elements.push_back(Element(
(int)col - ((int)width)/2,
((double)(rand() % 5))/4 - 0.5,
base + distance,
length,
block( "" ),
Vector3(
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX
)
));
running[col] += distance + length;
size_t mindist = distance + length;
for (size_t j = 0; j < width; ++j)
mindist = std::min(mindist, running[j]);
for (size_t j = 0; j < width; ++j)
running[j] -= mindist;
base += mindist;
}
_startPoint = Vector3(0.5, 0, 0);
}
struct Column
{
char key;
double start, length;
};
struct BlockPos
{
BlockPos() : block(0), ypos(0.0) { }
const Block * block;
double ypos;
Element::TriggerFn tfn;
};
+void parseAlias(
+ std::istream& is
+ , const boost::ptr_map< std::string, Block >& blocks
+ , std::vector< std::list< BlockPos > >& aliases
+ )
+{
+ char key;
+ is >> key;
+ if ( key < 0 )
+ throw std::runtime_error( std::string("Invalid alias name ") + key );
+ BlockPos pos;
+ std::string blockName;
+ while ( is >> blockName )
+ {
+ if ( blocks.find( blockName ) == blocks.end() )
+ throw std::runtime_error( "Unknown block " + blockName );
+ else
+ pos.block = blocks.find( blockName )->second;
+
+ std::string tmp;
+ if (!( is >> tmp ))
+ throw std::runtime_error( "Unexpected end of line." );
+ if (tmp.size() == 1 && std::isalpha(tmp[0]))
+ {
+ switch ( tmp[0] )
+ {
+ case 'd': pos.tfn = std::mem_fun_ref( &Game::explode ); break;
+ default: pos.tfn = 0; break;
+ }
+ if (!( is >> tmp ))
+ throw std::runtime_error( "Unexpected end of line." );
+ }
+ else
+ pos.tfn = 0;
+ std::istringstream( tmp ) >> pos.ypos;
+
+ aliases[ key ].push_back( pos );
+ }
+}
+
void Map::loadMap( std::istream& is )
{
std::string line;
std::vector< std::list< BlockPos > > aliases(256);
std::vector< Element > newElements;
size_t columns = 0;
Vector3 startPoint = Vector3( 0.5, 0, 0 );
std::vector< std::string > maplines;
while ( std::getline( is, line ) )
{
std::istringstream iss( line );
std::string cmd;
if (!( iss >> cmd ))
continue;
else if ( cmd == "alias" )
{
- char key;
- iss >> key;
- if ( key < 0 )
- throw std::runtime_error( std::string("Invalid alias name ") + key );
- BlockPos pos;
- std::string blockName;
- while ( iss >> blockName )
- {
- if ( blocks.find( blockName ) == blocks.end() )
- throw std::runtime_error( "Unknown block " + blockName );
- else
- pos.block = blocks.find( blockName )->second;
-
- std::string tmp;
- if (!( iss >> tmp ))
- throw std::runtime_error( "Unexpected end of line." );
- if (tmp.size() == 1 && std::isalpha(tmp[0]))
- {
- switch ( tmp[0] )
- {
- case 'd': pos.tfn = std::mem_fun_ref( &Game::explode ); break;
- default: pos.tfn = 0; break;
- }
- if (!( iss >> tmp ))
- throw std::runtime_error( "Unexpected end of line." );
- }
- else
- pos.tfn = 0;
- std::istringstream( tmp ) >> pos.ypos;
-
- aliases[ key ].push_back( pos );
- }
+ parseAlias( iss, blocks, aliases );
}
else if ( cmd == "start" )
{
if (!( iss >> startPoint.x >> startPoint.y ))
throw std::runtime_error( "Unexpected end of line in start coordinates." );
}
else if ( cmd == "map" )
{
std::string delim;
if (!( iss >> columns ))
throw std::runtime_error( "Unexpected end of line before map width." );
if (!( iss >> delim ))
throw std::runtime_error( "Unexpected end of line before map delim." );
while ( is && std::getline( is, line ) && line != delim )
maplines.push_back(line);
if ( line != delim )
throw std::runtime_error( "Unexpected eof during map block." );
}
}
if ( maplines.empty() )
throw std::runtime_error( "Missing/empty map block." );
Column emptyColumn = { ' ', 0, 0 };
std::vector< Column > runningdata(columns, emptyColumn);
double rowlength, position = 0.0;
for ( std::vector< std::string >::iterator mapiter = maplines.begin();
mapiter != maplines.end(); ++mapiter )
{
const std::string& line = *mapiter;
size_t seperator = line.find(':');
if ( seperator == std::string::npos )
throw std::runtime_error( "Missing seperator in map row." );
if ( sscanf( line.substr(0, seperator).c_str(), " %lf ", &rowlength ) != 1 )
throw std::runtime_error( "Invalid row length in map row." );
std::string row = line.substr( seperator+1 );
if ( row.length() > columns )
throw std::runtime_error( "Bad row size." );
else if ( row.length() < columns )
row.resize( columns, ' ' );
for (size_t i = 0; i < columns; ++i)
{
char key = row[i];
if ( key < 0 || ( key != ' ' && aliases[key].empty() ) )
throw std::runtime_error( std::string("Invalid alias name ") + key );
if ( key == runningdata[i].key )
{
runningdata[i].length += rowlength;
}
else
{
if ( runningdata[i].key != ' ' )
{
for ( std::list< BlockPos >::iterator posIter =
aliases[runningdata[i].key].begin();
posIter != aliases[runningdata[i].key].end();
++posIter)
{
newElements.push_back(Element(
( (double)i ) - ( (double)columns ) / 2,
posIter->ypos,
runningdata[i].start,
runningdata[i].length,
posIter->block,
Vector3(
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX
),
posIter->tfn
));
}
}
runningdata[i].key = key;
runningdata[i].start = position;
runningdata[i].length = rowlength;
}
}
position += rowlength;
}
for (size_t i = 0; i < columns; ++i)
{
if ( runningdata[i].key != ' ' )
{
for ( std::list< BlockPos >::iterator posIter =
aliases[runningdata[i].key].begin();
posIter != aliases[runningdata[i].key].end();
++posIter)
{
newElements.push_back(Element(
( (double)i ) - ( (double)columns ) / 2,
posIter->ypos,
runningdata[i].start,
runningdata[i].length,
posIter->block,
Vector3(
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX
),
posIter->tfn
));
}
}
}
_accelerator.clear();
using std::swap;
swap( elements, newElements );
_startPoint = startPoint;
}
|
devnev/skyways
|
2c1f019d8ed3a74c974857fb321cab88b7c567e8
|
Fixed const-correctness in drawing methods.
|
diff --git a/src/block.cpp b/src/block.cpp
index d89335c..e222e5a 100644
--- a/src/block.cpp
+++ b/src/block.cpp
@@ -1,131 +1,131 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <GL/gl.h>
#include <stdexcept>
#include <sstream>
#include <fstream>
#include <string>
#include "objmodel.hpp"
#include "block.hpp"
-void Block::draw()
+void Block::draw() const
{
if (model.vertices.size() > 0)
{
glScalef( 1, 1, -1 );
model.draw();
glScalef( 1, 1, -1 );
}
else
{
glBegin( GL_QUADS );
glNormal3f( 0, 0, 1 );
glVertex3f( 0, 0, 0 );
glVertex3f( 1, 0, 0 );
glVertex3f( 1, 1, 0 );
glVertex3f( 0, 1, 0 );
glNormal3f( 1, 0, 0 );
glVertex3f( 1, 0, 0 );
glVertex3f( 1, 0, -1 );
glVertex3f( 1, 1, -1 );
glVertex3f( 1, 1, 0 );
glNormal3f( 0, 0, -1 );
glVertex3f( 1, 0, -1 );
glVertex3f( 0, 0, -1 );
glVertex3f( 0, 1, -1 );
glVertex3f( 1, 1, -1 );
glNormal3f( -1, 0, 0 );
glVertex3f( 0, 0, -1 );
glVertex3f( 0, 0, 0 );
glVertex3f( 0, 1, 0 );
glVertex3f( 0, 1, -1 );
glNormal3f( 0, -1, 0 );
glVertex3f( 0, 0, 0 );
glVertex3f( 0, 0, -1 );
glVertex3f( 1, 0, -1 );
glVertex3f( 1, 0, 0 );
glNormal3f( 0, 1, 0 );
glVertex3f( 0, 1, 0 );
glVertex3f( 1, 1, 0 );
glVertex3f( 1, 1, -1 );
glVertex3f( 0, 1, -1 );
glEnd();
}
}
-void Block::drawDl()
+void Block::drawDl() const
{
if ( _blockDl == 0 )
{
_blockDl = glGenLists( 1 );
glNewList( _blockDl, GL_COMPILE_AND_EXECUTE );
draw();
glEndList();
}
else
{
glCallList( _blockDl );
}
}
std::auto_ptr< Block > Block::fromFile( const std::string& filename )
{
std::auto_ptr< Block > block( new Block() );
ObjUnknownsList objunknowns;
loadObjModel( filename.c_str(), block->model, false, &objunknowns, "b\0" );
for ( ObjUnknownsList::iterator unknown = objunknowns.begin();
unknown != objunknowns.end(); ++unknown )
{
if ( unknown->first == "b" )
{
std::istringstream iss( unknown->second );
std::string cmd;
iss >> cmd;
AABB aabb;
iss >> aabb.p1.x >> aabb.p1.y >> aabb.p1.z
>> aabb.p2.x >> aabb.p2.y >> aabb.p2.z;
block->bounds.push_back( aabb );
}
}
return block;
}
bool Block::collide( const AABB& aabb ) const throw()
{
if ( model.vertices.size() == 0 )
{
return aabb.collide( AABB( Vector3( 0, 0, 0 ), Vector3( 1, 1, 1 ) ) );
}
for ( AabbList::const_iterator iter = bounds.begin();
iter != bounds.end(); ++iter )
{
if ( aabb.collide( *iter ) )
return true;
}
return false;
}
diff --git a/src/block.hpp b/src/block.hpp
index 665056d..1eeb21f 100644
--- a/src/block.hpp
+++ b/src/block.hpp
@@ -1,56 +1,56 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _BLOCK_HPP_
#define _BLOCK_HPP_
#include <memory>
#include <vector>
#include <istream>
#include <GL/gl.h>
#include "vector.hpp"
#include "model.hpp"
#include "aabb.hpp"
class Block
{
public:
Block() : _blockDl( 0 ) { }
- void draw();
- void drawDl();
+ void draw() const;
+ void drawDl() const;
static std::auto_ptr< Block > fromStream( std::istream& is );
static std::auto_ptr< Block > fromFile( const std::string& filename );
bool collide( const AABB& aabb ) const throw();
private:
Model model;
typedef std::vector< AABB > AabbList;
AabbList bounds;
- GLuint _blockDl;
+ mutable GLuint _blockDl;
};
#endif // _BLOCK_HPP_
diff --git a/src/element.hpp b/src/element.hpp
index ae75841..9388ef2 100644
--- a/src/element.hpp
+++ b/src/element.hpp
@@ -1,60 +1,60 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _ELEMENT_HPP_
#define _ELEMENT_HPP_
#include "block.hpp"
#include <boost/function.hpp>
class Game;
class Element
{
public:
typedef boost::function1<void, Game&> TriggerFn;
- Element( double x, double y, double z, double l, Block * b, const Vector3& color, TriggerFn trigger = 0 )
+ Element( double x, double y, double z, double l, const Block * b, const Vector3& color, TriggerFn trigger = 0 )
: _pos(Vector3( x, y, z)), _length( l ), _block( b ), _color( color ), _trigger( trigger )
{
}
void glDraw();
void trigger(Game& game) const { if (_trigger) _trigger(game); }
const Vector3& pos() const throw() { return _pos; }
double xoff() const throw() { return _pos.x; }
double yoff() const throw() { return _pos.y; }
double zoff() const throw() { return _pos.z; }
double length() const throw() { return _length; }
bool collide( const AABB& aabb ) const;
private:
Vector3 _pos;
double _length;
- Block * _block;
+ const Block * _block;
Vector3 _color;
TriggerFn _trigger;
};
#endif // _ELEMENT_HPP_
diff --git a/src/map.cpp b/src/map.cpp
index e197f4a..4282ddf 100644
--- a/src/map.cpp
+++ b/src/map.cpp
@@ -1,304 +1,304 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <algorithm>
#include <functional>
#include <fstream>
#include <string>
#include <sstream>
#include <list>
#include <cctype>
#include "game.hpp"
#include "map.hpp"
Map::Map( size_t sectionSize )
: _accelerator( sectionSize )
{
std::string empty;
blocks.insert( empty, new Block() );
}
void Map::glDraw( double )
{
for ( ElementList::iterator elem = elements.begin() ;
elem != elements.end(); ++elem )
{
elem->glDraw();
}
_elementsDrawn = elements.size();
}
void Map::loadBlocks()
{
using namespace boost::filesystem;
path block_dir( "blocks" );
if ( !exists( block_dir ) )
return;
for ( recursive_directory_iterator block_fs_entry( block_dir ) ;
block_fs_entry != recursive_directory_iterator() ;
++block_fs_entry )
{
if ( is_directory( block_fs_entry->status() ) )
continue;
std::string block_path;
path::iterator iter = block_fs_entry->path().begin();
++iter;
if ( iter != block_fs_entry->path().end() )
block_path = *iter;
for ( ++iter ; iter != block_fs_entry->path().end() ; ++iter )
block_path = block_path + "/" + *iter;
blocks.insert( block_path, Block::fromFile( block_fs_entry->path().string() ) );
}
}
void Map::optimize()
{
for ( ElementList::iterator elem = elements.begin() ;
elem != elements.end(); ++elem )
{
_accelerator.addElement( *elem );
}
}
const Element * Map::collide( const AABB& aabb )
{
return _accelerator.collide( aabb );
}
void Map::generateMap()
{
_accelerator.clear();
elements.clear();
elements.push_back(Element(
0, -1, 0, 20, block( "" ), Vector3( 1, 1, 1 )
));
size_t width = 7;
size_t base = 0;
std::vector< size_t > running(width, 0);
running[width/2] = 20;
for (size_t i = 0; i < 100; ++i)
{
size_t distance = rand()%18+8;
size_t length = rand()%20+2;
size_t col;
do {
col = rand()%width;
} while (running[col] > 0);
elements.push_back(Element(
(int)col - ((int)width)/2,
((double)(rand() % 5))/4 - 0.5,
base + distance,
length,
block( "" ),
Vector3(
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX
)
));
running[col] += distance + length;
size_t mindist = distance + length;
for (size_t j = 0; j < width; ++j)
mindist = std::min(mindist, running[j]);
for (size_t j = 0; j < width; ++j)
running[j] -= mindist;
base += mindist;
}
_startPoint = Vector3(0.5, 0, 0);
}
struct Column
{
char key;
double start, length;
};
struct BlockPos
{
BlockPos() : block(0), ypos(0.0) { }
- Block * block;
+ const Block * block;
double ypos;
Element::TriggerFn tfn;
};
void Map::loadMap( std::istream& is )
{
std::string line;
std::vector< std::list< BlockPos > > aliases(256);
std::vector< Element > newElements;
size_t columns = 0;
Vector3 startPoint = Vector3( 0.5, 0, 0 );
std::vector< std::string > maplines;
while ( std::getline( is, line ) )
{
std::istringstream iss( line );
std::string cmd;
if (!( iss >> cmd ))
continue;
else if ( cmd == "alias" )
{
char key;
iss >> key;
if ( key < 0 )
throw std::runtime_error( std::string("Invalid alias name ") + key );
BlockPos pos;
std::string blockName;
while ( iss >> blockName )
{
if ( blocks.find( blockName ) == blocks.end() )
throw std::runtime_error( "Unknown block " + blockName );
else
pos.block = blocks.find( blockName )->second;
std::string tmp;
if (!( iss >> tmp ))
throw std::runtime_error( "Unexpected end of line." );
if (tmp.size() == 1 && std::isalpha(tmp[0]))
{
switch ( tmp[0] )
{
case 'd': pos.tfn = std::mem_fun_ref( &Game::explode ); break;
default: pos.tfn = 0; break;
}
if (!( iss >> tmp ))
throw std::runtime_error( "Unexpected end of line." );
}
else
pos.tfn = 0;
std::istringstream( tmp ) >> pos.ypos;
aliases[ key ].push_back( pos );
}
}
else if ( cmd == "start" )
{
if (!( iss >> startPoint.x >> startPoint.y ))
throw std::runtime_error( "Unexpected end of line in start coordinates." );
}
else if ( cmd == "map" )
{
std::string delim;
if (!( iss >> columns ))
throw std::runtime_error( "Unexpected end of line before map width." );
if (!( iss >> delim ))
throw std::runtime_error( "Unexpected end of line before map delim." );
while ( is && std::getline( is, line ) && line != delim )
maplines.push_back(line);
if ( line != delim )
throw std::runtime_error( "Unexpected eof during map block." );
}
}
if ( maplines.empty() )
throw std::runtime_error( "Missing/empty map block." );
Column emptyColumn = { ' ', 0, 0 };
std::vector< Column > runningdata(columns, emptyColumn);
double rowlength, position = 0.0;
for ( std::vector< std::string >::iterator mapiter = maplines.begin();
mapiter != maplines.end(); ++mapiter )
{
const std::string& line = *mapiter;
size_t seperator = line.find(':');
if ( seperator == std::string::npos )
throw std::runtime_error( "Missing seperator in map row." );
if ( sscanf( line.substr(0, seperator).c_str(), " %lf ", &rowlength ) != 1 )
throw std::runtime_error( "Invalid row length in map row." );
std::string row = line.substr( seperator+1 );
if ( row.length() > columns )
throw std::runtime_error( "Bad row size." );
else if ( row.length() < columns )
row.resize( columns, ' ' );
for (size_t i = 0; i < columns; ++i)
{
char key = row[i];
if ( key < 0 || ( key != ' ' && aliases[key].empty() ) )
throw std::runtime_error( std::string("Invalid alias name ") + key );
if ( key == runningdata[i].key )
{
runningdata[i].length += rowlength;
}
else
{
if ( runningdata[i].key != ' ' )
{
for ( std::list< BlockPos >::iterator posIter =
aliases[runningdata[i].key].begin();
posIter != aliases[runningdata[i].key].end();
++posIter)
{
newElements.push_back(Element(
( (double)i ) - ( (double)columns ) / 2,
posIter->ypos,
runningdata[i].start,
runningdata[i].length,
posIter->block,
Vector3(
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX
),
posIter->tfn
));
}
}
runningdata[i].key = key;
runningdata[i].start = position;
runningdata[i].length = rowlength;
}
}
position += rowlength;
}
for (size_t i = 0; i < columns; ++i)
{
if ( runningdata[i].key != ' ' )
{
for ( std::list< BlockPos >::iterator posIter =
aliases[runningdata[i].key].begin();
posIter != aliases[runningdata[i].key].end();
++posIter)
{
newElements.push_back(Element(
( (double)i ) - ( (double)columns ) / 2,
posIter->ypos,
runningdata[i].start,
runningdata[i].length,
posIter->block,
Vector3(
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX
),
posIter->tfn
));
}
}
}
_accelerator.clear();
using std::swap;
swap( elements, newElements );
_startPoint = startPoint;
}
diff --git a/src/model.hpp b/src/model.hpp
index 417915a..e0d5a70 100644
--- a/src/model.hpp
+++ b/src/model.hpp
@@ -1,105 +1,105 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _MODEL_HPP_
#define _MODEL_HPP_
#include <vector>
#include <GL/gl.h>
#include "vector.hpp"
typedef struct
{
size_t ix[3];
} Triangle;
typedef struct
{
size_t ix[4];
} Quad;
template<size_t N>
struct Face
{
size_t vertices[N];
size_t normals[N];
bool valid()
{
for (size_t i = 0; i < N; ++i)
{
if ( vertices[i] == vertices[(i+1)%N] )
return false;
}
return true;
}
};
typedef struct
{
std::vector< Vector3 > vertices;
std::vector< Vector3 > normals;
std::vector< Face<3> > trifaces;
std::vector< Face<4> > quadfaces;
- void draw()
+ void draw() const
{
glBegin( GL_TRIANGLES );
for ( size_t i = 0; i < trifaces.size(); ++i )
drawFace( trifaces[i] );
glEnd();
glBegin( GL_QUADS );
for ( size_t i = 0; i < quadfaces.size(); ++i )
drawFace( quadfaces[i] );
glEnd();
}
private:
template<size_t N>
- void drawFace( Face<N>& face )
+ void drawFace( const Face<N>& face ) const
{
for ( size_t i = 0; i < N; ++i )
{
if ( normals.size() > 0 )
{
glNormal3d(
normals[face.normals[i]].x,
normals[face.normals[i]].y,
normals[face.normals[i]].z
);
}
glVertex3d(
vertices[face.vertices[i]].x,
vertices[face.vertices[i]].y,
vertices[face.vertices[i]].z
);
}
}
} Model;
#endif // _MODEL_HPP_
|
devnev/skyways
|
a9d4a2e26a82dfcb302ff89b72a023c6ce03206e
|
Store target block directly in BlockPos struct.
|
diff --git a/src/map.cpp b/src/map.cpp
index 2f6c82d..e197f4a 100644
--- a/src/map.cpp
+++ b/src/map.cpp
@@ -1,301 +1,304 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <algorithm>
#include <functional>
#include <fstream>
#include <string>
#include <sstream>
#include <list>
#include <cctype>
#include "game.hpp"
#include "map.hpp"
Map::Map( size_t sectionSize )
: _accelerator( sectionSize )
{
std::string empty;
blocks.insert( empty, new Block() );
}
void Map::glDraw( double )
{
for ( ElementList::iterator elem = elements.begin() ;
elem != elements.end(); ++elem )
{
elem->glDraw();
}
_elementsDrawn = elements.size();
}
void Map::loadBlocks()
{
using namespace boost::filesystem;
path block_dir( "blocks" );
if ( !exists( block_dir ) )
return;
for ( recursive_directory_iterator block_fs_entry( block_dir ) ;
block_fs_entry != recursive_directory_iterator() ;
++block_fs_entry )
{
if ( is_directory( block_fs_entry->status() ) )
continue;
std::string block_path;
path::iterator iter = block_fs_entry->path().begin();
++iter;
if ( iter != block_fs_entry->path().end() )
block_path = *iter;
for ( ++iter ; iter != block_fs_entry->path().end() ; ++iter )
block_path = block_path + "/" + *iter;
blocks.insert( block_path, Block::fromFile( block_fs_entry->path().string() ) );
}
}
void Map::optimize()
{
for ( ElementList::iterator elem = elements.begin() ;
elem != elements.end(); ++elem )
{
_accelerator.addElement( *elem );
}
}
const Element * Map::collide( const AABB& aabb )
{
return _accelerator.collide( aabb );
}
void Map::generateMap()
{
_accelerator.clear();
elements.clear();
elements.push_back(Element(
0, -1, 0, 20, block( "" ), Vector3( 1, 1, 1 )
));
size_t width = 7;
size_t base = 0;
std::vector< size_t > running(width, 0);
running[width/2] = 20;
for (size_t i = 0; i < 100; ++i)
{
size_t distance = rand()%18+8;
size_t length = rand()%20+2;
size_t col;
do {
col = rand()%width;
} while (running[col] > 0);
elements.push_back(Element(
(int)col - ((int)width)/2,
((double)(rand() % 5))/4 - 0.5,
base + distance,
length,
block( "" ),
Vector3(
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX
)
));
running[col] += distance + length;
size_t mindist = distance + length;
for (size_t j = 0; j < width; ++j)
mindist = std::min(mindist, running[j]);
for (size_t j = 0; j < width; ++j)
running[j] -= mindist;
base += mindist;
}
_startPoint = Vector3(0.5, 0, 0);
}
struct Column
{
char key;
double start, length;
};
struct BlockPos
{
- BlockPos() : block(), ypos(0.0) { }
- std::string block;
+ BlockPos() : block(0), ypos(0.0) { }
+ Block * block;
double ypos;
Element::TriggerFn tfn;
};
void Map::loadMap( std::istream& is )
{
std::string line;
std::vector< std::list< BlockPos > > aliases(256);
std::vector< Element > newElements;
size_t columns = 0;
Vector3 startPoint = Vector3( 0.5, 0, 0 );
std::vector< std::string > maplines;
while ( std::getline( is, line ) )
{
std::istringstream iss( line );
std::string cmd;
if (!( iss >> cmd ))
continue;
else if ( cmd == "alias" )
{
char key;
iss >> key;
if ( key < 0 )
throw std::runtime_error( std::string("Invalid alias name ") + key );
BlockPos pos;
- while ( iss >> pos.block )
+ std::string blockName;
+ while ( iss >> blockName )
{
- if ( blocks.find( pos.block ) == blocks.end() )
- throw std::runtime_error( "Unknown block " + pos.block );
+ if ( blocks.find( blockName ) == blocks.end() )
+ throw std::runtime_error( "Unknown block " + blockName );
+ else
+ pos.block = blocks.find( blockName )->second;
std::string tmp;
if (!( iss >> tmp ))
throw std::runtime_error( "Unexpected end of line." );
if (tmp.size() == 1 && std::isalpha(tmp[0]))
{
switch ( tmp[0] )
{
case 'd': pos.tfn = std::mem_fun_ref( &Game::explode ); break;
default: pos.tfn = 0; break;
}
if (!( iss >> tmp ))
throw std::runtime_error( "Unexpected end of line." );
}
else
pos.tfn = 0;
std::istringstream( tmp ) >> pos.ypos;
aliases[ key ].push_back( pos );
}
}
else if ( cmd == "start" )
{
if (!( iss >> startPoint.x >> startPoint.y ))
throw std::runtime_error( "Unexpected end of line in start coordinates." );
}
else if ( cmd == "map" )
{
std::string delim;
if (!( iss >> columns ))
throw std::runtime_error( "Unexpected end of line before map width." );
if (!( iss >> delim ))
throw std::runtime_error( "Unexpected end of line before map delim." );
while ( is && std::getline( is, line ) && line != delim )
maplines.push_back(line);
if ( line != delim )
throw std::runtime_error( "Unexpected eof during map block." );
}
}
if ( maplines.empty() )
throw std::runtime_error( "Missing/empty map block." );
Column emptyColumn = { ' ', 0, 0 };
std::vector< Column > runningdata(columns, emptyColumn);
double rowlength, position = 0.0;
for ( std::vector< std::string >::iterator mapiter = maplines.begin();
mapiter != maplines.end(); ++mapiter )
{
const std::string& line = *mapiter;
size_t seperator = line.find(':');
if ( seperator == std::string::npos )
throw std::runtime_error( "Missing seperator in map row." );
if ( sscanf( line.substr(0, seperator).c_str(), " %lf ", &rowlength ) != 1 )
throw std::runtime_error( "Invalid row length in map row." );
std::string row = line.substr( seperator+1 );
if ( row.length() > columns )
throw std::runtime_error( "Bad row size." );
else if ( row.length() < columns )
row.resize( columns, ' ' );
for (size_t i = 0; i < columns; ++i)
{
char key = row[i];
if ( key < 0 || ( key != ' ' && aliases[key].empty() ) )
throw std::runtime_error( std::string("Invalid alias name ") + key );
if ( key == runningdata[i].key )
{
runningdata[i].length += rowlength;
}
else
{
if ( runningdata[i].key != ' ' )
{
for ( std::list< BlockPos >::iterator posIter =
aliases[runningdata[i].key].begin();
posIter != aliases[runningdata[i].key].end();
++posIter)
{
newElements.push_back(Element(
( (double)i ) - ( (double)columns ) / 2,
posIter->ypos,
runningdata[i].start,
runningdata[i].length,
- blocks.find( posIter->block )->second,
+ posIter->block,
Vector3(
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX
),
posIter->tfn
));
}
}
runningdata[i].key = key;
runningdata[i].start = position;
runningdata[i].length = rowlength;
}
}
position += rowlength;
}
for (size_t i = 0; i < columns; ++i)
{
if ( runningdata[i].key != ' ' )
{
for ( std::list< BlockPos >::iterator posIter =
aliases[runningdata[i].key].begin();
posIter != aliases[runningdata[i].key].end();
++posIter)
{
newElements.push_back(Element(
( (double)i ) - ( (double)columns ) / 2,
posIter->ypos,
runningdata[i].start,
runningdata[i].length,
- blocks.find( posIter->block )->second,
+ posIter->block,
Vector3(
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX
),
posIter->tfn
));
}
}
}
_accelerator.clear();
using std::swap;
swap( elements, newElements );
_startPoint = startPoint;
}
|
devnev/skyways
|
3f782cd8d2d06e5052ce83b9d43f4a1e8504ef71
|
Simplified world file format to use command-like syntax.
|
diff --git a/src/map.cpp b/src/map.cpp
index 5628dab..2f6c82d 100644
--- a/src/map.cpp
+++ b/src/map.cpp
@@ -1,285 +1,301 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <algorithm>
#include <functional>
#include <fstream>
#include <string>
#include <sstream>
#include <list>
#include <cctype>
#include "game.hpp"
#include "map.hpp"
Map::Map( size_t sectionSize )
: _accelerator( sectionSize )
{
std::string empty;
blocks.insert( empty, new Block() );
}
void Map::glDraw( double )
{
for ( ElementList::iterator elem = elements.begin() ;
elem != elements.end(); ++elem )
{
elem->glDraw();
}
_elementsDrawn = elements.size();
}
void Map::loadBlocks()
{
using namespace boost::filesystem;
path block_dir( "blocks" );
if ( !exists( block_dir ) )
return;
for ( recursive_directory_iterator block_fs_entry( block_dir ) ;
block_fs_entry != recursive_directory_iterator() ;
++block_fs_entry )
{
if ( is_directory( block_fs_entry->status() ) )
continue;
std::string block_path;
path::iterator iter = block_fs_entry->path().begin();
++iter;
if ( iter != block_fs_entry->path().end() )
block_path = *iter;
for ( ++iter ; iter != block_fs_entry->path().end() ; ++iter )
block_path = block_path + "/" + *iter;
blocks.insert( block_path, Block::fromFile( block_fs_entry->path().string() ) );
}
}
void Map::optimize()
{
for ( ElementList::iterator elem = elements.begin() ;
elem != elements.end(); ++elem )
{
_accelerator.addElement( *elem );
}
}
const Element * Map::collide( const AABB& aabb )
{
return _accelerator.collide( aabb );
}
void Map::generateMap()
{
_accelerator.clear();
elements.clear();
elements.push_back(Element(
0, -1, 0, 20, block( "" ), Vector3( 1, 1, 1 )
));
size_t width = 7;
size_t base = 0;
std::vector< size_t > running(width, 0);
running[width/2] = 20;
for (size_t i = 0; i < 100; ++i)
{
size_t distance = rand()%18+8;
size_t length = rand()%20+2;
size_t col;
do {
col = rand()%width;
} while (running[col] > 0);
elements.push_back(Element(
(int)col - ((int)width)/2,
((double)(rand() % 5))/4 - 0.5,
base + distance,
length,
block( "" ),
Vector3(
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX
)
));
running[col] += distance + length;
size_t mindist = distance + length;
for (size_t j = 0; j < width; ++j)
mindist = std::min(mindist, running[j]);
for (size_t j = 0; j < width; ++j)
running[j] -= mindist;
base += mindist;
}
_startPoint = Vector3(0.5, 0, 0);
}
struct Column
{
char key;
double start, length;
};
struct BlockPos
{
BlockPos() : block(), ypos(0.0) { }
std::string block;
double ypos;
Element::TriggerFn tfn;
};
void Map::loadMap( std::istream& is )
{
std::string line;
std::vector< std::list< BlockPos > > aliases(256);
std::vector< Element > newElements;
+ size_t columns = 0;
+ Vector3 startPoint = Vector3( 0.5, 0, 0 );
+ std::vector< std::string > maplines;
while ( std::getline( is, line ) )
{
- if ( line == "%%" )
- break;
std::istringstream iss( line );
- char key;
- iss >> key;
- if ( key < 0 )
- throw std::runtime_error( std::string("Invalid alias name ") + key );
- BlockPos pos;
- while ( iss >> pos.block )
+ std::string cmd;
+ if (!( iss >> cmd ))
+ continue;
+ else if ( cmd == "alias" )
{
- if ( blocks.find( pos.block ) == blocks.end() )
- throw std::runtime_error( "Unknown block " + pos.block );
-
- std::string tmp;
- if (!( iss >> tmp ))
- throw std::runtime_error( "Unexpected end of line" );
- if (tmp.size() == 1 && std::isalpha(tmp[0]))
+ char key;
+ iss >> key;
+ if ( key < 0 )
+ throw std::runtime_error( std::string("Invalid alias name ") + key );
+ BlockPos pos;
+ while ( iss >> pos.block )
{
- switch ( tmp[0] )
+ if ( blocks.find( pos.block ) == blocks.end() )
+ throw std::runtime_error( "Unknown block " + pos.block );
+
+ std::string tmp;
+ if (!( iss >> tmp ))
+ throw std::runtime_error( "Unexpected end of line." );
+ if (tmp.size() == 1 && std::isalpha(tmp[0]))
{
- case 'd': pos.tfn = std::mem_fun_ref( &Game::explode ); break;
- default: pos.tfn = 0; break;
+ switch ( tmp[0] )
+ {
+ case 'd': pos.tfn = std::mem_fun_ref( &Game::explode ); break;
+ default: pos.tfn = 0; break;
+ }
+ if (!( iss >> tmp ))
+ throw std::runtime_error( "Unexpected end of line." );
}
- if (!( iss >> tmp ))
- throw std::runtime_error( "Unexpected end of line" );
- }
- else
- pos.tfn = 0;
- std::istringstream( tmp ) >> pos.ypos;
+ else
+ pos.tfn = 0;
+ std::istringstream( tmp ) >> pos.ypos;
- aliases[ key ].push_back( pos );
+ aliases[ key ].push_back( pos );
+ }
+ }
+ else if ( cmd == "start" )
+ {
+ if (!( iss >> startPoint.x >> startPoint.y ))
+ throw std::runtime_error( "Unexpected end of line in start coordinates." );
+ }
+ else if ( cmd == "map" )
+ {
+ std::string delim;
+ if (!( iss >> columns ))
+ throw std::runtime_error( "Unexpected end of line before map width." );
+ if (!( iss >> delim ))
+ throw std::runtime_error( "Unexpected end of line before map delim." );
+ while ( is && std::getline( is, line ) && line != delim )
+ maplines.push_back(line);
+ if ( line != delim )
+ throw std::runtime_error( "Unexpected eof during map block." );
}
}
- if ( !is || !std::getline( is, line ) )
- throw std::runtime_error( "Unexpected eof before map." );
- size_t columns;
- Vector3 startPoint;
- {
- std::istringstream iss( line );
- iss >> columns;
- if (!( iss >> startPoint.x >> startPoint.y ))
- startPoint = Vector3( 0.5, 0, 0 );
- }
+ if ( maplines.empty() )
+ throw std::runtime_error( "Missing/empty map block." );
Column emptyColumn = { ' ', 0, 0 };
-
std::vector< Column > runningdata(columns, emptyColumn);
-
double rowlength, position = 0.0;
- while ( std::getline( is, line ) )
+ for ( std::vector< std::string >::iterator mapiter = maplines.begin();
+ mapiter != maplines.end(); ++mapiter )
{
+ const std::string& line = *mapiter;
size_t seperator = line.find(':');
if ( seperator == std::string::npos )
throw std::runtime_error( "Missing seperator in map row." );
if ( sscanf( line.substr(0, seperator).c_str(), " %lf ", &rowlength ) != 1 )
throw std::runtime_error( "Invalid row length in map row." );
std::string row = line.substr( seperator+1 );
if ( row.length() > columns )
throw std::runtime_error( "Bad row size." );
else if ( row.length() < columns )
row.resize( columns, ' ' );
for (size_t i = 0; i < columns; ++i)
{
char key = row[i];
if ( key < 0 || ( key != ' ' && aliases[key].empty() ) )
throw std::runtime_error( std::string("Invalid alias name ") + key );
if ( key == runningdata[i].key )
{
runningdata[i].length += rowlength;
}
else
{
if ( runningdata[i].key != ' ' )
{
for ( std::list< BlockPos >::iterator posIter =
aliases[runningdata[i].key].begin();
posIter != aliases[runningdata[i].key].end();
++posIter)
{
newElements.push_back(Element(
( (double)i ) - ( (double)columns ) / 2,
posIter->ypos,
runningdata[i].start,
runningdata[i].length,
blocks.find( posIter->block )->second,
Vector3(
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX
),
posIter->tfn
));
}
}
runningdata[i].key = key;
runningdata[i].start = position;
runningdata[i].length = rowlength;
}
}
position += rowlength;
}
for (size_t i = 0; i < columns; ++i)
{
if ( runningdata[i].key != ' ' )
{
for ( std::list< BlockPos >::iterator posIter =
aliases[runningdata[i].key].begin();
posIter != aliases[runningdata[i].key].end();
++posIter)
{
newElements.push_back(Element(
( (double)i ) - ( (double)columns ) / 2,
posIter->ypos,
runningdata[i].start,
runningdata[i].length,
blocks.find( posIter->block )->second,
Vector3(
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX
),
posIter->tfn
));
}
}
}
_accelerator.clear();
using std::swap;
swap( elements, newElements );
_startPoint = startPoint;
}
diff --git a/world b/world
index 21717be..b1c1a10 100644
--- a/world
+++ b/world
@@ -1,26 +1,27 @@
-. flat 0
-_ cube -1
-e cube d -1
-- cube 0.25
-a tunnel 1.0
-o flat 0.75 tunnel 1.0
-b cube 1.5
-= cube 0 cube 2
-%%
-4 0.5 6
+alias . flat 0
+alias _ cube -1
+alias e cube d -1
+alias - cube 0.25
+alias a tunnel 1.0
+alias o flat 0.75 tunnel 1.0
+alias b cube 1.5
+alias = cube 0 cube 2
+start 0.5 6
+map 4 EOMAP
10 : _
30 : .
20 : .
10 :. -
15 : -
10 :. o
10 :e =
4 : b
4 : b_
2 : b
10 : _
10 :b
10 :b _
10 :
10 : _
10 : _
+EOMAP
|
devnev/skyways
|
d68aadaee7063565c14bbd6f6e3c1441a9b45d48
|
Fixed collision bug in AABB.
|
diff --git a/src/aabb.hpp b/src/aabb.hpp
index 097975b..010db39 100644
--- a/src/aabb.hpp
+++ b/src/aabb.hpp
@@ -1,66 +1,66 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _AABB_HPP_
#define _AABB_HPP_
struct AABB
{
AABB()
: p1(Vector3(0, 0, 0))
, p2(Vector3(0, 0, 0))
{
}
AABB(const Vector3& p1_, const Vector3& p2_)
: p1(p1_), p2(p2_)
{
}
AABB offset( const Vector3& d ) const throw()
{
return AABB(p1.offset(d), p2.offset(d));
}
AABB offset( double x, double y, double z ) const throw()
{
return AABB(p1.offset( x, y, z ), p2.offset( x, y, z ));
}
Vector3 size() const throw()
{
return Vector3(p2.x-p1.x, p2.y-p1.y, p2.z-p1.z);
}
bool collide(const AABB& other) const throw()
{
int c = 0;
- c |= (p1.x > other.p1.x && p1.x < other.p2.x) ? 0x01 : 0;
- c |= (p1.y > other.p1.y && p1.y < other.p2.y) ? 0x02 : 0;
- c |= (p1.z > other.p1.z && p1.z < other.p2.z) ? 0x04 : 0;
- c |= (p2.x > other.p1.x && p2.x < other.p2.x) ? 0x01 : 0;
- c |= (p2.y > other.p1.y && p2.y < other.p2.y) ? 0x02 : 0;
- c |= (p2.z > other.p1.z && p2.z < other.p2.z) ? 0x04 : 0;
+ c |= ((p1.x > other.p1.x && p1.x < other.p2.x) ? 0x01 : 0);
+ c |= ((p1.y > other.p1.y && p1.y < other.p2.y) ? 0x02 : 0);
+ c |= ((p1.z > other.p1.z && p1.z < other.p2.z) ? 0x04 : 0);
+ c |= ((p2.x > other.p1.x && p2.x < other.p2.x) ? 0x01 : 0);
+ c |= ((p2.y > other.p1.y && p2.y < other.p2.y) ? 0x02 : 0);
+ c |= ((p2.z > other.p1.z && p2.z < other.p2.z) ? 0x04 : 0);
return c == 0x07;
}
Vector3 p1, p2;
};
#endif // _AABB_HPP_
|
devnev/skyways
|
d5975953ecca437c5937c9b32c5bb23ac661706a
|
Implemented setting start coordinates in map description files.
|
diff --git a/src/controller.cpp b/src/controller.cpp
index 10f924f..f09deee 100644
--- a/src/controller.cpp
+++ b/src/controller.cpp
@@ -1,196 +1,197 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <GL/glew.h>
#include <GL/gl.h>
#include <boost/format.hpp>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include "textprinter.hpp"
#include "shader.hpp"
#include "controller.hpp"
Controller::Controller(
std::auto_ptr< Game > game
, double cameraheight, double cameradistance, double camerarotation
, Controller::QuitCallback cbQuit
, std::auto_ptr< TextPrinter > printer
)
: _game( game ), _map( 10 )
, _camy( cameraheight ), _camz( cameradistance ), _camrot( camerarotation )
, _quitcb( cbQuit ), _printer( printer )
, _windowwidth( 1 ), _windowheight( 1 )
{
- _game->setMap( _map );
}
Controller::~Controller()
{
}
void Controller::keydown( int key )
{
switch ( key )
{
case STRAFE_L_KEY: _game->setStrafe( -1 ); break;
case STRAFE_R_KEY: _game->setStrafe( 1 ); break;
case ACCEL_KEY: _game->setAcceleration( 1 ); break;
case DECEL_KEY: _game->setAcceleration( -1 ); break;
case JUMP_KEY: _game->startJump(); break;
case QUIT_KEY:
if ( _game->dead() )
{
_quitcb();
}
else
{
_game->suicide();
}
break;
}
}
void Controller::keyup( int key )
{
switch ( key )
{
case STRAFE_L_KEY:
_game->setStrafe( 0 );
break;
case STRAFE_R_KEY:
_game->setStrafe( 0 );
break;
case ACCEL_KEY:
_game->setAcceleration( 0 );
break;
case DECEL_KEY:
_game->setAcceleration( 0 );
break;
}
}
void Controller::loadMap( std::string filename )
{
_map.loadBlocks();
std::ifstream mapFile( filename.c_str() );
_map.loadMap( mapFile );
+ _game->setMap( _map );
}
void Controller::generateMap()
{
_map.loadBlocks();
srand(time(0));
_map.generateMap();
+ _game->setMap( _map );
}
void Controller::initialize()
{
GLenum err = glewInit();
if (err != GLEW_OK)
throw std::runtime_error((const char*)glewGetErrorString(err));
if (!GLEW_VERSION_2_0)
throw std::runtime_error("Nead OpenGL >= 2.0 for shaders. Update your graphics drivers!");
_shaderProgram = createShaderProgram("shaders/shader.glslv", "shaders/shader.glslf");
_game->setShader( *_shaderProgram );
glClearColor( 0.2, 0.2, 0.2, 0 );
glClearDepth( 1.0 );
glDepthFunc( GL_LEQUAL );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
glEnable( GL_LINE_SMOOTH );
glHint( GL_LINE_SMOOTH_HINT, GL_NICEST );
_map.optimize();
}
void Controller::resize( int width, int height )
{
glViewport( 0, 0, width, height );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
double fH = tan( 30.0 / 180.0 * 3.14159265358979323846 );
double fW = ( (double)width ) / ( (double)height ) * fH;
glFrustum( -fW, fW, -fH, fH, 1.0, 1000.0 );
glMatrixMode( GL_MODELVIEW );
_windowwidth = width;
_windowheight = height;
}
void Controller::draw()
{
glClear( GL_DEPTH_BUFFER_BIT );
// draw gradient background
glMatrixMode( GL_PROJECTION );
glPushMatrix();
glLoadIdentity();
glOrtho( 0, 1, 1, 0, -1, 1 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glDisable( GL_DEPTH_TEST );
glDisable( GL_BLEND );
glBegin( GL_QUADS );
glColor3f(0.1, 0.1, 0.1);
glVertex2f(0, 0);
glColor3f(0.15, 0.05, 0);
glVertex2f(0, 1);
glColor3f(0.15, 0.05, 0);
glVertex2f(1, 1);
glColor3f(0.1, 0.1, 0.1);
glVertex2f(1, 0);
glEnd();
glMatrixMode( GL_PROJECTION );
glPopMatrix();
glMatrixMode( GL_MODELVIEW );
glEnable( GL_DEPTH_TEST );
glEnable( GL_CULL_FACE );
glEnable( GL_BLEND );
glLoadIdentity();
glRotatef( _camrot, 1, 0, 0 );
glTranslated( 0.0, -_camy, -_camz );
_game->draw( _camz );
if ( _game->dead() )
{
glUseProgram(0);
_printer->print(
( boost::format( "%1% Distance Traveled: %2%" )
% _game->deathCause()
% _game->distanceTraveled() ).str(),
_windowwidth / 2, _windowheight / 4 * 3,
TextPrinter::ALIGN_CENTER
);
}
}
void Controller::update( int difference )
{
if ( _game->dead() )
return;
_game->update( difference );
}
diff --git a/src/game.hpp b/src/game.hpp
index 52c9e38..73df8b1 100644
--- a/src/game.hpp
+++ b/src/game.hpp
@@ -1,74 +1,74 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _WORLD_HPP_
#define _WORLD_HPP_
#include "ship.hpp"
#include "map.hpp"
class ShaderProgram;
class Game
{
public:
Game(
double acceleration, double strafespeed, double speedlimit
, double gravity, double jumpstrength
, ShaderProgram * shader = 0
);
- void setMap(Map& map) throw() { _map = ↦ }
+ void setMap(Map& map) throw() { _map = ↦ _ship.pos() = _map->startPoint(); }
void setShader(ShaderProgram& shader) throw() { _shader = &shader; }
void setAcceleration( double accel ) { _currAcc = accel*_maxAcc; }
void setStrafe( double strafe ) { _currStrafe = strafe*_maxStrafe; }
void startJump();
void draw( double zminClip );
void update( int difference );
double distanceTraveled() const throw() { return _ship.pos().z; }
bool droppedOut() const throw() {
return _ship.pos().y < _map->lowestPoint() - 1;
}
void kill( const std::string & cause );
void suicide();
void explode();
bool dead() const throw() { return !_death.empty(); }
const std::string& deathCause() const { return _death; }
private:
Ship _ship;
Map* _map;
ShaderProgram * _shader;
double _currAcc, _maxAcc;
double _currStrafe, _maxStrafe;
double _maxSpeed, _zspeed;
double _yapex, _tapex, _gravity;
double _jstrength;
bool _grounded;
std::string _death;
};
#endif // _WORLD_HPP_
diff --git a/src/map.cpp b/src/map.cpp
index b8ce14b..5628dab 100644
--- a/src/map.cpp
+++ b/src/map.cpp
@@ -1,280 +1,285 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <algorithm>
#include <functional>
#include <fstream>
#include <string>
#include <sstream>
#include <list>
#include <cctype>
#include "game.hpp"
#include "map.hpp"
Map::Map( size_t sectionSize )
: _accelerator( sectionSize )
{
std::string empty;
blocks.insert( empty, new Block() );
}
void Map::glDraw( double )
{
for ( ElementList::iterator elem = elements.begin() ;
elem != elements.end(); ++elem )
{
elem->glDraw();
}
_elementsDrawn = elements.size();
}
void Map::loadBlocks()
{
using namespace boost::filesystem;
path block_dir( "blocks" );
if ( !exists( block_dir ) )
return;
for ( recursive_directory_iterator block_fs_entry( block_dir ) ;
block_fs_entry != recursive_directory_iterator() ;
++block_fs_entry )
{
if ( is_directory( block_fs_entry->status() ) )
continue;
std::string block_path;
path::iterator iter = block_fs_entry->path().begin();
++iter;
if ( iter != block_fs_entry->path().end() )
block_path = *iter;
for ( ++iter ; iter != block_fs_entry->path().end() ; ++iter )
block_path = block_path + "/" + *iter;
blocks.insert( block_path, Block::fromFile( block_fs_entry->path().string() ) );
}
}
void Map::optimize()
{
for ( ElementList::iterator elem = elements.begin() ;
elem != elements.end(); ++elem )
{
_accelerator.addElement( *elem );
}
}
const Element * Map::collide( const AABB& aabb )
{
return _accelerator.collide( aabb );
}
void Map::generateMap()
{
_accelerator.clear();
elements.clear();
elements.push_back(Element(
0, -1, 0, 20, block( "" ), Vector3( 1, 1, 1 )
));
size_t width = 7;
size_t base = 0;
std::vector< size_t > running(width, 0);
running[width/2] = 20;
for (size_t i = 0; i < 100; ++i)
{
size_t distance = rand()%18+8;
size_t length = rand()%20+2;
size_t col;
do {
col = rand()%width;
} while (running[col] > 0);
elements.push_back(Element(
(int)col - ((int)width)/2,
((double)(rand() % 5))/4 - 0.5,
base + distance,
length,
block( "" ),
Vector3(
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX
)
));
running[col] += distance + length;
size_t mindist = distance + length;
for (size_t j = 0; j < width; ++j)
mindist = std::min(mindist, running[j]);
for (size_t j = 0; j < width; ++j)
running[j] -= mindist;
base += mindist;
}
+ _startPoint = Vector3(0.5, 0, 0);
}
struct Column
{
char key;
double start, length;
};
struct BlockPos
{
BlockPos() : block(), ypos(0.0) { }
std::string block;
double ypos;
Element::TriggerFn tfn;
};
void Map::loadMap( std::istream& is )
{
std::string line;
std::vector< std::list< BlockPos > > aliases(256);
std::vector< Element > newElements;
while ( std::getline( is, line ) )
{
if ( line == "%%" )
break;
std::istringstream iss( line );
char key;
iss >> key;
if ( key < 0 )
throw std::runtime_error( std::string("Invalid alias name ") + key );
BlockPos pos;
while ( iss >> pos.block )
{
if ( blocks.find( pos.block ) == blocks.end() )
throw std::runtime_error( "Unknown block " + pos.block );
std::string tmp;
if (!( iss >> tmp ))
throw std::runtime_error( "Unexpected end of line" );
if (tmp.size() == 1 && std::isalpha(tmp[0]))
{
switch ( tmp[0] )
{
case 'd': pos.tfn = std::mem_fun_ref( &Game::explode ); break;
default: pos.tfn = 0; break;
}
if (!( iss >> tmp ))
throw std::runtime_error( "Unexpected end of line" );
}
else
pos.tfn = 0;
std::istringstream( tmp ) >> pos.ypos;
aliases[ key ].push_back( pos );
}
}
if ( !is || !std::getline( is, line ) )
throw std::runtime_error( "Unexpected eof before map." );
size_t columns;
+ Vector3 startPoint;
{
std::istringstream iss( line );
iss >> columns;
+ if (!( iss >> startPoint.x >> startPoint.y ))
+ startPoint = Vector3( 0.5, 0, 0 );
}
Column emptyColumn = { ' ', 0, 0 };
std::vector< Column > runningdata(columns, emptyColumn);
double rowlength, position = 0.0;
while ( std::getline( is, line ) )
{
size_t seperator = line.find(':');
if ( seperator == std::string::npos )
throw std::runtime_error( "Missing seperator in map row." );
if ( sscanf( line.substr(0, seperator).c_str(), " %lf ", &rowlength ) != 1 )
throw std::runtime_error( "Invalid row length in map row." );
std::string row = line.substr( seperator+1 );
if ( row.length() > columns )
throw std::runtime_error( "Bad row size." );
else if ( row.length() < columns )
row.resize( columns, ' ' );
for (size_t i = 0; i < columns; ++i)
{
char key = row[i];
if ( key < 0 || ( key != ' ' && aliases[key].empty() ) )
throw std::runtime_error( std::string("Invalid alias name ") + key );
if ( key == runningdata[i].key )
{
runningdata[i].length += rowlength;
}
else
{
if ( runningdata[i].key != ' ' )
{
for ( std::list< BlockPos >::iterator posIter =
aliases[runningdata[i].key].begin();
posIter != aliases[runningdata[i].key].end();
++posIter)
{
newElements.push_back(Element(
( (double)i ) - ( (double)columns ) / 2,
posIter->ypos,
runningdata[i].start,
runningdata[i].length,
blocks.find( posIter->block )->second,
Vector3(
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX
),
posIter->tfn
));
}
}
runningdata[i].key = key;
runningdata[i].start = position;
runningdata[i].length = rowlength;
}
}
position += rowlength;
}
for (size_t i = 0; i < columns; ++i)
{
if ( runningdata[i].key != ' ' )
{
for ( std::list< BlockPos >::iterator posIter =
aliases[runningdata[i].key].begin();
posIter != aliases[runningdata[i].key].end();
++posIter)
{
newElements.push_back(Element(
( (double)i ) - ( (double)columns ) / 2,
posIter->ypos,
runningdata[i].start,
runningdata[i].length,
blocks.find( posIter->block )->second,
Vector3(
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX
),
posIter->tfn
));
}
}
}
_accelerator.clear();
using std::swap;
swap( elements, newElements );
+ _startPoint = startPoint;
}
diff --git a/src/map.hpp b/src/map.hpp
index dfcf958..7141287 100644
--- a/src/map.hpp
+++ b/src/map.hpp
@@ -1,69 +1,72 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _MAP_HPP_
#define _MAP_HPP_
#include <vector>
#include <istream>
#include <boost/ptr_container/ptr_map.hpp>
#include "element.hpp"
#include "aabb.hpp"
#include "collisionaccelerator.hpp"
class Map
{
public:
Map( size_t sectionSize );
void glDraw( double zmin = 0 );
void loadBlocks();
void generateMap();
void loadMap( std::istream& is );
void optimize();
Block * block( const char * name ) { return &blocks.at( name ); }
// statistic functions
size_t elementsDrawn() const throw() { return _elementsDrawn; }
size_t blocksLoaded() const throw() { return blocks.size(); }
double lowestPoint() const throw() { return -1; /* TODO: calculate */ }
+ const Vector3& startPoint() const throw() { return _startPoint; }
// collide AABB with map.
// assumes aabb.size().z<sectionSize
const Element * collide( const AABB& aabb );
private:
CollisionAccelerator _accelerator;
typedef std::vector< Element > ElementList;
ElementList elements;
size_t _elementsDrawn; // for statistics
boost::ptr_map< std::string, Block > blocks;
+ Vector3 _startPoint;
+
};
#endif // _MAP_HPP_
diff --git a/world b/world
index 8a82bf4..21717be 100644
--- a/world
+++ b/world
@@ -1,26 +1,26 @@
. flat 0
_ cube -1
e cube d -1
- cube 0.25
a tunnel 1.0
o flat 0.75 tunnel 1.0
b cube 1.5
= cube 0 cube 2
%%
-4
+4 0.5 6
10 : _
30 : .
20 : .
10 :. -
15 : -
10 :. o
10 :e =
4 : b
4 : b_
2 : b
10 : _
10 :b
10 :b _
10 :
10 : _
10 : _
|
devnev/skyways
|
a8833ed60e08296ab72dcfb157051c453a51707e
|
Added drawing of gradient background.
|
diff --git a/src/controller.cpp b/src/controller.cpp
index ff4f3ec..10f924f 100644
--- a/src/controller.cpp
+++ b/src/controller.cpp
@@ -1,186 +1,196 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <GL/glew.h>
#include <GL/gl.h>
#include <boost/format.hpp>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include "textprinter.hpp"
#include "shader.hpp"
#include "controller.hpp"
Controller::Controller(
std::auto_ptr< Game > game
, double cameraheight, double cameradistance, double camerarotation
, Controller::QuitCallback cbQuit
, std::auto_ptr< TextPrinter > printer
)
: _game( game ), _map( 10 )
, _camy( cameraheight ), _camz( cameradistance ), _camrot( camerarotation )
, _quitcb( cbQuit ), _printer( printer )
, _windowwidth( 1 ), _windowheight( 1 )
{
_game->setMap( _map );
}
Controller::~Controller()
{
}
void Controller::keydown( int key )
{
switch ( key )
{
case STRAFE_L_KEY: _game->setStrafe( -1 ); break;
case STRAFE_R_KEY: _game->setStrafe( 1 ); break;
case ACCEL_KEY: _game->setAcceleration( 1 ); break;
case DECEL_KEY: _game->setAcceleration( -1 ); break;
case JUMP_KEY: _game->startJump(); break;
case QUIT_KEY:
if ( _game->dead() )
{
_quitcb();
}
else
{
_game->suicide();
}
break;
}
}
void Controller::keyup( int key )
{
switch ( key )
{
case STRAFE_L_KEY:
_game->setStrafe( 0 );
break;
case STRAFE_R_KEY:
_game->setStrafe( 0 );
break;
case ACCEL_KEY:
_game->setAcceleration( 0 );
break;
case DECEL_KEY:
_game->setAcceleration( 0 );
break;
}
}
void Controller::loadMap( std::string filename )
{
_map.loadBlocks();
std::ifstream mapFile( filename.c_str() );
_map.loadMap( mapFile );
}
void Controller::generateMap()
{
_map.loadBlocks();
srand(time(0));
_map.generateMap();
}
void Controller::initialize()
{
GLenum err = glewInit();
if (err != GLEW_OK)
throw std::runtime_error((const char*)glewGetErrorString(err));
if (!GLEW_VERSION_2_0)
throw std::runtime_error("Nead OpenGL >= 2.0 for shaders. Update your graphics drivers!");
_shaderProgram = createShaderProgram("shaders/shader.glslv", "shaders/shader.glslf");
_game->setShader( *_shaderProgram );
glClearColor( 0.2, 0.2, 0.2, 0 );
glClearDepth( 1.0 );
- glEnable( GL_DEPTH_TEST );
glDepthFunc( GL_LEQUAL );
- glEnable( GL_CULL_FACE );
-
- glEnable( GL_LIGHTING );
- glShadeModel( GL_SMOOTH );
- glEnable( GL_COLOR_MATERIAL );
- glEnable( GL_NORMALIZE );
-
- glEnable( GL_BLEND );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
glEnable( GL_LINE_SMOOTH );
glHint( GL_LINE_SMOOTH_HINT, GL_NICEST );
- float ambient[] = { 0.2f, 0.2f, 0.2f, 1.0f };
- float diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f };
- float position[] = { 0.0f, 4.0f, -2.0f, 1.0f };
- glLightfv( GL_LIGHT1, GL_AMBIENT, ambient );
- glLightfv( GL_LIGHT1, GL_DIFFUSE, diffuse );
- glLightfv( GL_LIGHT1, GL_POSITION, position );
- glEnable( GL_LIGHT1 );
-
_map.optimize();
}
void Controller::resize( int width, int height )
{
glViewport( 0, 0, width, height );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
double fH = tan( 30.0 / 180.0 * 3.14159265358979323846 );
double fW = ( (double)width ) / ( (double)height ) * fH;
glFrustum( -fW, fW, -fH, fH, 1.0, 1000.0 );
glMatrixMode( GL_MODELVIEW );
_windowwidth = width;
_windowheight = height;
}
void Controller::draw()
{
- glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
+ glClear( GL_DEPTH_BUFFER_BIT );
+
+ // draw gradient background
+ glMatrixMode( GL_PROJECTION );
+ glPushMatrix();
+ glLoadIdentity();
+ glOrtho( 0, 1, 1, 0, -1, 1 );
+ glMatrixMode( GL_MODELVIEW );
+ glLoadIdentity();
+ glDisable( GL_DEPTH_TEST );
+ glDisable( GL_BLEND );
+ glBegin( GL_QUADS );
+ glColor3f(0.1, 0.1, 0.1);
+ glVertex2f(0, 0);
+ glColor3f(0.15, 0.05, 0);
+ glVertex2f(0, 1);
+ glColor3f(0.15, 0.05, 0);
+ glVertex2f(1, 1);
+ glColor3f(0.1, 0.1, 0.1);
+ glVertex2f(1, 0);
+ glEnd();
+ glMatrixMode( GL_PROJECTION );
+ glPopMatrix();
+ glMatrixMode( GL_MODELVIEW );
+
+ glEnable( GL_DEPTH_TEST );
+ glEnable( GL_CULL_FACE );
+ glEnable( GL_BLEND );
glLoadIdentity();
glRotatef( _camrot, 1, 0, 0 );
glTranslated( 0.0, -_camy, -_camz );
_game->draw( _camz );
if ( _game->dead() )
{
glUseProgram(0);
_printer->print(
( boost::format( "%1% Distance Traveled: %2%" )
% _game->deathCause()
% _game->distanceTraveled() ).str(),
_windowwidth / 2, _windowheight / 4 * 3,
TextPrinter::ALIGN_CENTER
);
}
}
void Controller::update( int difference )
{
if ( _game->dead() )
return;
_game->update( difference );
}
|
devnev/skyways
|
4563b1c450d8c91d2c9c8b92d2d5c55843d3c56a
|
Implemented death trigger.
|
diff --git a/src/element.hpp b/src/element.hpp
index 5b43bc6..ae75841 100644
--- a/src/element.hpp
+++ b/src/element.hpp
@@ -1,53 +1,60 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _ELEMENT_HPP_
#define _ELEMENT_HPP_
#include "block.hpp"
+#include <boost/function.hpp>
+
+class Game;
class Element
{
public:
- Element( double x, double y, double z, double l, Block * b, const Vector3& color )
- : _pos(Vector3( x, y, z)), _length( l ), _block( b ), _color( color )
+ typedef boost::function1<void, Game&> TriggerFn;
+
+ Element( double x, double y, double z, double l, Block * b, const Vector3& color, TriggerFn trigger = 0 )
+ : _pos(Vector3( x, y, z)), _length( l ), _block( b ), _color( color ), _trigger( trigger )
{
}
void glDraw();
+ void trigger(Game& game) const { if (_trigger) _trigger(game); }
const Vector3& pos() const throw() { return _pos; }
double xoff() const throw() { return _pos.x; }
double yoff() const throw() { return _pos.y; }
double zoff() const throw() { return _pos.z; }
double length() const throw() { return _length; }
bool collide( const AABB& aabb ) const;
private:
Vector3 _pos;
double _length;
Block * _block;
Vector3 _color;
+ TriggerFn _trigger;
};
#endif // _ELEMENT_HPP_
diff --git a/src/game.cpp b/src/game.cpp
index cc5a2b3..f11eb11 100644
--- a/src/game.cpp
+++ b/src/game.cpp
@@ -1,142 +1,150 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <cstdlib>
#include <ctime>
#include <cmath>
#include "shader.hpp"
#include "game.hpp"
Game::Game(
double acceleration, double strafespeed, double speedlimit
, double gravity, double jumpstrength
, ShaderProgram * shader
)
: _ship(), _map( 0 ), _shader( shader )
, _currAcc( 0 ), _maxAcc( acceleration )
, _currStrafe( 0 ), _maxStrafe( strafespeed )
, _maxSpeed( speedlimit ), _zspeed( 0 )
, _yapex( 0 ), _tapex( 0 ), _gravity( gravity )
, _jstrength( jumpstrength ), _grounded( true )
{
_ship.initialize();
_ship.pos().x = 0.5;
}
void Game::startJump()
{
if ( _grounded ||
_map->collide( AABB(
_ship.pos().offset(0, -0.2, 0),
_ship.pos().offset(0, -0.2, 0).offset(_ship.size())
) ) )
{
_yapex = _ship.ypos() + _jstrength;
_tapex = sqrt( _jstrength / _gravity );
}
}
void Game::draw( double zminClip )
{
_shader->use();
glPushMatrix();
glTranslated( _ship.xpos() - 0.5, _ship.ypos(), 0.0 );
glColor4f( 1, 0, 0, 0.25 );
_ship.drawDl();
glPopMatrix();
glColor3f( 0.8f, 1, 1 );
glTranslatef( -0.5, 0.0, _ship.zpos() );
_map->glDraw( _ship.zpos() - zminClip );
}
void Game::update( int difference )
{
double multiplier = ( (double)difference ) / 1000;
Vector3 newPos = _ship.pos();
AABB shipAabb(
Vector3( -_ship.size().x/2, 0, 0 ),
Vector3( _ship.size().x/2, _ship.size().y, _ship.size().z )
);
if ( _currAcc < -_maxAcc ) _currAcc = -_maxAcc;
else if ( _currAcc > _maxAcc ) _currAcc = _maxAcc;
_zspeed += _currAcc*multiplier;
if ( _zspeed < 0 ) _zspeed = 0;
if ( _zspeed > _maxSpeed ) _zspeed = _maxSpeed;
newPos.z += multiplier * _zspeed;
if ( _map->collide( shipAabb.offset( newPos ) ) )
{
newPos.z = _ship.pos().z;
_zspeed = 0;
}
else
_ship.pos().z = newPos.z;
if ( _currStrafe < -_maxStrafe ) _currStrafe = -_maxStrafe;
if ( _currStrafe > _maxStrafe ) _currStrafe = _maxStrafe;
if ( _currStrafe != 0 )
{
newPos.x += _currStrafe*multiplier;
if ( _map->collide( shipAabb.offset( newPos ) ) )
newPos.x = _ship.pos().x;
else
_ship.pos().x = newPos.x;
}
if ( _tapex <= 0 && _grounded )
{
_tapex = 0;
_yapex = _ship.pos().y;
}
_tapex -= multiplier;
newPos.y = _yapex - _gravity * ( _tapex*_tapex );
- if ( _map->collide( shipAabb.offset( newPos ) ) )
+ const Element * collision;
+ if ( ( collision = _map->collide( shipAabb.offset( newPos ) ) ) )
{
newPos.y = _ship.pos().y;
- if (_tapex < 0)
+ if (_tapex < 0) {
_grounded = true;
+ collision->trigger( *this );
+ }
_tapex = 0;
_yapex = _ship.pos().y;
}
else
{
_ship.pos().y = newPos.y;
_grounded = false;
}
if ( droppedOut() )
{
kill( "You dropped into the void!" );
}
}
void Game::suicide()
{
kill( "You committed suicide!" );
}
+void Game::explode()
+{
+ kill( "You exploded!" );
+}
+
void Game::kill( const std::string & cause )
{
_death = cause;
}
diff --git a/src/game.hpp b/src/game.hpp
index dacc6a1..52c9e38 100644
--- a/src/game.hpp
+++ b/src/game.hpp
@@ -1,73 +1,74 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _WORLD_HPP_
#define _WORLD_HPP_
#include "ship.hpp"
#include "map.hpp"
class ShaderProgram;
class Game
{
public:
Game(
double acceleration, double strafespeed, double speedlimit
, double gravity, double jumpstrength
, ShaderProgram * shader = 0
);
void setMap(Map& map) throw() { _map = ↦ }
void setShader(ShaderProgram& shader) throw() { _shader = &shader; }
void setAcceleration( double accel ) { _currAcc = accel*_maxAcc; }
void setStrafe( double strafe ) { _currStrafe = strafe*_maxStrafe; }
void startJump();
void draw( double zminClip );
void update( int difference );
double distanceTraveled() const throw() { return _ship.pos().z; }
bool droppedOut() const throw() {
return _ship.pos().y < _map->lowestPoint() - 1;
}
void kill( const std::string & cause );
void suicide();
+ void explode();
bool dead() const throw() { return !_death.empty(); }
const std::string& deathCause() const { return _death; }
private:
Ship _ship;
Map* _map;
ShaderProgram * _shader;
double _currAcc, _maxAcc;
double _currStrafe, _maxStrafe;
double _maxSpeed, _zspeed;
double _yapex, _tapex, _gravity;
double _jstrength;
bool _grounded;
std::string _death;
};
#endif // _WORLD_HPP_
diff --git a/src/map.cpp b/src/map.cpp
index 8c3cf52..b8ce14b 100644
--- a/src/map.cpp
+++ b/src/map.cpp
@@ -1,273 +1,280 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <algorithm>
#include <functional>
#include <fstream>
#include <string>
#include <sstream>
#include <list>
#include <cctype>
+#include "game.hpp"
#include "map.hpp"
Map::Map( size_t sectionSize )
: _accelerator( sectionSize )
{
std::string empty;
blocks.insert( empty, new Block() );
}
void Map::glDraw( double )
{
for ( ElementList::iterator elem = elements.begin() ;
elem != elements.end(); ++elem )
{
elem->glDraw();
}
_elementsDrawn = elements.size();
}
void Map::loadBlocks()
{
using namespace boost::filesystem;
path block_dir( "blocks" );
if ( !exists( block_dir ) )
return;
for ( recursive_directory_iterator block_fs_entry( block_dir ) ;
block_fs_entry != recursive_directory_iterator() ;
++block_fs_entry )
{
if ( is_directory( block_fs_entry->status() ) )
continue;
std::string block_path;
path::iterator iter = block_fs_entry->path().begin();
++iter;
if ( iter != block_fs_entry->path().end() )
block_path = *iter;
for ( ++iter ; iter != block_fs_entry->path().end() ; ++iter )
block_path = block_path + "/" + *iter;
blocks.insert( block_path, Block::fromFile( block_fs_entry->path().string() ) );
}
}
void Map::optimize()
{
for ( ElementList::iterator elem = elements.begin() ;
elem != elements.end(); ++elem )
{
_accelerator.addElement( *elem );
}
}
-bool Map::collide( const AABB& aabb )
+const Element * Map::collide( const AABB& aabb )
{
return _accelerator.collide( aabb );
}
void Map::generateMap()
{
_accelerator.clear();
elements.clear();
elements.push_back(Element(
0, -1, 0, 20, block( "" ), Vector3( 1, 1, 1 )
));
size_t width = 7;
size_t base = 0;
std::vector< size_t > running(width, 0);
running[width/2] = 20;
for (size_t i = 0; i < 100; ++i)
{
size_t distance = rand()%18+8;
size_t length = rand()%20+2;
size_t col;
do {
col = rand()%width;
} while (running[col] > 0);
elements.push_back(Element(
(int)col - ((int)width)/2,
((double)(rand() % 5))/4 - 0.5,
base + distance,
length,
block( "" ),
Vector3(
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX
)
));
running[col] += distance + length;
size_t mindist = distance + length;
for (size_t j = 0; j < width; ++j)
mindist = std::min(mindist, running[j]);
for (size_t j = 0; j < width; ++j)
running[j] -= mindist;
base += mindist;
}
}
struct Column
{
char key;
double start, length;
};
struct BlockPos
{
BlockPos() : block(), ypos(0.0) { }
std::string block;
double ypos;
- char flag;
+ Element::TriggerFn tfn;
};
void Map::loadMap( std::istream& is )
{
std::string line;
std::vector< std::list< BlockPos > > aliases(256);
std::vector< Element > newElements;
while ( std::getline( is, line ) )
{
if ( line == "%%" )
break;
std::istringstream iss( line );
char key;
iss >> key;
if ( key < 0 )
throw std::runtime_error( std::string("Invalid alias name ") + key );
BlockPos pos;
while ( iss >> pos.block )
{
if ( blocks.find( pos.block ) == blocks.end() )
throw std::runtime_error( "Unknown block " + pos.block );
std::string tmp;
if (!( iss >> tmp ))
throw std::runtime_error( "Unexpected end of line" );
if (tmp.size() == 1 && std::isalpha(tmp[0]))
{
- pos.flag = tmp[0];
+ switch ( tmp[0] )
+ {
+ case 'd': pos.tfn = std::mem_fun_ref( &Game::explode ); break;
+ default: pos.tfn = 0; break;
+ }
if (!( iss >> tmp ))
throw std::runtime_error( "Unexpected end of line" );
}
else
- pos.flag = 0;
+ pos.tfn = 0;
std::istringstream( tmp ) >> pos.ypos;
aliases[ key ].push_back( pos );
}
}
if ( !is || !std::getline( is, line ) )
throw std::runtime_error( "Unexpected eof before map." );
size_t columns;
{
std::istringstream iss( line );
iss >> columns;
}
Column emptyColumn = { ' ', 0, 0 };
std::vector< Column > runningdata(columns, emptyColumn);
double rowlength, position = 0.0;
while ( std::getline( is, line ) )
{
size_t seperator = line.find(':');
if ( seperator == std::string::npos )
throw std::runtime_error( "Missing seperator in map row." );
if ( sscanf( line.substr(0, seperator).c_str(), " %lf ", &rowlength ) != 1 )
throw std::runtime_error( "Invalid row length in map row." );
std::string row = line.substr( seperator+1 );
if ( row.length() > columns )
throw std::runtime_error( "Bad row size." );
else if ( row.length() < columns )
row.resize( columns, ' ' );
for (size_t i = 0; i < columns; ++i)
{
char key = row[i];
if ( key < 0 || ( key != ' ' && aliases[key].empty() ) )
throw std::runtime_error( std::string("Invalid alias name ") + key );
if ( key == runningdata[i].key )
{
runningdata[i].length += rowlength;
}
else
{
if ( runningdata[i].key != ' ' )
{
for ( std::list< BlockPos >::iterator posIter =
aliases[runningdata[i].key].begin();
posIter != aliases[runningdata[i].key].end();
++posIter)
{
newElements.push_back(Element(
( (double)i ) - ( (double)columns ) / 2,
posIter->ypos,
runningdata[i].start,
runningdata[i].length,
blocks.find( posIter->block )->second,
Vector3(
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX
- )
+ ),
+ posIter->tfn
));
}
}
runningdata[i].key = key;
runningdata[i].start = position;
runningdata[i].length = rowlength;
}
}
position += rowlength;
}
for (size_t i = 0; i < columns; ++i)
{
if ( runningdata[i].key != ' ' )
{
for ( std::list< BlockPos >::iterator posIter =
aliases[runningdata[i].key].begin();
posIter != aliases[runningdata[i].key].end();
++posIter)
{
newElements.push_back(Element(
( (double)i ) - ( (double)columns ) / 2,
posIter->ypos,
runningdata[i].start,
runningdata[i].length,
blocks.find( posIter->block )->second,
Vector3(
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX
- )
+ ),
+ posIter->tfn
));
}
}
}
_accelerator.clear();
using std::swap;
swap( elements, newElements );
}
diff --git a/src/map.hpp b/src/map.hpp
index 6cf0439..dfcf958 100644
--- a/src/map.hpp
+++ b/src/map.hpp
@@ -1,69 +1,69 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _MAP_HPP_
#define _MAP_HPP_
#include <vector>
#include <istream>
#include <boost/ptr_container/ptr_map.hpp>
#include "element.hpp"
#include "aabb.hpp"
#include "collisionaccelerator.hpp"
class Map
{
public:
Map( size_t sectionSize );
void glDraw( double zmin = 0 );
void loadBlocks();
void generateMap();
void loadMap( std::istream& is );
void optimize();
Block * block( const char * name ) { return &blocks.at( name ); }
// statistic functions
size_t elementsDrawn() const throw() { return _elementsDrawn; }
size_t blocksLoaded() const throw() { return blocks.size(); }
double lowestPoint() const throw() { return -1; /* TODO: calculate */ }
// collide AABB with map.
// assumes aabb.size().z<sectionSize
- bool collide( const AABB& aabb );
+ const Element * collide( const AABB& aabb );
private:
CollisionAccelerator _accelerator;
typedef std::vector< Element > ElementList;
ElementList elements;
size_t _elementsDrawn; // for statistics
boost::ptr_map< std::string, Block > blocks;
};
#endif // _MAP_HPP_
diff --git a/world b/world
index 65072a0..8a82bf4 100644
--- a/world
+++ b/world
@@ -1,23 +1,26 @@
. flat 0
_ cube -1
+e cube d -1
- cube 0.25
a tunnel 1.0
o flat 0.75 tunnel 1.0
b cube 1.5
= cube 0 cube 2
%%
4
10 : _
30 : .
20 : .
10 :. -
15 : -
10 :. o
-10 :_ =
-10 : b
+10 :e =
+4 : b
+4 : b_
+2 : b
10 : _
10 :b
10 :b _
10 :
10 : _
10 : _
|
devnev/skyways
|
be3e3fb6324b12ee18d61259b4f3cefc69b89304
|
Moved suicide message into game class.
|
diff --git a/src/controller.cpp b/src/controller.cpp
index cc0a1a5..ff4f3ec 100644
--- a/src/controller.cpp
+++ b/src/controller.cpp
@@ -1,186 +1,186 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <GL/glew.h>
#include <GL/gl.h>
#include <boost/format.hpp>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include "textprinter.hpp"
#include "shader.hpp"
#include "controller.hpp"
Controller::Controller(
std::auto_ptr< Game > game
, double cameraheight, double cameradistance, double camerarotation
, Controller::QuitCallback cbQuit
, std::auto_ptr< TextPrinter > printer
)
: _game( game ), _map( 10 )
, _camy( cameraheight ), _camz( cameradistance ), _camrot( camerarotation )
, _quitcb( cbQuit ), _printer( printer )
, _windowwidth( 1 ), _windowheight( 1 )
{
_game->setMap( _map );
}
Controller::~Controller()
{
}
void Controller::keydown( int key )
{
switch ( key )
{
case STRAFE_L_KEY: _game->setStrafe( -1 ); break;
case STRAFE_R_KEY: _game->setStrafe( 1 ); break;
case ACCEL_KEY: _game->setAcceleration( 1 ); break;
case DECEL_KEY: _game->setAcceleration( -1 ); break;
case JUMP_KEY: _game->startJump(); break;
case QUIT_KEY:
if ( _game->dead() )
{
_quitcb();
}
else
{
- _game->kill( "You committed suicide!" );
+ _game->suicide();
}
break;
}
}
void Controller::keyup( int key )
{
switch ( key )
{
case STRAFE_L_KEY:
_game->setStrafe( 0 );
break;
case STRAFE_R_KEY:
_game->setStrafe( 0 );
break;
case ACCEL_KEY:
_game->setAcceleration( 0 );
break;
case DECEL_KEY:
_game->setAcceleration( 0 );
break;
}
}
void Controller::loadMap( std::string filename )
{
_map.loadBlocks();
std::ifstream mapFile( filename.c_str() );
_map.loadMap( mapFile );
}
void Controller::generateMap()
{
_map.loadBlocks();
srand(time(0));
_map.generateMap();
}
void Controller::initialize()
{
GLenum err = glewInit();
if (err != GLEW_OK)
throw std::runtime_error((const char*)glewGetErrorString(err));
if (!GLEW_VERSION_2_0)
throw std::runtime_error("Nead OpenGL >= 2.0 for shaders. Update your graphics drivers!");
_shaderProgram = createShaderProgram("shaders/shader.glslv", "shaders/shader.glslf");
_game->setShader( *_shaderProgram );
glClearColor( 0.2, 0.2, 0.2, 0 );
glClearDepth( 1.0 );
glEnable( GL_DEPTH_TEST );
glDepthFunc( GL_LEQUAL );
glEnable( GL_CULL_FACE );
glEnable( GL_LIGHTING );
glShadeModel( GL_SMOOTH );
glEnable( GL_COLOR_MATERIAL );
glEnable( GL_NORMALIZE );
glEnable( GL_BLEND );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
glEnable( GL_LINE_SMOOTH );
glHint( GL_LINE_SMOOTH_HINT, GL_NICEST );
float ambient[] = { 0.2f, 0.2f, 0.2f, 1.0f };
float diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f };
float position[] = { 0.0f, 4.0f, -2.0f, 1.0f };
glLightfv( GL_LIGHT1, GL_AMBIENT, ambient );
glLightfv( GL_LIGHT1, GL_DIFFUSE, diffuse );
glLightfv( GL_LIGHT1, GL_POSITION, position );
glEnable( GL_LIGHT1 );
_map.optimize();
}
void Controller::resize( int width, int height )
{
glViewport( 0, 0, width, height );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
double fH = tan( 30.0 / 180.0 * 3.14159265358979323846 );
double fW = ( (double)width ) / ( (double)height ) * fH;
glFrustum( -fW, fW, -fH, fH, 1.0, 1000.0 );
glMatrixMode( GL_MODELVIEW );
_windowwidth = width;
_windowheight = height;
}
void Controller::draw()
{
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glLoadIdentity();
glRotatef( _camrot, 1, 0, 0 );
glTranslated( 0.0, -_camy, -_camz );
_game->draw( _camz );
if ( _game->dead() )
{
glUseProgram(0);
_printer->print(
( boost::format( "%1% Distance Traveled: %2%" )
% _game->deathCause()
% _game->distanceTraveled() ).str(),
_windowwidth / 2, _windowheight / 4 * 3,
TextPrinter::ALIGN_CENTER
);
}
}
void Controller::update( int difference )
{
if ( _game->dead() )
return;
_game->update( difference );
}
diff --git a/src/game.cpp b/src/game.cpp
index e763632..cc5a2b3 100644
--- a/src/game.cpp
+++ b/src/game.cpp
@@ -1,137 +1,142 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <cstdlib>
#include <ctime>
#include <cmath>
#include "shader.hpp"
#include "game.hpp"
Game::Game(
double acceleration, double strafespeed, double speedlimit
, double gravity, double jumpstrength
, ShaderProgram * shader
)
: _ship(), _map( 0 ), _shader( shader )
, _currAcc( 0 ), _maxAcc( acceleration )
, _currStrafe( 0 ), _maxStrafe( strafespeed )
, _maxSpeed( speedlimit ), _zspeed( 0 )
, _yapex( 0 ), _tapex( 0 ), _gravity( gravity )
, _jstrength( jumpstrength ), _grounded( true )
{
_ship.initialize();
_ship.pos().x = 0.5;
}
void Game::startJump()
{
if ( _grounded ||
_map->collide( AABB(
_ship.pos().offset(0, -0.2, 0),
_ship.pos().offset(0, -0.2, 0).offset(_ship.size())
) ) )
{
_yapex = _ship.ypos() + _jstrength;
_tapex = sqrt( _jstrength / _gravity );
}
}
void Game::draw( double zminClip )
{
_shader->use();
glPushMatrix();
glTranslated( _ship.xpos() - 0.5, _ship.ypos(), 0.0 );
glColor4f( 1, 0, 0, 0.25 );
_ship.drawDl();
glPopMatrix();
glColor3f( 0.8f, 1, 1 );
glTranslatef( -0.5, 0.0, _ship.zpos() );
_map->glDraw( _ship.zpos() - zminClip );
}
void Game::update( int difference )
{
double multiplier = ( (double)difference ) / 1000;
Vector3 newPos = _ship.pos();
AABB shipAabb(
Vector3( -_ship.size().x/2, 0, 0 ),
Vector3( _ship.size().x/2, _ship.size().y, _ship.size().z )
);
if ( _currAcc < -_maxAcc ) _currAcc = -_maxAcc;
else if ( _currAcc > _maxAcc ) _currAcc = _maxAcc;
_zspeed += _currAcc*multiplier;
if ( _zspeed < 0 ) _zspeed = 0;
if ( _zspeed > _maxSpeed ) _zspeed = _maxSpeed;
newPos.z += multiplier * _zspeed;
if ( _map->collide( shipAabb.offset( newPos ) ) )
{
newPos.z = _ship.pos().z;
_zspeed = 0;
}
else
_ship.pos().z = newPos.z;
if ( _currStrafe < -_maxStrafe ) _currStrafe = -_maxStrafe;
if ( _currStrafe > _maxStrafe ) _currStrafe = _maxStrafe;
if ( _currStrafe != 0 )
{
newPos.x += _currStrafe*multiplier;
if ( _map->collide( shipAabb.offset( newPos ) ) )
newPos.x = _ship.pos().x;
else
_ship.pos().x = newPos.x;
}
if ( _tapex <= 0 && _grounded )
{
_tapex = 0;
_yapex = _ship.pos().y;
}
_tapex -= multiplier;
newPos.y = _yapex - _gravity * ( _tapex*_tapex );
if ( _map->collide( shipAabb.offset( newPos ) ) )
{
newPos.y = _ship.pos().y;
if (_tapex < 0)
_grounded = true;
_tapex = 0;
_yapex = _ship.pos().y;
}
else
{
_ship.pos().y = newPos.y;
_grounded = false;
}
if ( droppedOut() )
{
- kill( "You dropped into the void" );
+ kill( "You dropped into the void!" );
}
}
+void Game::suicide()
+{
+ kill( "You committed suicide!" );
+}
+
void Game::kill( const std::string & cause )
{
_death = cause;
}
diff --git a/src/game.hpp b/src/game.hpp
index 68128b2..dacc6a1 100644
--- a/src/game.hpp
+++ b/src/game.hpp
@@ -1,72 +1,73 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _WORLD_HPP_
#define _WORLD_HPP_
#include "ship.hpp"
#include "map.hpp"
class ShaderProgram;
class Game
{
public:
Game(
double acceleration, double strafespeed, double speedlimit
, double gravity, double jumpstrength
, ShaderProgram * shader = 0
);
void setMap(Map& map) throw() { _map = ↦ }
void setShader(ShaderProgram& shader) throw() { _shader = &shader; }
void setAcceleration( double accel ) { _currAcc = accel*_maxAcc; }
void setStrafe( double strafe ) { _currStrafe = strafe*_maxStrafe; }
void startJump();
void draw( double zminClip );
void update( int difference );
double distanceTraveled() const throw() { return _ship.pos().z; }
bool droppedOut() const throw() {
return _ship.pos().y < _map->lowestPoint() - 1;
}
void kill( const std::string & cause );
+ void suicide();
bool dead() const throw() { return !_death.empty(); }
const std::string& deathCause() const { return _death; }
private:
Ship _ship;
Map* _map;
ShaderProgram * _shader;
double _currAcc, _maxAcc;
double _currStrafe, _maxStrafe;
double _maxSpeed, _zspeed;
double _yapex, _tapex, _gravity;
double _jstrength;
bool _grounded;
std::string _death;
};
#endif // _WORLD_HPP_
|
devnev/skyways
|
8ec9abe9dba361a4844f4fe82be9c94cac3bfed7
|
Integrated death cause into game class.
|
diff --git a/src/controller.cpp b/src/controller.cpp
index f2ea7b3..cc0a1a5 100644
--- a/src/controller.cpp
+++ b/src/controller.cpp
@@ -1,188 +1,186 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <GL/glew.h>
#include <GL/gl.h>
#include <boost/format.hpp>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include "textprinter.hpp"
#include "shader.hpp"
#include "controller.hpp"
Controller::Controller(
std::auto_ptr< Game > game
, double cameraheight, double cameradistance, double camerarotation
, Controller::QuitCallback cbQuit
, std::auto_ptr< TextPrinter > printer
)
: _game( game ), _map( 10 )
, _camy( cameraheight ), _camz( cameradistance ), _camrot( camerarotation )
, _quitcb( cbQuit ), _printer( printer )
, _windowwidth( 1 ), _windowheight( 1 )
{
_game->setMap( _map );
}
Controller::~Controller()
{
}
void Controller::keydown( int key )
{
switch ( key )
{
case STRAFE_L_KEY: _game->setStrafe( -1 ); break;
case STRAFE_R_KEY: _game->setStrafe( 1 ); break;
case ACCEL_KEY: _game->setAcceleration( 1 ); break;
case DECEL_KEY: _game->setAcceleration( -1 ); break;
case JUMP_KEY: _game->startJump(); break;
case QUIT_KEY:
if ( _game->dead() )
{
_quitcb();
}
else
{
- std::cout <<
- "You committed suicide!\n"
- "Distance traveled: " << _game->distanceTraveled() << std::endl;
- _game->kill();
+ _game->kill( "You committed suicide!" );
}
break;
}
}
void Controller::keyup( int key )
{
switch ( key )
{
case STRAFE_L_KEY:
_game->setStrafe( 0 );
break;
case STRAFE_R_KEY:
_game->setStrafe( 0 );
break;
case ACCEL_KEY:
_game->setAcceleration( 0 );
break;
case DECEL_KEY:
_game->setAcceleration( 0 );
break;
}
}
void Controller::loadMap( std::string filename )
{
_map.loadBlocks();
std::ifstream mapFile( filename.c_str() );
_map.loadMap( mapFile );
}
void Controller::generateMap()
{
_map.loadBlocks();
srand(time(0));
_map.generateMap();
}
void Controller::initialize()
{
GLenum err = glewInit();
if (err != GLEW_OK)
throw std::runtime_error((const char*)glewGetErrorString(err));
if (!GLEW_VERSION_2_0)
throw std::runtime_error("Nead OpenGL >= 2.0 for shaders. Update your graphics drivers!");
_shaderProgram = createShaderProgram("shaders/shader.glslv", "shaders/shader.glslf");
_game->setShader( *_shaderProgram );
glClearColor( 0.2, 0.2, 0.2, 0 );
glClearDepth( 1.0 );
glEnable( GL_DEPTH_TEST );
glDepthFunc( GL_LEQUAL );
glEnable( GL_CULL_FACE );
glEnable( GL_LIGHTING );
glShadeModel( GL_SMOOTH );
glEnable( GL_COLOR_MATERIAL );
glEnable( GL_NORMALIZE );
glEnable( GL_BLEND );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
glEnable( GL_LINE_SMOOTH );
glHint( GL_LINE_SMOOTH_HINT, GL_NICEST );
float ambient[] = { 0.2f, 0.2f, 0.2f, 1.0f };
float diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f };
float position[] = { 0.0f, 4.0f, -2.0f, 1.0f };
glLightfv( GL_LIGHT1, GL_AMBIENT, ambient );
glLightfv( GL_LIGHT1, GL_DIFFUSE, diffuse );
glLightfv( GL_LIGHT1, GL_POSITION, position );
glEnable( GL_LIGHT1 );
_map.optimize();
}
void Controller::resize( int width, int height )
{
glViewport( 0, 0, width, height );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
double fH = tan( 30.0 / 180.0 * 3.14159265358979323846 );
double fW = ( (double)width ) / ( (double)height ) * fH;
glFrustum( -fW, fW, -fH, fH, 1.0, 1000.0 );
glMatrixMode( GL_MODELVIEW );
_windowwidth = width;
_windowheight = height;
}
void Controller::draw()
{
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glLoadIdentity();
glRotatef( _camrot, 1, 0, 0 );
glTranslated( 0.0, -_camy, -_camz );
_game->draw( _camz );
if ( _game->dead() )
{
glUseProgram(0);
_printer->print(
- ( boost::format( "Distance Traveled: %1%" ) % _game->distanceTraveled() ).str(),
+ ( boost::format( "%1% Distance Traveled: %2%" )
+ % _game->deathCause()
+ % _game->distanceTraveled() ).str(),
_windowwidth / 2, _windowheight / 4 * 3,
TextPrinter::ALIGN_CENTER
);
}
}
void Controller::update( int difference )
{
if ( _game->dead() )
return;
_game->update( difference );
-
}
diff --git a/src/game.cpp b/src/game.cpp
index 8a18920..e763632 100644
--- a/src/game.cpp
+++ b/src/game.cpp
@@ -1,141 +1,137 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <cstdlib>
#include <ctime>
#include <cmath>
-#include <iostream>
#include "shader.hpp"
#include "game.hpp"
Game::Game(
double acceleration, double strafespeed, double speedlimit
, double gravity, double jumpstrength
, ShaderProgram * shader
)
: _ship(), _map( 0 ), _shader( shader )
, _currAcc( 0 ), _maxAcc( acceleration )
, _currStrafe( 0 ), _maxStrafe( strafespeed )
, _maxSpeed( speedlimit ), _zspeed( 0 )
, _yapex( 0 ), _tapex( 0 ), _gravity( gravity )
- , _jstrength( jumpstrength ), _grounded( true ), _dead( false )
+ , _jstrength( jumpstrength ), _grounded( true )
{
_ship.initialize();
_ship.pos().x = 0.5;
}
void Game::startJump()
{
if ( _grounded ||
_map->collide( AABB(
_ship.pos().offset(0, -0.2, 0),
_ship.pos().offset(0, -0.2, 0).offset(_ship.size())
) ) )
{
_yapex = _ship.ypos() + _jstrength;
_tapex = sqrt( _jstrength / _gravity );
}
}
void Game::draw( double zminClip )
{
_shader->use();
glPushMatrix();
glTranslated( _ship.xpos() - 0.5, _ship.ypos(), 0.0 );
glColor4f( 1, 0, 0, 0.25 );
_ship.drawDl();
glPopMatrix();
glColor3f( 0.8f, 1, 1 );
glTranslatef( -0.5, 0.0, _ship.zpos() );
_map->glDraw( _ship.zpos() - zminClip );
}
void Game::update( int difference )
{
double multiplier = ( (double)difference ) / 1000;
Vector3 newPos = _ship.pos();
AABB shipAabb(
Vector3( -_ship.size().x/2, 0, 0 ),
Vector3( _ship.size().x/2, _ship.size().y, _ship.size().z )
);
if ( _currAcc < -_maxAcc ) _currAcc = -_maxAcc;
else if ( _currAcc > _maxAcc ) _currAcc = _maxAcc;
_zspeed += _currAcc*multiplier;
if ( _zspeed < 0 ) _zspeed = 0;
if ( _zspeed > _maxSpeed ) _zspeed = _maxSpeed;
newPos.z += multiplier * _zspeed;
if ( _map->collide( shipAabb.offset( newPos ) ) )
{
newPos.z = _ship.pos().z;
_zspeed = 0;
}
else
_ship.pos().z = newPos.z;
if ( _currStrafe < -_maxStrafe ) _currStrafe = -_maxStrafe;
if ( _currStrafe > _maxStrafe ) _currStrafe = _maxStrafe;
if ( _currStrafe != 0 )
{
newPos.x += _currStrafe*multiplier;
if ( _map->collide( shipAabb.offset( newPos ) ) )
newPos.x = _ship.pos().x;
else
_ship.pos().x = newPos.x;
}
if ( _tapex <= 0 && _grounded )
{
_tapex = 0;
_yapex = _ship.pos().y;
}
_tapex -= multiplier;
newPos.y = _yapex - _gravity * ( _tapex*_tapex );
if ( _map->collide( shipAabb.offset( newPos ) ) )
{
newPos.y = _ship.pos().y;
if (_tapex < 0)
_grounded = true;
_tapex = 0;
_yapex = _ship.pos().y;
}
else
{
_ship.pos().y = newPos.y;
_grounded = false;
}
if ( droppedOut() )
{
- std::cout <<
- "You dropped into the void!\n"
- "Distance traveled: " << distanceTraveled() << std::endl;
- kill();
+ kill( "You dropped into the void" );
}
}
-void Game::kill()
+void Game::kill( const std::string & cause )
{
- _dead = true;
+ _death = cause;
}
diff --git a/src/game.hpp b/src/game.hpp
index a19ec60..68128b2 100644
--- a/src/game.hpp
+++ b/src/game.hpp
@@ -1,71 +1,72 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _WORLD_HPP_
#define _WORLD_HPP_
#include "ship.hpp"
#include "map.hpp"
class ShaderProgram;
class Game
{
public:
Game(
double acceleration, double strafespeed, double speedlimit
, double gravity, double jumpstrength
, ShaderProgram * shader = 0
);
void setMap(Map& map) throw() { _map = ↦ }
void setShader(ShaderProgram& shader) throw() { _shader = &shader; }
void setAcceleration( double accel ) { _currAcc = accel*_maxAcc; }
void setStrafe( double strafe ) { _currStrafe = strafe*_maxStrafe; }
void startJump();
void draw( double zminClip );
void update( int difference );
double distanceTraveled() const throw() { return _ship.pos().z; }
bool droppedOut() const throw() {
return _ship.pos().y < _map->lowestPoint() - 1;
}
- void kill();
- bool dead() const throw() { return _dead; }
+ void kill( const std::string & cause );
+ bool dead() const throw() { return !_death.empty(); }
+ const std::string& deathCause() const { return _death; }
private:
Ship _ship;
Map* _map;
ShaderProgram * _shader;
double _currAcc, _maxAcc;
double _currStrafe, _maxStrafe;
double _maxSpeed, _zspeed;
double _yapex, _tapex, _gravity;
double _jstrength;
bool _grounded;
- bool _dead;
+ std::string _death;
};
#endif // _WORLD_HPP_
|
devnev/skyways
|
133b76f5ce477fdd03d47b0a5606e245588bcb01
|
Moved death state into Game class.
|
diff --git a/src/controller.cpp b/src/controller.cpp
index cf003fd..f2ea7b3 100644
--- a/src/controller.cpp
+++ b/src/controller.cpp
@@ -1,197 +1,188 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <GL/glew.h>
#include <GL/gl.h>
#include <boost/format.hpp>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include "textprinter.hpp"
#include "shader.hpp"
#include "controller.hpp"
Controller::Controller(
std::auto_ptr< Game > game
, double cameraheight, double cameradistance, double camerarotation
, Controller::QuitCallback cbQuit
, std::auto_ptr< TextPrinter > printer
)
: _game( game ), _map( 10 )
, _camy( cameraheight ), _camz( cameradistance ), _camrot( camerarotation )
- , _dead( false ), _quitcb( cbQuit )
- , _printer( printer )
+ , _quitcb( cbQuit ), _printer( printer )
, _windowwidth( 1 ), _windowheight( 1 )
{
_game->setMap( _map );
}
Controller::~Controller()
{
}
void Controller::keydown( int key )
{
switch ( key )
{
case STRAFE_L_KEY: _game->setStrafe( -1 ); break;
case STRAFE_R_KEY: _game->setStrafe( 1 ); break;
case ACCEL_KEY: _game->setAcceleration( 1 ); break;
case DECEL_KEY: _game->setAcceleration( -1 ); break;
case JUMP_KEY: _game->startJump(); break;
case QUIT_KEY:
- if ( _dead )
+ if ( _game->dead() )
{
_quitcb();
}
else
{
std::cout <<
"You committed suicide!\n"
"Distance traveled: " << _game->distanceTraveled() << std::endl;
- _dead = true;
+ _game->kill();
}
break;
}
}
void Controller::keyup( int key )
{
switch ( key )
{
case STRAFE_L_KEY:
_game->setStrafe( 0 );
break;
case STRAFE_R_KEY:
_game->setStrafe( 0 );
break;
case ACCEL_KEY:
_game->setAcceleration( 0 );
break;
case DECEL_KEY:
_game->setAcceleration( 0 );
break;
}
}
void Controller::loadMap( std::string filename )
{
_map.loadBlocks();
std::ifstream mapFile( filename.c_str() );
_map.loadMap( mapFile );
}
void Controller::generateMap()
{
_map.loadBlocks();
srand(time(0));
_map.generateMap();
}
void Controller::initialize()
{
GLenum err = glewInit();
if (err != GLEW_OK)
throw std::runtime_error((const char*)glewGetErrorString(err));
if (!GLEW_VERSION_2_0)
throw std::runtime_error("Nead OpenGL >= 2.0 for shaders. Update your graphics drivers!");
_shaderProgram = createShaderProgram("shaders/shader.glslv", "shaders/shader.glslf");
_game->setShader( *_shaderProgram );
glClearColor( 0.2, 0.2, 0.2, 0 );
glClearDepth( 1.0 );
glEnable( GL_DEPTH_TEST );
glDepthFunc( GL_LEQUAL );
glEnable( GL_CULL_FACE );
glEnable( GL_LIGHTING );
glShadeModel( GL_SMOOTH );
glEnable( GL_COLOR_MATERIAL );
glEnable( GL_NORMALIZE );
glEnable( GL_BLEND );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
glEnable( GL_LINE_SMOOTH );
glHint( GL_LINE_SMOOTH_HINT, GL_NICEST );
float ambient[] = { 0.2f, 0.2f, 0.2f, 1.0f };
float diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f };
float position[] = { 0.0f, 4.0f, -2.0f, 1.0f };
glLightfv( GL_LIGHT1, GL_AMBIENT, ambient );
glLightfv( GL_LIGHT1, GL_DIFFUSE, diffuse );
glLightfv( GL_LIGHT1, GL_POSITION, position );
glEnable( GL_LIGHT1 );
_map.optimize();
}
void Controller::resize( int width, int height )
{
glViewport( 0, 0, width, height );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
double fH = tan( 30.0 / 180.0 * 3.14159265358979323846 );
double fW = ( (double)width ) / ( (double)height ) * fH;
glFrustum( -fW, fW, -fH, fH, 1.0, 1000.0 );
glMatrixMode( GL_MODELVIEW );
_windowwidth = width;
_windowheight = height;
}
void Controller::draw()
{
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glLoadIdentity();
glRotatef( _camrot, 1, 0, 0 );
glTranslated( 0.0, -_camy, -_camz );
_game->draw( _camz );
- if ( _dead )
+ if ( _game->dead() )
{
glUseProgram(0);
_printer->print(
( boost::format( "Distance Traveled: %1%" ) % _game->distanceTraveled() ).str(),
_windowwidth / 2, _windowheight / 4 * 3,
TextPrinter::ALIGN_CENTER
);
}
}
void Controller::update( int difference )
{
- if ( _dead )
+ if ( _game->dead() )
return;
_game->update( difference );
- if ( _game->droppedOut() )
- {
- std::cout <<
- "You dropped into the void!\n"
- "Distance traveled: " << _game->distanceTraveled() << std::endl;
- _dead = true;
- }
-
}
diff --git a/src/controller.hpp b/src/controller.hpp
index e8242b5..34c6d52 100644
--- a/src/controller.hpp
+++ b/src/controller.hpp
@@ -1,77 +1,76 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _CONTROLLER_HPP_
#define _CONTROLLER_HPP_
#include <memory>
#include "map.hpp"
#include "game.hpp"
class TextPrinter;
class ShaderProgram;
class Controller
{
public:
typedef void (*QuitCallback)();
Controller(
std::auto_ptr< Game > game
, double cameraheight, double cameradistance, double camerarotation
, QuitCallback cbQuit
, std::auto_ptr< TextPrinter > printer
);
~Controller();
enum {
JUMP_KEY = 1,
STRAFE_L_KEY = 2,
STRAFE_R_KEY = 3,
ACCEL_KEY = 4,
DECEL_KEY = 5,
QUIT_KEY = 6,
};
void keydown( int key );
void keyup( int key );
void loadMap( std::string filename );
void generateMap();
void initialize();
void resize( int width, int height );
void draw();
void update( int difference );
private:
std::auto_ptr< Game > _game;
Map _map;
double _camy, _camz, _camrot;
- bool _dead;
QuitCallback _quitcb;
std::auto_ptr< TextPrinter > _printer;
size_t _windowwidth, _windowheight;
std::auto_ptr< ShaderProgram > _shaderProgram;
};
#endif // _CONTROLLER_HPP_
diff --git a/src/game.cpp b/src/game.cpp
index 41c7b2f..8a18920 100644
--- a/src/game.cpp
+++ b/src/game.cpp
@@ -1,127 +1,141 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <cstdlib>
#include <ctime>
#include <cmath>
+#include <iostream>
#include "shader.hpp"
#include "game.hpp"
Game::Game(
double acceleration, double strafespeed, double speedlimit
, double gravity, double jumpstrength
, ShaderProgram * shader
)
: _ship(), _map( 0 ), _shader( shader )
, _currAcc( 0 ), _maxAcc( acceleration )
, _currStrafe( 0 ), _maxStrafe( strafespeed )
, _maxSpeed( speedlimit ), _zspeed( 0 )
, _yapex( 0 ), _tapex( 0 ), _gravity( gravity )
- , _jstrength( jumpstrength ), _grounded( true )
+ , _jstrength( jumpstrength ), _grounded( true ), _dead( false )
{
_ship.initialize();
_ship.pos().x = 0.5;
}
void Game::startJump()
{
if ( _grounded ||
_map->collide( AABB(
_ship.pos().offset(0, -0.2, 0),
_ship.pos().offset(0, -0.2, 0).offset(_ship.size())
) ) )
{
_yapex = _ship.ypos() + _jstrength;
_tapex = sqrt( _jstrength / _gravity );
}
}
void Game::draw( double zminClip )
{
_shader->use();
glPushMatrix();
glTranslated( _ship.xpos() - 0.5, _ship.ypos(), 0.0 );
glColor4f( 1, 0, 0, 0.25 );
_ship.drawDl();
glPopMatrix();
glColor3f( 0.8f, 1, 1 );
glTranslatef( -0.5, 0.0, _ship.zpos() );
_map->glDraw( _ship.zpos() - zminClip );
}
void Game::update( int difference )
{
double multiplier = ( (double)difference ) / 1000;
Vector3 newPos = _ship.pos();
AABB shipAabb(
Vector3( -_ship.size().x/2, 0, 0 ),
Vector3( _ship.size().x/2, _ship.size().y, _ship.size().z )
);
if ( _currAcc < -_maxAcc ) _currAcc = -_maxAcc;
else if ( _currAcc > _maxAcc ) _currAcc = _maxAcc;
_zspeed += _currAcc*multiplier;
if ( _zspeed < 0 ) _zspeed = 0;
if ( _zspeed > _maxSpeed ) _zspeed = _maxSpeed;
newPos.z += multiplier * _zspeed;
if ( _map->collide( shipAabb.offset( newPos ) ) )
{
newPos.z = _ship.pos().z;
_zspeed = 0;
}
else
_ship.pos().z = newPos.z;
if ( _currStrafe < -_maxStrafe ) _currStrafe = -_maxStrafe;
if ( _currStrafe > _maxStrafe ) _currStrafe = _maxStrafe;
if ( _currStrafe != 0 )
{
newPos.x += _currStrafe*multiplier;
if ( _map->collide( shipAabb.offset( newPos ) ) )
newPos.x = _ship.pos().x;
else
_ship.pos().x = newPos.x;
}
if ( _tapex <= 0 && _grounded )
{
_tapex = 0;
_yapex = _ship.pos().y;
}
_tapex -= multiplier;
newPos.y = _yapex - _gravity * ( _tapex*_tapex );
if ( _map->collide( shipAabb.offset( newPos ) ) )
{
newPos.y = _ship.pos().y;
if (_tapex < 0)
_grounded = true;
_tapex = 0;
_yapex = _ship.pos().y;
}
else
{
_ship.pos().y = newPos.y;
_grounded = false;
}
+ if ( droppedOut() )
+ {
+ std::cout <<
+ "You dropped into the void!\n"
+ "Distance traveled: " << distanceTraveled() << std::endl;
+ kill();
+ }
+
+}
+
+void Game::kill()
+{
+ _dead = true;
}
diff --git a/src/game.hpp b/src/game.hpp
index 599a127..a19ec60 100644
--- a/src/game.hpp
+++ b/src/game.hpp
@@ -1,67 +1,71 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _WORLD_HPP_
#define _WORLD_HPP_
#include "ship.hpp"
#include "map.hpp"
class ShaderProgram;
class Game
{
public:
Game(
double acceleration, double strafespeed, double speedlimit
, double gravity, double jumpstrength
, ShaderProgram * shader = 0
);
void setMap(Map& map) throw() { _map = ↦ }
void setShader(ShaderProgram& shader) throw() { _shader = &shader; }
void setAcceleration( double accel ) { _currAcc = accel*_maxAcc; }
void setStrafe( double strafe ) { _currStrafe = strafe*_maxStrafe; }
void startJump();
void draw( double zminClip );
void update( int difference );
double distanceTraveled() const throw() { return _ship.pos().z; }
bool droppedOut() const throw() {
return _ship.pos().y < _map->lowestPoint() - 1;
}
+ void kill();
+ bool dead() const throw() { return _dead; }
+
private:
Ship _ship;
Map* _map;
ShaderProgram * _shader;
double _currAcc, _maxAcc;
double _currStrafe, _maxStrafe;
double _maxSpeed, _zspeed;
double _yapex, _tapex, _gravity;
double _jstrength;
bool _grounded;
+ bool _dead;
};
#endif // _WORLD_HPP_
|
devnev/skyways
|
e60c1c1a78fd33fae7233dd179af1ff717b6690c
|
Renamed class World to Game.
|
diff --git a/Makefile b/Makefile
index 69a6f86..d25e263 100644
--- a/Makefile
+++ b/Makefile
@@ -1,155 +1,155 @@
###########################
# prelude: do not change! #
###########################
CWD:=$(shell pwd)
default: all
BUILDFLAGS=CFLAGS CPPFLAGS CXXFLAGS LDFLAGS
define FLAGINIT_template
ifndef $(1)
$(1)=
endif
endef
$(foreach flag,$(BUILDFLAGS),$(eval $(call FLAGINIT_template,$(flag))))
######################################
# configuration: change things here. #
######################################
PROGRAMS=SkywaysGlut SkywaysQt SkywaysSdl
SkywaysGlut_BINARY=skyways.glut
SkywaysQt_BINARY=skyways.qt
SkywaysSdl_BINARY=skyways.sdl
HEADERS= \
src/aabb.hpp \
src/block.hpp \
src/collisionaccelerator.hpp \
src/configuration.hpp \
src/controller.hpp \
src/element.hpp \
src/map.hpp \
src/model.hpp \
src/objmodel.hpp \
src/shader.hpp \
src/ship.hpp \
src/textprinter.hpp \
src/vector.hpp \
- src/world.hpp
+ src/game.hpp
SkywasyGlut_HEADERS= $(HEADERS) \
src/configparser.hpp
SkywasyQt_HEADERS= $(HEADERS) \
src/qtconfigparser.hpp \
src/qtwindow.hpp
SkywaysSdl_HEADERS= $(HEADERS) \
src/configparser.hpp
CXXSOURCES= \
src/block.cpp \
src/collisionaccelerator.cpp \
src/configuration.cpp \
src/controller.cpp \
src/element.cpp \
src/map.cpp \
src/objmodel.cpp \
src/shader.cpp \
src/ship.cpp \
src/textprinter.cpp \
- src/world.cpp
+ src/game.cpp
SkywaysGlut_CXXSOURCES= $(CXXSOURCES) \
src/configparser.cpp \
src/glutmain.cpp
SkywaysQt_CXXSOURCES= $(CXXSOURCES) \
src/moc_qtwindow.cpp \
src/qtconfigparser.cpp \
src/qtmain.cpp \
src/qtwindow.cpp
SkywaysSdl_CXXSOURCES= $(CXXSOURCES) \
src/configparser.cpp \
src/sdlmain.cpp
CPPFLAGS+= -O2 -g -Wall -I/usr/include/FTGL -I/usr/include/freetype2
LDFLAGS+= -lGL -lboost_filesystem -lftgl -lGLEW
SkywaysGlut_LDFLAGS=-lglut -lboost_program_options
SkywaysQt_LDFLAGS=-lQtOpenGL -lQtGui -lQtCore -lGLU -lGL -lpthread
SkywaysQt_CPPFLAGS=-D_REENTRANT -DQT_NO_DEBUG -DQT_OPENGL_LIB -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED -I/usr/include/qt4/QtCore -I/usr/include/qt4/QtGui -I/usr/include/qt4/QtOpenGL -I/usr/include/qt4
SkywaysSdl_LDFLAGS=-lSDL -lboost_program_options
SkywaysSdl_CPPFLAGS=-I/usr/include/SDL
EXTRADIST=
######################################
# auto-configuration: do not change! #
######################################
$(foreach prog,$(PROGRAMS),$(eval $(prog)_SOURCES=$($(prog)_CSOURCES) $($(prog)_CXXSOURCES)))
$(foreach prog,$(PROGRAMS),$(eval $(prog)_OBJECTS=$(patsubst %.c,%_$(prog).o,$($(prog)_CSOURCES)) $(patsubst %.cpp,%_$(prog).o,$($(prog)_CXXSOURCES))))
$(foreach flag,CFLAGS CPPFLAGS CXXFLAGS LDFLAGS,$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_$(flag)=$($(flag)) $($(prog)_$(flag)))))
#CSOURCES=$(foreach prog,$(PROGRAMS),$($(prog)_CSOURCES))
#CXXSOURCES=$(foreach prog,$(PROGRAMS),$($(prog)_CXXSOURCES))
#SOURCES=$(CSOURCES) $(CXXSOURCES)
#HEADERS=$(foreach prog,$(PROGRAMS),$($(prog)_HEADERS))
OBJECTS=$(foreach prog,$(PROGRAMS),$($(prog)_OBJECTS))
BINARIES=$(foreach prog,$(PROGRAMS),$($(prog)_BINARY))
DEPENDS=$(patsubst %.o,%.d,$(OBJECTS))
define CDEP_template
%_$(1).d: %.c
set -e; rm -f "$$@" || true; \
$$(CC) -MM -MQ "`echo "$$<" | sed 's,\($$*\)\.c,\1_$(1).o,'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) "$$<" | \
sed 's,\($$*_$(1)\).o *:,\1.o $$@:,' >$$@
endef
define CXXDEP_template
%_$(1).d: %.cpp
set -e; rm -f "$$@" || true; \
$$(CXX) -MM -MQ "`echo "$$<" | sed 's,\($$*\)\.cpp,\1_$(1).o,'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) "$$<" | \
sed 's,\($$*_$(1)\).o *:,\1.o $$@:,' >$$@
endef
define CSRC_template
%_$(1).o: %.c
$$(CC) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) $$< -o $$@
endef
define CXXSRC_template
%_$(1).o: %.cpp
$$(CXX) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) $$< -o $$@
endef
define BINARY_template
$$($(1)_BINARY): $$($(1)_OBJECTS)
$$(CC) $$($(1)_ALL_LDFLAGS) $$^ $$(LOADLIBS) $$(LDLIBS) -o $$@
endef
$(foreach template,CDEP CXXDEP CSRC CXXSRC BINARY,$(foreach prog,$(PROGRAMS),$(eval $(call $(template)_template,$(prog)))))
all: $(BINARIES)
#################################
# extra stuff: change as needed #
#################################
clean:
rm $(OBJECTS) $(BINARIES) $(DEPENDS) $(DISTFILES) || true
moc_%.cpp: %.hpp
moc-qt4 $(SkywaysQt_CPPFLAGS) $(SkywaysQt_CXXFLAGS) $< -o $@
.PHONY: default clean
-include $(DEPENDS)
diff --git a/src/configuration.cpp b/src/configuration.cpp
index 10236a0..0a7b234 100644
--- a/src/configuration.cpp
+++ b/src/configuration.cpp
@@ -1,42 +1,42 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include "textprinter.hpp"
#include "controller.hpp"
#include "configuration.hpp"
Configuration::Configuration()
{
}
std::auto_ptr< Controller > Configuration::buildController( Controller::QuitCallback cbquit )
{
std::auto_ptr< TextPrinter > printer( new TextPrinter( "DejaVuSans.ttf" ) );
- std::auto_ptr< World > world( new World(
+ std::auto_ptr< Game > game( new Game(
10, 5, 100, 20, 1.5
) );
std::auto_ptr< Controller > controller( new Controller (
- world, 3.5, 6, 10, cbquit, printer
+ game, 3.5, 6, 10, cbquit, printer
) );
if ( _map.length() )
controller->loadMap( _map );
else
controller->generateMap();
return controller;
}
diff --git a/src/controller.cpp b/src/controller.cpp
index c3a553f..cf003fd 100644
--- a/src/controller.cpp
+++ b/src/controller.cpp
@@ -1,197 +1,197 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <GL/glew.h>
#include <GL/gl.h>
#include <boost/format.hpp>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include "textprinter.hpp"
#include "shader.hpp"
#include "controller.hpp"
Controller::Controller(
- std::auto_ptr< World > world
+ std::auto_ptr< Game > game
, double cameraheight, double cameradistance, double camerarotation
, Controller::QuitCallback cbQuit
, std::auto_ptr< TextPrinter > printer
)
- : _world( world ), _map( 10 )
+ : _game( game ), _map( 10 )
, _camy( cameraheight ), _camz( cameradistance ), _camrot( camerarotation )
, _dead( false ), _quitcb( cbQuit )
, _printer( printer )
, _windowwidth( 1 ), _windowheight( 1 )
{
- _world->setMap( _map );
+ _game->setMap( _map );
}
Controller::~Controller()
{
}
void Controller::keydown( int key )
{
switch ( key )
{
- case STRAFE_L_KEY: _world->setStrafe( -1 ); break;
- case STRAFE_R_KEY: _world->setStrafe( 1 ); break;
- case ACCEL_KEY: _world->setAcceleration( 1 ); break;
- case DECEL_KEY: _world->setAcceleration( -1 ); break;
- case JUMP_KEY: _world->startJump(); break;
+ case STRAFE_L_KEY: _game->setStrafe( -1 ); break;
+ case STRAFE_R_KEY: _game->setStrafe( 1 ); break;
+ case ACCEL_KEY: _game->setAcceleration( 1 ); break;
+ case DECEL_KEY: _game->setAcceleration( -1 ); break;
+ case JUMP_KEY: _game->startJump(); break;
case QUIT_KEY:
if ( _dead )
{
_quitcb();
}
else
{
std::cout <<
"You committed suicide!\n"
- "Distance traveled: " << _world->distanceTraveled() << std::endl;
+ "Distance traveled: " << _game->distanceTraveled() << std::endl;
_dead = true;
}
break;
}
}
void Controller::keyup( int key )
{
switch ( key )
{
case STRAFE_L_KEY:
- _world->setStrafe( 0 );
+ _game->setStrafe( 0 );
break;
case STRAFE_R_KEY:
- _world->setStrafe( 0 );
+ _game->setStrafe( 0 );
break;
case ACCEL_KEY:
- _world->setAcceleration( 0 );
+ _game->setAcceleration( 0 );
break;
case DECEL_KEY:
- _world->setAcceleration( 0 );
+ _game->setAcceleration( 0 );
break;
}
}
void Controller::loadMap( std::string filename )
{
_map.loadBlocks();
std::ifstream mapFile( filename.c_str() );
_map.loadMap( mapFile );
}
void Controller::generateMap()
{
_map.loadBlocks();
srand(time(0));
_map.generateMap();
}
void Controller::initialize()
{
GLenum err = glewInit();
if (err != GLEW_OK)
throw std::runtime_error((const char*)glewGetErrorString(err));
if (!GLEW_VERSION_2_0)
throw std::runtime_error("Nead OpenGL >= 2.0 for shaders. Update your graphics drivers!");
_shaderProgram = createShaderProgram("shaders/shader.glslv", "shaders/shader.glslf");
- _world->setShader( *_shaderProgram );
+ _game->setShader( *_shaderProgram );
glClearColor( 0.2, 0.2, 0.2, 0 );
glClearDepth( 1.0 );
glEnable( GL_DEPTH_TEST );
glDepthFunc( GL_LEQUAL );
glEnable( GL_CULL_FACE );
glEnable( GL_LIGHTING );
glShadeModel( GL_SMOOTH );
glEnable( GL_COLOR_MATERIAL );
glEnable( GL_NORMALIZE );
glEnable( GL_BLEND );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
glEnable( GL_LINE_SMOOTH );
glHint( GL_LINE_SMOOTH_HINT, GL_NICEST );
float ambient[] = { 0.2f, 0.2f, 0.2f, 1.0f };
float diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f };
float position[] = { 0.0f, 4.0f, -2.0f, 1.0f };
glLightfv( GL_LIGHT1, GL_AMBIENT, ambient );
glLightfv( GL_LIGHT1, GL_DIFFUSE, diffuse );
glLightfv( GL_LIGHT1, GL_POSITION, position );
glEnable( GL_LIGHT1 );
_map.optimize();
}
void Controller::resize( int width, int height )
{
glViewport( 0, 0, width, height );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
double fH = tan( 30.0 / 180.0 * 3.14159265358979323846 );
double fW = ( (double)width ) / ( (double)height ) * fH;
glFrustum( -fW, fW, -fH, fH, 1.0, 1000.0 );
glMatrixMode( GL_MODELVIEW );
_windowwidth = width;
_windowheight = height;
}
void Controller::draw()
{
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glLoadIdentity();
glRotatef( _camrot, 1, 0, 0 );
glTranslated( 0.0, -_camy, -_camz );
- _world->draw( _camz );
+ _game->draw( _camz );
if ( _dead )
{
glUseProgram(0);
_printer->print(
- ( boost::format( "Distance Traveled: %1%" ) % _world->distanceTraveled() ).str(),
+ ( boost::format( "Distance Traveled: %1%" ) % _game->distanceTraveled() ).str(),
_windowwidth / 2, _windowheight / 4 * 3,
TextPrinter::ALIGN_CENTER
);
}
}
void Controller::update( int difference )
{
if ( _dead )
return;
- _world->update( difference );
+ _game->update( difference );
- if ( _world->droppedOut() )
+ if ( _game->droppedOut() )
{
std::cout <<
"You dropped into the void!\n"
- "Distance traveled: " << _world->distanceTraveled() << std::endl;
+ "Distance traveled: " << _game->distanceTraveled() << std::endl;
_dead = true;
}
}
diff --git a/src/controller.hpp b/src/controller.hpp
index 86b7603..e8242b5 100644
--- a/src/controller.hpp
+++ b/src/controller.hpp
@@ -1,77 +1,77 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _CONTROLLER_HPP_
#define _CONTROLLER_HPP_
#include <memory>
#include "map.hpp"
-#include "world.hpp"
+#include "game.hpp"
class TextPrinter;
class ShaderProgram;
class Controller
{
public:
typedef void (*QuitCallback)();
Controller(
- std::auto_ptr< World > world
+ std::auto_ptr< Game > game
, double cameraheight, double cameradistance, double camerarotation
, QuitCallback cbQuit
, std::auto_ptr< TextPrinter > printer
);
~Controller();
enum {
JUMP_KEY = 1,
STRAFE_L_KEY = 2,
STRAFE_R_KEY = 3,
ACCEL_KEY = 4,
DECEL_KEY = 5,
QUIT_KEY = 6,
};
void keydown( int key );
void keyup( int key );
void loadMap( std::string filename );
void generateMap();
void initialize();
void resize( int width, int height );
void draw();
void update( int difference );
private:
- std::auto_ptr< World > _world;
+ std::auto_ptr< Game > _game;
Map _map;
double _camy, _camz, _camrot;
bool _dead;
QuitCallback _quitcb;
std::auto_ptr< TextPrinter > _printer;
size_t _windowwidth, _windowheight;
std::auto_ptr< ShaderProgram > _shaderProgram;
};
#endif // _CONTROLLER_HPP_
diff --git a/src/world.cpp b/src/game.cpp
similarity index 95%
rename from src/world.cpp
rename to src/game.cpp
index b1d3455..41c7b2f 100644
--- a/src/world.cpp
+++ b/src/game.cpp
@@ -1,127 +1,127 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <cstdlib>
#include <ctime>
#include <cmath>
#include "shader.hpp"
-#include "world.hpp"
+#include "game.hpp"
-World::World(
+Game::Game(
double acceleration, double strafespeed, double speedlimit
, double gravity, double jumpstrength
, ShaderProgram * shader
)
: _ship(), _map( 0 ), _shader( shader )
, _currAcc( 0 ), _maxAcc( acceleration )
, _currStrafe( 0 ), _maxStrafe( strafespeed )
, _maxSpeed( speedlimit ), _zspeed( 0 )
, _yapex( 0 ), _tapex( 0 ), _gravity( gravity )
, _jstrength( jumpstrength ), _grounded( true )
{
_ship.initialize();
_ship.pos().x = 0.5;
}
-void World::startJump()
+void Game::startJump()
{
if ( _grounded ||
_map->collide( AABB(
_ship.pos().offset(0, -0.2, 0),
_ship.pos().offset(0, -0.2, 0).offset(_ship.size())
) ) )
{
_yapex = _ship.ypos() + _jstrength;
_tapex = sqrt( _jstrength / _gravity );
}
}
-void World::draw( double zminClip )
+void Game::draw( double zminClip )
{
_shader->use();
glPushMatrix();
glTranslated( _ship.xpos() - 0.5, _ship.ypos(), 0.0 );
glColor4f( 1, 0, 0, 0.25 );
_ship.drawDl();
glPopMatrix();
glColor3f( 0.8f, 1, 1 );
glTranslatef( -0.5, 0.0, _ship.zpos() );
_map->glDraw( _ship.zpos() - zminClip );
}
-void World::update( int difference )
+void Game::update( int difference )
{
double multiplier = ( (double)difference ) / 1000;
Vector3 newPos = _ship.pos();
AABB shipAabb(
Vector3( -_ship.size().x/2, 0, 0 ),
Vector3( _ship.size().x/2, _ship.size().y, _ship.size().z )
);
if ( _currAcc < -_maxAcc ) _currAcc = -_maxAcc;
else if ( _currAcc > _maxAcc ) _currAcc = _maxAcc;
_zspeed += _currAcc*multiplier;
if ( _zspeed < 0 ) _zspeed = 0;
if ( _zspeed > _maxSpeed ) _zspeed = _maxSpeed;
newPos.z += multiplier * _zspeed;
if ( _map->collide( shipAabb.offset( newPos ) ) )
{
newPos.z = _ship.pos().z;
_zspeed = 0;
}
else
_ship.pos().z = newPos.z;
if ( _currStrafe < -_maxStrafe ) _currStrafe = -_maxStrafe;
if ( _currStrafe > _maxStrafe ) _currStrafe = _maxStrafe;
if ( _currStrafe != 0 )
{
newPos.x += _currStrafe*multiplier;
if ( _map->collide( shipAabb.offset( newPos ) ) )
newPos.x = _ship.pos().x;
else
_ship.pos().x = newPos.x;
}
if ( _tapex <= 0 && _grounded )
{
_tapex = 0;
_yapex = _ship.pos().y;
}
_tapex -= multiplier;
newPos.y = _yapex - _gravity * ( _tapex*_tapex );
if ( _map->collide( shipAabb.offset( newPos ) ) )
{
newPos.y = _ship.pos().y;
if (_tapex < 0)
_grounded = true;
_tapex = 0;
_yapex = _ship.pos().y;
}
else
{
_ship.pos().y = newPos.y;
_grounded = false;
}
}
diff --git a/src/world.hpp b/src/game.hpp
similarity index 98%
rename from src/world.hpp
rename to src/game.hpp
index 08ad5ed..599a127 100644
--- a/src/world.hpp
+++ b/src/game.hpp
@@ -1,67 +1,67 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _WORLD_HPP_
#define _WORLD_HPP_
#include "ship.hpp"
#include "map.hpp"
class ShaderProgram;
-class World
+class Game
{
public:
- World(
+ Game(
double acceleration, double strafespeed, double speedlimit
, double gravity, double jumpstrength
, ShaderProgram * shader = 0
);
void setMap(Map& map) throw() { _map = ↦ }
void setShader(ShaderProgram& shader) throw() { _shader = &shader; }
void setAcceleration( double accel ) { _currAcc = accel*_maxAcc; }
void setStrafe( double strafe ) { _currStrafe = strafe*_maxStrafe; }
void startJump();
void draw( double zminClip );
void update( int difference );
double distanceTraveled() const throw() { return _ship.pos().z; }
bool droppedOut() const throw() {
return _ship.pos().y < _map->lowestPoint() - 1;
}
private:
Ship _ship;
Map* _map;
ShaderProgram * _shader;
double _currAcc, _maxAcc;
double _currStrafe, _maxStrafe;
double _maxSpeed, _zspeed;
double _yapex, _tapex, _gravity;
double _jstrength;
bool _grounded;
};
#endif // _WORLD_HPP_
|
devnev/skyways
|
59d8b3e3df4ee6770bb0ee6e900737193a36630b
|
Removed edge highlighting.
|
diff --git a/src/element.cpp b/src/element.cpp
index 8d66a43..3384cff 100644
--- a/src/element.cpp
+++ b/src/element.cpp
@@ -1,51 +1,45 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <GL/gl.h>
#include "element.hpp"
void Element::glDraw()
{
glPushMatrix();
glColor4d( _color.x, _color.y, _color.z, 0.5 );
glTranslated( _pos.x, _pos.y, -_pos.z );
glScaled( 1, 1, _length );
glEnable( GL_POLYGON_OFFSET_FILL );
glPolygonOffset( 0.01f, 0.01f );
_block->drawDl();
glDisable( GL_POLYGON_OFFSET_FILL );
- glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
- glColor3f( 0.75f, 0.75f, 0.75f );
- glLineWidth( 1.0f );
- _block->drawDl();
- glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
-
glPopMatrix();
}
bool Element::collide( const AABB& aabb ) const
{
AABB _aabb( aabb.offset( -_pos.x, -_pos.y, -_pos.z ) );
_aabb.p1.z /= _length;
_aabb.p2.z /= _length;
return _block->collide( _aabb );
}
diff --git a/src/ship.cpp b/src/ship.cpp
index 0efd51b..639de7e 100644
--- a/src/ship.cpp
+++ b/src/ship.cpp
@@ -1,128 +1,122 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <GL/gl.h>
#include <cmath>
#include <iostream>
#include <stdexcept>
#include "ship.hpp"
#include "objmodel.hpp"
Ship::Ship()
: _pos(Vector3(0, 0, 0))
, _size(Vector3(0.8, 0.5, 1.0))
, _shipDl(0)
{
}
Ship::~Ship()
{
}
void Ship::initialize()
{
try
{
loadObjModel("ship.obj", _model, true, 0, "mtl\0");
std::cout << "loaded "
<< _model.vertices.size() << " vertices and "
<< _model.trifaces.size() + _model.quadfaces.size()
<< " faces for ship." << std::endl;
}
catch (std::runtime_error& e)
{
std::cerr <<
"Warning: failed to load ship model, "
"falling back to box ship.\n"
"Exception caught was: "
<< e.what() << '\n';
}
}
void Ship::draw()
{
glTranslated( 0, _size.y / 2, -_size.z / 2 );
if ( _model.vertices.size() && _model.trifaces.size() )
{
glScaled( _size.x, _size.y, -_size.z );
_model.draw();
}
else
{
glScaled( _size.x, _size.y, _size.z );
glEnable( GL_POLYGON_OFFSET_FILL );
glPolygonOffset( 0.01f, 0.01f );
drawSimple();
glDisable( GL_POLYGON_OFFSET_FILL );
-
- glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
- glColor3f( 0.75f, 0.75f, 0.75f );
- glLineWidth( 1.0f );
- drawSimple();
- glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
}
}
void Ship::drawDl()
{
if ( _shipDl == 0 )
{
_shipDl = glGenLists( 1 );
glNewList( _shipDl, GL_COMPILE_AND_EXECUTE );
draw();
glEndList();
}
else
{
glCallList( _shipDl );
}
}
void Ship::drawSimple()
{
glBegin( GL_QUADS );
glNormal3d( 0, 0, 1 );
glVertex3d( -0.5, 0.5, 0.5 );
glVertex3d( -0.5, -0.5, 0.5 );
glVertex3d( 0.5, -0.5, 0.5 );
glVertex3d( 0.5, 0.5, 0.5 );
glEnd();
glBegin( GL_TRIANGLES );
glNormal3d( -1, 0, -0.5 );
glVertex3d( -0.5, -0.5, 0.5 );
glVertex3d( -0.5, 0.5, 0.5 );
glVertex3d( 0, 0, -1.0 );
glNormal3d( 0, 1, -0.5 );
glVertex3d( -0.5, 0.5, 0.5 );
glVertex3d( 0.5, 0.5, 0.5 );
glVertex3d( 0, 0, -1.0 );
glNormal3d( 1, 0, -0.5 );
glVertex3d( 0.5, 0.5, 0.5 );
glVertex3d( 0.5, -0.5, 0.5 );
glVertex3d( 0, 0, -1.0 );
glNormal3d( 0, -1, -0.5 );
glVertex3d( 0.5, -0.5, 0.5 );
glVertex3d( -0.5, -0.5, 0.5 );
glVertex3d( 0, 0, -1.0 );
glEnd();
}
|
devnev/skyways
|
2229ad3acf5cd582d15101adee8effc12c409be6
|
Added optional flag to alias definitions in world file format.
|
diff --git a/src/map.cpp b/src/map.cpp
index 568c477..8c3cf52 100644
--- a/src/map.cpp
+++ b/src/map.cpp
@@ -1,257 +1,273 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <algorithm>
#include <functional>
#include <fstream>
#include <string>
#include <sstream>
#include <list>
+#include <cctype>
#include "map.hpp"
Map::Map( size_t sectionSize )
: _accelerator( sectionSize )
{
std::string empty;
blocks.insert( empty, new Block() );
}
void Map::glDraw( double )
{
for ( ElementList::iterator elem = elements.begin() ;
elem != elements.end(); ++elem )
{
elem->glDraw();
}
_elementsDrawn = elements.size();
}
void Map::loadBlocks()
{
using namespace boost::filesystem;
path block_dir( "blocks" );
if ( !exists( block_dir ) )
return;
for ( recursive_directory_iterator block_fs_entry( block_dir ) ;
block_fs_entry != recursive_directory_iterator() ;
++block_fs_entry )
{
if ( is_directory( block_fs_entry->status() ) )
continue;
std::string block_path;
path::iterator iter = block_fs_entry->path().begin();
++iter;
if ( iter != block_fs_entry->path().end() )
block_path = *iter;
for ( ++iter ; iter != block_fs_entry->path().end() ; ++iter )
block_path = block_path + "/" + *iter;
blocks.insert( block_path, Block::fromFile( block_fs_entry->path().string() ) );
}
}
void Map::optimize()
{
for ( ElementList::iterator elem = elements.begin() ;
elem != elements.end(); ++elem )
{
_accelerator.addElement( *elem );
}
}
bool Map::collide( const AABB& aabb )
{
return _accelerator.collide( aabb );
}
void Map::generateMap()
{
_accelerator.clear();
elements.clear();
elements.push_back(Element(
0, -1, 0, 20, block( "" ), Vector3( 1, 1, 1 )
));
size_t width = 7;
size_t base = 0;
std::vector< size_t > running(width, 0);
running[width/2] = 20;
for (size_t i = 0; i < 100; ++i)
{
size_t distance = rand()%18+8;
size_t length = rand()%20+2;
size_t col;
do {
col = rand()%width;
} while (running[col] > 0);
elements.push_back(Element(
(int)col - ((int)width)/2,
((double)(rand() % 5))/4 - 0.5,
base + distance,
length,
block( "" ),
Vector3(
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX
)
));
running[col] += distance + length;
size_t mindist = distance + length;
for (size_t j = 0; j < width; ++j)
mindist = std::min(mindist, running[j]);
for (size_t j = 0; j < width; ++j)
running[j] -= mindist;
base += mindist;
}
}
struct Column
{
char key;
double start, length;
};
struct BlockPos
{
BlockPos() : block(), ypos(0.0) { }
std::string block;
double ypos;
+ char flag;
};
void Map::loadMap( std::istream& is )
{
std::string line;
std::vector< std::list< BlockPos > > aliases(256);
std::vector< Element > newElements;
while ( std::getline( is, line ) )
{
if ( line == "%%" )
break;
std::istringstream iss( line );
char key;
iss >> key;
if ( key < 0 )
throw std::runtime_error( std::string("Invalid alias name ") + key );
BlockPos pos;
- while ( iss >> pos.block >> pos.ypos )
+ while ( iss >> pos.block )
{
if ( blocks.find( pos.block ) == blocks.end() )
throw std::runtime_error( "Unknown block " + pos.block );
+
+ std::string tmp;
+ if (!( iss >> tmp ))
+ throw std::runtime_error( "Unexpected end of line" );
+ if (tmp.size() == 1 && std::isalpha(tmp[0]))
+ {
+ pos.flag = tmp[0];
+ if (!( iss >> tmp ))
+ throw std::runtime_error( "Unexpected end of line" );
+ }
+ else
+ pos.flag = 0;
+ std::istringstream( tmp ) >> pos.ypos;
+
aliases[ key ].push_back( pos );
}
}
if ( !is || !std::getline( is, line ) )
throw std::runtime_error( "Unexpected eof before map." );
size_t columns;
{
std::istringstream iss( line );
iss >> columns;
}
Column emptyColumn = { ' ', 0, 0 };
std::vector< Column > runningdata(columns, emptyColumn);
double rowlength, position = 0.0;
while ( std::getline( is, line ) )
{
size_t seperator = line.find(':');
if ( seperator == std::string::npos )
throw std::runtime_error( "Missing seperator in map row." );
if ( sscanf( line.substr(0, seperator).c_str(), " %lf ", &rowlength ) != 1 )
throw std::runtime_error( "Invalid row length in map row." );
std::string row = line.substr( seperator+1 );
if ( row.length() > columns )
throw std::runtime_error( "Bad row size." );
else if ( row.length() < columns )
row.resize( columns, ' ' );
for (size_t i = 0; i < columns; ++i)
{
char key = row[i];
if ( key < 0 || ( key != ' ' && aliases[key].empty() ) )
throw std::runtime_error( std::string("Invalid alias name ") + key );
if ( key == runningdata[i].key )
{
runningdata[i].length += rowlength;
}
else
{
if ( runningdata[i].key != ' ' )
{
for ( std::list< BlockPos >::iterator posIter =
aliases[runningdata[i].key].begin();
posIter != aliases[runningdata[i].key].end();
++posIter)
{
newElements.push_back(Element(
( (double)i ) - ( (double)columns ) / 2,
posIter->ypos,
runningdata[i].start,
runningdata[i].length,
blocks.find( posIter->block )->second,
Vector3(
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX
)
));
}
}
runningdata[i].key = key;
runningdata[i].start = position;
runningdata[i].length = rowlength;
}
}
position += rowlength;
}
for (size_t i = 0; i < columns; ++i)
{
if ( runningdata[i].key != ' ' )
{
for ( std::list< BlockPos >::iterator posIter =
aliases[runningdata[i].key].begin();
posIter != aliases[runningdata[i].key].end();
++posIter)
{
newElements.push_back(Element(
( (double)i ) - ( (double)columns ) / 2,
posIter->ypos,
runningdata[i].start,
runningdata[i].length,
blocks.find( posIter->block )->second,
Vector3(
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX
)
));
}
}
}
_accelerator.clear();
using std::swap;
swap( elements, newElements );
}
|
devnev/skyways
|
fc238197a897c7fb2c5389e2ad8d5d45ed79b087
|
Fixed level generation so blocks don't overlap.
|
diff --git a/src/map.cpp b/src/map.cpp
index 1504f97..568c477 100644
--- a/src/map.cpp
+++ b/src/map.cpp
@@ -1,238 +1,257 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <algorithm>
#include <functional>
#include <fstream>
#include <string>
#include <sstream>
#include <list>
#include "map.hpp"
Map::Map( size_t sectionSize )
: _accelerator( sectionSize )
{
std::string empty;
blocks.insert( empty, new Block() );
}
void Map::glDraw( double )
{
for ( ElementList::iterator elem = elements.begin() ;
elem != elements.end(); ++elem )
{
elem->glDraw();
}
_elementsDrawn = elements.size();
}
void Map::loadBlocks()
{
using namespace boost::filesystem;
path block_dir( "blocks" );
if ( !exists( block_dir ) )
return;
for ( recursive_directory_iterator block_fs_entry( block_dir ) ;
block_fs_entry != recursive_directory_iterator() ;
++block_fs_entry )
{
if ( is_directory( block_fs_entry->status() ) )
continue;
std::string block_path;
path::iterator iter = block_fs_entry->path().begin();
++iter;
if ( iter != block_fs_entry->path().end() )
block_path = *iter;
for ( ++iter ; iter != block_fs_entry->path().end() ; ++iter )
block_path = block_path + "/" + *iter;
blocks.insert( block_path, Block::fromFile( block_fs_entry->path().string() ) );
}
}
void Map::optimize()
{
for ( ElementList::iterator elem = elements.begin() ;
elem != elements.end(); ++elem )
{
_accelerator.addElement( *elem );
}
}
bool Map::collide( const AABB& aabb )
{
return _accelerator.collide( aabb );
}
void Map::generateMap()
{
_accelerator.clear();
elements.clear();
elements.push_back(Element(
0, -1, 0, 20, block( "" ), Vector3( 1, 1, 1 )
));
+
+ size_t width = 7;
+ size_t base = 0;
+ std::vector< size_t > running(width, 0);
+ running[width/2] = 20;
+
for (size_t i = 0; i < 100; ++i)
{
+ size_t distance = rand()%18+8;
+ size_t length = rand()%20+2;
+ size_t col;
+ do {
+ col = rand()%width;
+ } while (running[col] > 0);
elements.push_back(Element(
- rand() % 7 - 3,
+ (int)col - ((int)width)/2,
((double)(rand() % 5))/4 - 0.5,
- rand() % 400,
- rand() % 20 + 2,
+ base + distance,
+ length,
block( "" ),
Vector3(
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX
)
));
+ running[col] += distance + length;
+ size_t mindist = distance + length;
+ for (size_t j = 0; j < width; ++j)
+ mindist = std::min(mindist, running[j]);
+ for (size_t j = 0; j < width; ++j)
+ running[j] -= mindist;
+ base += mindist;
}
}
struct Column
{
char key;
double start, length;
};
struct BlockPos
{
BlockPos() : block(), ypos(0.0) { }
std::string block;
double ypos;
};
void Map::loadMap( std::istream& is )
{
std::string line;
std::vector< std::list< BlockPos > > aliases(256);
std::vector< Element > newElements;
while ( std::getline( is, line ) )
{
if ( line == "%%" )
break;
std::istringstream iss( line );
char key;
iss >> key;
if ( key < 0 )
throw std::runtime_error( std::string("Invalid alias name ") + key );
BlockPos pos;
while ( iss >> pos.block >> pos.ypos )
{
if ( blocks.find( pos.block ) == blocks.end() )
throw std::runtime_error( "Unknown block " + pos.block );
aliases[ key ].push_back( pos );
}
}
if ( !is || !std::getline( is, line ) )
throw std::runtime_error( "Unexpected eof before map." );
size_t columns;
{
std::istringstream iss( line );
iss >> columns;
}
Column emptyColumn = { ' ', 0, 0 };
std::vector< Column > runningdata(columns, emptyColumn);
double rowlength, position = 0.0;
while ( std::getline( is, line ) )
{
size_t seperator = line.find(':');
if ( seperator == std::string::npos )
throw std::runtime_error( "Missing seperator in map row." );
if ( sscanf( line.substr(0, seperator).c_str(), " %lf ", &rowlength ) != 1 )
throw std::runtime_error( "Invalid row length in map row." );
std::string row = line.substr( seperator+1 );
if ( row.length() > columns )
throw std::runtime_error( "Bad row size." );
else if ( row.length() < columns )
row.resize( columns, ' ' );
for (size_t i = 0; i < columns; ++i)
{
char key = row[i];
if ( key < 0 || ( key != ' ' && aliases[key].empty() ) )
throw std::runtime_error( std::string("Invalid alias name ") + key );
if ( key == runningdata[i].key )
{
runningdata[i].length += rowlength;
}
else
{
if ( runningdata[i].key != ' ' )
{
for ( std::list< BlockPos >::iterator posIter =
aliases[runningdata[i].key].begin();
posIter != aliases[runningdata[i].key].end();
++posIter)
{
newElements.push_back(Element(
( (double)i ) - ( (double)columns ) / 2,
posIter->ypos,
runningdata[i].start,
runningdata[i].length,
blocks.find( posIter->block )->second,
Vector3(
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX
)
));
}
}
runningdata[i].key = key;
runningdata[i].start = position;
runningdata[i].length = rowlength;
}
}
position += rowlength;
}
for (size_t i = 0; i < columns; ++i)
{
if ( runningdata[i].key != ' ' )
{
for ( std::list< BlockPos >::iterator posIter =
aliases[runningdata[i].key].begin();
posIter != aliases[runningdata[i].key].end();
++posIter)
{
newElements.push_back(Element(
( (double)i ) - ( (double)columns ) / 2,
posIter->ypos,
runningdata[i].start,
runningdata[i].length,
blocks.find( posIter->block )->second,
Vector3(
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX,
( (double)rand() ) / RAND_MAX
)
));
}
}
}
_accelerator.clear();
using std::swap;
swap( elements, newElements );
}
|
devnev/skyways
|
24f3ad7a6d5fa1eb462750814cad1f08df40cf22
|
Added support for shader uniforms.
|
diff --git a/src/shader.cpp b/src/shader.cpp
index d367257..3d97ed0 100644
--- a/src/shader.cpp
+++ b/src/shader.cpp
@@ -1,139 +1,145 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <list>
#include <string>
#include <sstream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <vector>
#include <stdexcept>
#include <GL/glew.h>
#include "shader.hpp"
void ShaderSource::addShaderSource( const std::string& source )
{
_sources.push_back( source );
}
void ShaderSource::loadShaderSource( const char * filename )
{
std::ifstream fin;
fin.exceptions( std::ios::badbit | std::ios::failbit );
std::ostringstream sout;
fin.open( filename );
sout << fin.rdbuf();
fin.close();
addShaderSource( sout.str() );
}
void Shader::setSource(const ShaderSource& source)
{
std::list< std::string > sources = source.getSources();
if ( sources.size() == 0 )
{
throw std::runtime_error("Attempted to create shader with empty sources");
}
if ( sources.size() == 1 )
{
const char * cstr = sources.front().c_str();
glShaderSource(_shaderId, 1, &cstr, 0);
}
else
{
std::vector< const char* > strArray(sources.size(), 0);
size_t i = 0;
std::list< std::string >::iterator sourcestr = sources.begin();
for ( ; sourcestr != sources.end(); ++sourcestr, ++i )
{
strArray[i] = sourcestr->c_str();
}
glShaderSource(_shaderId, i, &strArray[0], 0);
}
}
void Shader::compile()
{
glCompileShader(_shaderId);
GLint status;
glGetShaderiv(_shaderId, GL_COMPILE_STATUS, &status);
if(status == GL_FALSE)
{
GLint length;
glGetShaderiv(_shaderId, GL_INFO_LOG_LENGTH, &length);
std::vector< char > errorstr(length);
glGetShaderInfoLog(_shaderId, length, NULL, &errorstr[0]);
throw std::runtime_error("Compile errors(s): " + std::string(&errorstr[0]));
}
}
void ShaderProgram::attachShader( Shader& shader )
{
glAttachShader( _programId, shader.getGlId() );
shaders.push_back( &shader );
}
+Uniform ShaderProgram::getUniform( const std::string& name )
+{
+ GLint location = glGetUniformLocation( _programId, name.c_str() );
+ return Uniform( location );
+}
+
void ShaderProgram::link()
{
std::for_each( shaders.begin(), shaders.end(), std::mem_fun( &Shader::compile ) );
glLinkProgram( _programId );
GLint status;
glGetProgramiv(_programId, GL_LINK_STATUS, &status);
if(status == GL_FALSE)
{
GLint length;
glGetProgramiv(_programId, GL_INFO_LOG_LENGTH, &length);
std::vector< char > errorstr(length);
glGetProgramInfoLog(_programId, length, NULL, &errorstr[0]);
throw std::runtime_error("Link error(s): " + std::string(&errorstr[0]));
}
_linked = true;
}
void ShaderProgram::use()
{
if (!_linked)
link();
glUseProgram( _programId );
}
std::auto_ptr< ShaderProgram >
createShaderProgram(
const char * vertexFilename,
const char * fragmentFilename
)
{
ShaderSource vertexSource;
vertexSource.loadShaderSource( vertexFilename );
Shader vertexShader( Shader::VertexShader );
vertexShader.setSource( vertexSource );
ShaderSource fragmentSource;
fragmentSource.loadShaderSource( fragmentFilename );
Shader fragmentShader( Shader::FragmentShader );
fragmentShader.setSource( fragmentSource );
std::auto_ptr< ShaderProgram > program( new ShaderProgram() );
program->attachShader( vertexShader );
program->attachShader( fragmentShader );
program->link();
return program;
}
diff --git a/src/shader.hpp b/src/shader.hpp
index 7003117..f7f217f 100644
--- a/src/shader.hpp
+++ b/src/shader.hpp
@@ -1,119 +1,122 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _SHADER_HPP_
#define _SHADER_HPP_
#include <list>
#include <string>
#include <vector>
#include <memory>
+#include "uniform.hpp"
class ShaderSource
{
public:
ShaderSource() { }
~ShaderSource() { }
void addShaderSource( const std::string& source );
void loadShaderSource( const char * filename );
std::list< std::string > getSources() const
{
return _sources;
}
private:
std::list< std::string > _sources;
};
class Shader
{
public:
enum ShaderType {
VertexShader = GL_VERTEX_SHADER,
FragmentShader = GL_FRAGMENT_SHADER,
};
Shader(ShaderType shaderType)
: _shaderType( shaderType )
, _shaderId( glCreateShader(shaderType) )
{
}
void setSource(const ShaderSource& source);
void compile();
GLuint getGlId()
{
return _shaderId;
}
private:
ShaderType _shaderType;
GLuint _shaderId;
};
class ShaderProgram
{
public:
ShaderProgram()
: _programId( glCreateProgram() )
, _linked( false )
{
}
void attachShader( Shader& shader );
+ Uniform getUniform( const std::string& name );
+
void link();
void use();
GLuint getGlId()
{
return _programId;
}
private:
std::vector< Shader* > shaders;
GLuint _programId;
bool _linked;
};
std::auto_ptr< ShaderProgram >
createShaderProgram(
const char * vertexFilename,
const char * fragmentFilename
);
#endif // _SHADER_HPP_
diff --git a/src/uniform.hpp b/src/uniform.hpp
new file mode 100644
index 0000000..db41049
--- /dev/null
+++ b/src/uniform.hpp
@@ -0,0 +1,70 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#ifndef _UNIFORM_HPP_
+#define _UNIFORM_HPP_
+
+#include <boost/preprocessor/repetition/enum.hpp>
+#include <boost/preprocessor/repetition/enum_params.hpp>
+#include <boost/preprocessor/facilities/empty.hpp>
+#include <GL/glew.h>
+
+class Uniform
+{
+
+public:
+
+ Uniform(GLint location)
+ : _location( location )
+ {
+ }
+
+ Uniform(const Uniform& other)
+ : _location( other._location )
+ {
+ }
+
+ ~Uniform()
+ {
+ }
+
+#define SETUNIFORM(n, t, glt) \
+ void setUniform(BOOST_PP_ENUM_PARAMS(n, t v)) { \
+ glUniform ## n ## glt (_location, BOOST_PP_ENUM_PARAMS(n, v)); \
+ } \
+ /**/
+
+ SETUNIFORM(1, float, f)
+ SETUNIFORM(2, float, f)
+ SETUNIFORM(3, float, f)
+ SETUNIFORM(4, float, f)
+ SETUNIFORM(1, int, i)
+ SETUNIFORM(2, int, i)
+ SETUNIFORM(3, int, i)
+ SETUNIFORM(4, int, i)
+
+#undef SETUNIFORM
+
+private:
+
+ GLint _location;
+
+};
+
+#endif // _UNIFORM_HPP_
|
devnev/skyways
|
afd7eedc6b496d5d79d045457d32a07d2a300536
|
Added shader reference to world, enable shader from there.
|
diff --git a/src/controller.cpp b/src/controller.cpp
index ce59257..c3a553f 100644
--- a/src/controller.cpp
+++ b/src/controller.cpp
@@ -1,197 +1,197 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <GL/glew.h>
#include <GL/gl.h>
#include <boost/format.hpp>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include "textprinter.hpp"
#include "shader.hpp"
#include "controller.hpp"
Controller::Controller(
std::auto_ptr< World > world
, double cameraheight, double cameradistance, double camerarotation
, Controller::QuitCallback cbQuit
, std::auto_ptr< TextPrinter > printer
)
: _world( world ), _map( 10 )
, _camy( cameraheight ), _camz( cameradistance ), _camrot( camerarotation )
, _dead( false ), _quitcb( cbQuit )
, _printer( printer )
, _windowwidth( 1 ), _windowheight( 1 )
{
_world->setMap( _map );
}
Controller::~Controller()
{
}
void Controller::keydown( int key )
{
switch ( key )
{
case STRAFE_L_KEY: _world->setStrafe( -1 ); break;
case STRAFE_R_KEY: _world->setStrafe( 1 ); break;
case ACCEL_KEY: _world->setAcceleration( 1 ); break;
case DECEL_KEY: _world->setAcceleration( -1 ); break;
case JUMP_KEY: _world->startJump(); break;
case QUIT_KEY:
if ( _dead )
{
_quitcb();
}
else
{
std::cout <<
"You committed suicide!\n"
"Distance traveled: " << _world->distanceTraveled() << std::endl;
_dead = true;
}
break;
}
}
void Controller::keyup( int key )
{
switch ( key )
{
case STRAFE_L_KEY:
_world->setStrafe( 0 );
break;
case STRAFE_R_KEY:
_world->setStrafe( 0 );
break;
case ACCEL_KEY:
_world->setAcceleration( 0 );
break;
case DECEL_KEY:
_world->setAcceleration( 0 );
break;
}
}
void Controller::loadMap( std::string filename )
{
_map.loadBlocks();
std::ifstream mapFile( filename.c_str() );
_map.loadMap( mapFile );
}
void Controller::generateMap()
{
_map.loadBlocks();
srand(time(0));
_map.generateMap();
}
void Controller::initialize()
{
GLenum err = glewInit();
if (err != GLEW_OK)
throw std::runtime_error((const char*)glewGetErrorString(err));
if (!GLEW_VERSION_2_0)
throw std::runtime_error("Nead OpenGL >= 2.0 for shaders. Update your graphics drivers!");
_shaderProgram = createShaderProgram("shaders/shader.glslv", "shaders/shader.glslf");
+ _world->setShader( *_shaderProgram );
glClearColor( 0.2, 0.2, 0.2, 0 );
glClearDepth( 1.0 );
glEnable( GL_DEPTH_TEST );
glDepthFunc( GL_LEQUAL );
glEnable( GL_CULL_FACE );
glEnable( GL_LIGHTING );
glShadeModel( GL_SMOOTH );
glEnable( GL_COLOR_MATERIAL );
glEnable( GL_NORMALIZE );
glEnable( GL_BLEND );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
glEnable( GL_LINE_SMOOTH );
glHint( GL_LINE_SMOOTH_HINT, GL_NICEST );
float ambient[] = { 0.2f, 0.2f, 0.2f, 1.0f };
float diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f };
float position[] = { 0.0f, 4.0f, -2.0f, 1.0f };
glLightfv( GL_LIGHT1, GL_AMBIENT, ambient );
glLightfv( GL_LIGHT1, GL_DIFFUSE, diffuse );
glLightfv( GL_LIGHT1, GL_POSITION, position );
glEnable( GL_LIGHT1 );
_map.optimize();
}
void Controller::resize( int width, int height )
{
glViewport( 0, 0, width, height );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
double fH = tan( 30.0 / 180.0 * 3.14159265358979323846 );
double fW = ( (double)width ) / ( (double)height ) * fH;
glFrustum( -fW, fW, -fH, fH, 1.0, 1000.0 );
glMatrixMode( GL_MODELVIEW );
_windowwidth = width;
_windowheight = height;
}
void Controller::draw()
{
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glLoadIdentity();
glRotatef( _camrot, 1, 0, 0 );
glTranslated( 0.0, -_camy, -_camz );
- _shaderProgram->use();
_world->draw( _camz );
if ( _dead )
{
glUseProgram(0);
_printer->print(
( boost::format( "Distance Traveled: %1%" ) % _world->distanceTraveled() ).str(),
_windowwidth / 2, _windowheight / 4 * 3,
TextPrinter::ALIGN_CENTER
);
}
}
void Controller::update( int difference )
{
if ( _dead )
return;
_world->update( difference );
if ( _world->droppedOut() )
{
std::cout <<
"You dropped into the void!\n"
"Distance traveled: " << _world->distanceTraveled() << std::endl;
_dead = true;
}
}
diff --git a/src/world.cpp b/src/world.cpp
index 65318b7..b1d3455 100644
--- a/src/world.cpp
+++ b/src/world.cpp
@@ -1,125 +1,127 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
-#include <GL/gl.h>
#include <cstdlib>
#include <ctime>
#include <cmath>
+#include "shader.hpp"
#include "world.hpp"
World::World(
double acceleration, double strafespeed, double speedlimit
, double gravity, double jumpstrength
+ , ShaderProgram * shader
)
- : _ship(), _map( 0 )
+ : _ship(), _map( 0 ), _shader( shader )
, _currAcc( 0 ), _maxAcc( acceleration )
, _currStrafe( 0 ), _maxStrafe( strafespeed )
, _maxSpeed( speedlimit ), _zspeed( 0 )
, _yapex( 0 ), _tapex( 0 ), _gravity( gravity )
, _jstrength( jumpstrength ), _grounded( true )
{
_ship.initialize();
_ship.pos().x = 0.5;
}
void World::startJump()
{
if ( _grounded ||
_map->collide( AABB(
_ship.pos().offset(0, -0.2, 0),
_ship.pos().offset(0, -0.2, 0).offset(_ship.size())
) ) )
{
_yapex = _ship.ypos() + _jstrength;
_tapex = sqrt( _jstrength / _gravity );
}
}
void World::draw( double zminClip )
{
+ _shader->use();
glPushMatrix();
glTranslated( _ship.xpos() - 0.5, _ship.ypos(), 0.0 );
glColor4f( 1, 0, 0, 0.25 );
_ship.drawDl();
glPopMatrix();
glColor3f( 0.8f, 1, 1 );
glTranslatef( -0.5, 0.0, _ship.zpos() );
_map->glDraw( _ship.zpos() - zminClip );
}
void World::update( int difference )
{
double multiplier = ( (double)difference ) / 1000;
Vector3 newPos = _ship.pos();
AABB shipAabb(
Vector3( -_ship.size().x/2, 0, 0 ),
Vector3( _ship.size().x/2, _ship.size().y, _ship.size().z )
);
if ( _currAcc < -_maxAcc ) _currAcc = -_maxAcc;
else if ( _currAcc > _maxAcc ) _currAcc = _maxAcc;
_zspeed += _currAcc*multiplier;
if ( _zspeed < 0 ) _zspeed = 0;
if ( _zspeed > _maxSpeed ) _zspeed = _maxSpeed;
newPos.z += multiplier * _zspeed;
if ( _map->collide( shipAabb.offset( newPos ) ) )
{
newPos.z = _ship.pos().z;
_zspeed = 0;
}
else
_ship.pos().z = newPos.z;
if ( _currStrafe < -_maxStrafe ) _currStrafe = -_maxStrafe;
if ( _currStrafe > _maxStrafe ) _currStrafe = _maxStrafe;
if ( _currStrafe != 0 )
{
newPos.x += _currStrafe*multiplier;
if ( _map->collide( shipAabb.offset( newPos ) ) )
newPos.x = _ship.pos().x;
else
_ship.pos().x = newPos.x;
}
if ( _tapex <= 0 && _grounded )
{
_tapex = 0;
_yapex = _ship.pos().y;
}
_tapex -= multiplier;
newPos.y = _yapex - _gravity * ( _tapex*_tapex );
if ( _map->collide( shipAabb.offset( newPos ) ) )
{
newPos.y = _ship.pos().y;
if (_tapex < 0)
_grounded = true;
_tapex = 0;
_yapex = _ship.pos().y;
}
else
{
_ship.pos().y = newPos.y;
_grounded = false;
}
}
diff --git a/src/world.hpp b/src/world.hpp
index b81f536..08ad5ed 100644
--- a/src/world.hpp
+++ b/src/world.hpp
@@ -1,62 +1,67 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _WORLD_HPP_
#define _WORLD_HPP_
#include "ship.hpp"
#include "map.hpp"
+class ShaderProgram;
+
class World
{
public:
World(
double acceleration, double strafespeed, double speedlimit
, double gravity, double jumpstrength
+ , ShaderProgram * shader = 0
);
void setMap(Map& map) throw() { _map = ↦ }
+ void setShader(ShaderProgram& shader) throw() { _shader = &shader; }
void setAcceleration( double accel ) { _currAcc = accel*_maxAcc; }
void setStrafe( double strafe ) { _currStrafe = strafe*_maxStrafe; }
void startJump();
void draw( double zminClip );
void update( int difference );
double distanceTraveled() const throw() { return _ship.pos().z; }
bool droppedOut() const throw() {
return _ship.pos().y < _map->lowestPoint() - 1;
}
private:
Ship _ship;
Map* _map;
+ ShaderProgram * _shader;
double _currAcc, _maxAcc;
double _currStrafe, _maxStrafe;
double _maxSpeed, _zspeed;
double _yapex, _tapex, _gravity;
double _jstrength;
bool _grounded;
};
#endif // _WORLD_HPP_
|
devnev/skyways
|
f3f66cb818a1c5b6bd0aaf7f2da00fc9a252502a
|
Changed rendering to reset shader before rendering text.
|
diff --git a/src/controller.cpp b/src/controller.cpp
index f27d998..ce59257 100644
--- a/src/controller.cpp
+++ b/src/controller.cpp
@@ -1,196 +1,197 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <GL/glew.h>
#include <GL/gl.h>
#include <boost/format.hpp>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include "textprinter.hpp"
#include "shader.hpp"
#include "controller.hpp"
Controller::Controller(
std::auto_ptr< World > world
, double cameraheight, double cameradistance, double camerarotation
, Controller::QuitCallback cbQuit
, std::auto_ptr< TextPrinter > printer
)
: _world( world ), _map( 10 )
, _camy( cameraheight ), _camz( cameradistance ), _camrot( camerarotation )
, _dead( false ), _quitcb( cbQuit )
, _printer( printer )
, _windowwidth( 1 ), _windowheight( 1 )
{
_world->setMap( _map );
}
Controller::~Controller()
{
}
void Controller::keydown( int key )
{
switch ( key )
{
case STRAFE_L_KEY: _world->setStrafe( -1 ); break;
case STRAFE_R_KEY: _world->setStrafe( 1 ); break;
case ACCEL_KEY: _world->setAcceleration( 1 ); break;
case DECEL_KEY: _world->setAcceleration( -1 ); break;
case JUMP_KEY: _world->startJump(); break;
case QUIT_KEY:
if ( _dead )
{
_quitcb();
}
else
{
std::cout <<
"You committed suicide!\n"
"Distance traveled: " << _world->distanceTraveled() << std::endl;
_dead = true;
}
break;
}
}
void Controller::keyup( int key )
{
switch ( key )
{
case STRAFE_L_KEY:
_world->setStrafe( 0 );
break;
case STRAFE_R_KEY:
_world->setStrafe( 0 );
break;
case ACCEL_KEY:
_world->setAcceleration( 0 );
break;
case DECEL_KEY:
_world->setAcceleration( 0 );
break;
}
}
void Controller::loadMap( std::string filename )
{
_map.loadBlocks();
std::ifstream mapFile( filename.c_str() );
_map.loadMap( mapFile );
}
void Controller::generateMap()
{
_map.loadBlocks();
srand(time(0));
_map.generateMap();
}
void Controller::initialize()
{
GLenum err = glewInit();
if (err != GLEW_OK)
throw std::runtime_error((const char*)glewGetErrorString(err));
if (!GLEW_VERSION_2_0)
throw std::runtime_error("Nead OpenGL >= 2.0 for shaders. Update your graphics drivers!");
_shaderProgram = createShaderProgram("shaders/shader.glslv", "shaders/shader.glslf");
- _shaderProgram->use();
glClearColor( 0.2, 0.2, 0.2, 0 );
glClearDepth( 1.0 );
glEnable( GL_DEPTH_TEST );
glDepthFunc( GL_LEQUAL );
glEnable( GL_CULL_FACE );
glEnable( GL_LIGHTING );
glShadeModel( GL_SMOOTH );
glEnable( GL_COLOR_MATERIAL );
glEnable( GL_NORMALIZE );
glEnable( GL_BLEND );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
glEnable( GL_LINE_SMOOTH );
glHint( GL_LINE_SMOOTH_HINT, GL_NICEST );
float ambient[] = { 0.2f, 0.2f, 0.2f, 1.0f };
float diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f };
float position[] = { 0.0f, 4.0f, -2.0f, 1.0f };
glLightfv( GL_LIGHT1, GL_AMBIENT, ambient );
glLightfv( GL_LIGHT1, GL_DIFFUSE, diffuse );
glLightfv( GL_LIGHT1, GL_POSITION, position );
glEnable( GL_LIGHT1 );
_map.optimize();
}
void Controller::resize( int width, int height )
{
glViewport( 0, 0, width, height );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
double fH = tan( 30.0 / 180.0 * 3.14159265358979323846 );
double fW = ( (double)width ) / ( (double)height ) * fH;
glFrustum( -fW, fW, -fH, fH, 1.0, 1000.0 );
glMatrixMode( GL_MODELVIEW );
_windowwidth = width;
_windowheight = height;
}
void Controller::draw()
{
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glLoadIdentity();
glRotatef( _camrot, 1, 0, 0 );
glTranslated( 0.0, -_camy, -_camz );
+ _shaderProgram->use();
_world->draw( _camz );
if ( _dead )
{
+ glUseProgram(0);
_printer->print(
( boost::format( "Distance Traveled: %1%" ) % _world->distanceTraveled() ).str(),
_windowwidth / 2, _windowheight / 4 * 3,
TextPrinter::ALIGN_CENTER
);
}
}
void Controller::update( int difference )
{
if ( _dead )
return;
_world->update( difference );
if ( _world->droppedOut() )
{
std::cout <<
"You dropped into the void!\n"
"Distance traveled: " << _world->distanceTraveled() << std::endl;
_dead = true;
}
}
|
devnev/skyways
|
4ed6d4e46b319af212a43b9b0ec9665d6015922a
|
Added method to load simple two-file shaders.
|
diff --git a/src/controller.cpp b/src/controller.cpp
index bc00c91..f27d998 100644
--- a/src/controller.cpp
+++ b/src/controller.cpp
@@ -1,207 +1,196 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <GL/glew.h>
#include <GL/gl.h>
#include <boost/format.hpp>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include "textprinter.hpp"
#include "shader.hpp"
#include "controller.hpp"
Controller::Controller(
std::auto_ptr< World > world
, double cameraheight, double cameradistance, double camerarotation
, Controller::QuitCallback cbQuit
, std::auto_ptr< TextPrinter > printer
)
: _world( world ), _map( 10 )
, _camy( cameraheight ), _camz( cameradistance ), _camrot( camerarotation )
, _dead( false ), _quitcb( cbQuit )
, _printer( printer )
, _windowwidth( 1 ), _windowheight( 1 )
{
_world->setMap( _map );
}
Controller::~Controller()
{
}
void Controller::keydown( int key )
{
switch ( key )
{
case STRAFE_L_KEY: _world->setStrafe( -1 ); break;
case STRAFE_R_KEY: _world->setStrafe( 1 ); break;
case ACCEL_KEY: _world->setAcceleration( 1 ); break;
case DECEL_KEY: _world->setAcceleration( -1 ); break;
case JUMP_KEY: _world->startJump(); break;
case QUIT_KEY:
if ( _dead )
{
_quitcb();
}
else
{
std::cout <<
"You committed suicide!\n"
"Distance traveled: " << _world->distanceTraveled() << std::endl;
_dead = true;
}
break;
}
}
void Controller::keyup( int key )
{
switch ( key )
{
case STRAFE_L_KEY:
_world->setStrafe( 0 );
break;
case STRAFE_R_KEY:
_world->setStrafe( 0 );
break;
case ACCEL_KEY:
_world->setAcceleration( 0 );
break;
case DECEL_KEY:
_world->setAcceleration( 0 );
break;
}
}
void Controller::loadMap( std::string filename )
{
_map.loadBlocks();
std::ifstream mapFile( filename.c_str() );
_map.loadMap( mapFile );
}
void Controller::generateMap()
{
_map.loadBlocks();
srand(time(0));
_map.generateMap();
}
void Controller::initialize()
{
GLenum err = glewInit();
if (err != GLEW_OK)
throw std::runtime_error((const char*)glewGetErrorString(err));
if (!GLEW_VERSION_2_0)
throw std::runtime_error("Nead OpenGL >= 2.0 for shaders. Update your graphics drivers!");
- ShaderSource vertexSource;
- vertexSource.loadShaderSource( "shaders/shader.glslv" );
- Shader vertexShader( Shader::VertexShader );
- vertexShader.setSource( vertexSource );
- ShaderSource fragmentSource;
- fragmentSource.loadShaderSource( "shaders/shader.glslf" );
- Shader fragmentShader( Shader::FragmentShader );
- fragmentShader.setSource( fragmentSource );
- _shaderProgram.reset( new ShaderProgram() );
- _shaderProgram->attachShader( vertexShader );
- _shaderProgram->attachShader( fragmentShader );
- _shaderProgram->link();
+ _shaderProgram = createShaderProgram("shaders/shader.glslv", "shaders/shader.glslf");
_shaderProgram->use();
glClearColor( 0.2, 0.2, 0.2, 0 );
glClearDepth( 1.0 );
glEnable( GL_DEPTH_TEST );
glDepthFunc( GL_LEQUAL );
glEnable( GL_CULL_FACE );
glEnable( GL_LIGHTING );
glShadeModel( GL_SMOOTH );
glEnable( GL_COLOR_MATERIAL );
glEnable( GL_NORMALIZE );
glEnable( GL_BLEND );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
glEnable( GL_LINE_SMOOTH );
glHint( GL_LINE_SMOOTH_HINT, GL_NICEST );
float ambient[] = { 0.2f, 0.2f, 0.2f, 1.0f };
float diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f };
float position[] = { 0.0f, 4.0f, -2.0f, 1.0f };
glLightfv( GL_LIGHT1, GL_AMBIENT, ambient );
glLightfv( GL_LIGHT1, GL_DIFFUSE, diffuse );
glLightfv( GL_LIGHT1, GL_POSITION, position );
glEnable( GL_LIGHT1 );
_map.optimize();
}
void Controller::resize( int width, int height )
{
glViewport( 0, 0, width, height );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
double fH = tan( 30.0 / 180.0 * 3.14159265358979323846 );
double fW = ( (double)width ) / ( (double)height ) * fH;
glFrustum( -fW, fW, -fH, fH, 1.0, 1000.0 );
glMatrixMode( GL_MODELVIEW );
_windowwidth = width;
_windowheight = height;
}
void Controller::draw()
{
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glLoadIdentity();
glRotatef( _camrot, 1, 0, 0 );
glTranslated( 0.0, -_camy, -_camz );
_world->draw( _camz );
if ( _dead )
{
_printer->print(
( boost::format( "Distance Traveled: %1%" ) % _world->distanceTraveled() ).str(),
_windowwidth / 2, _windowheight / 4 * 3,
TextPrinter::ALIGN_CENTER
);
}
}
void Controller::update( int difference )
{
if ( _dead )
return;
_world->update( difference );
if ( _world->droppedOut() )
{
std::cout <<
"You dropped into the void!\n"
"Distance traveled: " << _world->distanceTraveled() << std::endl;
_dead = true;
}
}
diff --git a/src/shader.cpp b/src/shader.cpp
index 144b28f..d367257 100644
--- a/src/shader.cpp
+++ b/src/shader.cpp
@@ -1,118 +1,139 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <list>
#include <string>
#include <sstream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <vector>
#include <stdexcept>
#include <GL/glew.h>
#include "shader.hpp"
void ShaderSource::addShaderSource( const std::string& source )
{
_sources.push_back( source );
}
void ShaderSource::loadShaderSource( const char * filename )
{
std::ifstream fin;
fin.exceptions( std::ios::badbit | std::ios::failbit );
std::ostringstream sout;
fin.open( filename );
sout << fin.rdbuf();
fin.close();
addShaderSource( sout.str() );
}
void Shader::setSource(const ShaderSource& source)
{
std::list< std::string > sources = source.getSources();
if ( sources.size() == 0 )
{
throw std::runtime_error("Attempted to create shader with empty sources");
}
if ( sources.size() == 1 )
{
const char * cstr = sources.front().c_str();
glShaderSource(_shaderId, 1, &cstr, 0);
}
else
{
std::vector< const char* > strArray(sources.size(), 0);
size_t i = 0;
std::list< std::string >::iterator sourcestr = sources.begin();
for ( ; sourcestr != sources.end(); ++sourcestr, ++i )
{
strArray[i] = sourcestr->c_str();
}
glShaderSource(_shaderId, i, &strArray[0], 0);
}
}
void Shader::compile()
{
glCompileShader(_shaderId);
GLint status;
glGetShaderiv(_shaderId, GL_COMPILE_STATUS, &status);
if(status == GL_FALSE)
{
GLint length;
glGetShaderiv(_shaderId, GL_INFO_LOG_LENGTH, &length);
std::vector< char > errorstr(length);
glGetShaderInfoLog(_shaderId, length, NULL, &errorstr[0]);
throw std::runtime_error("Compile errors(s): " + std::string(&errorstr[0]));
}
}
void ShaderProgram::attachShader( Shader& shader )
{
glAttachShader( _programId, shader.getGlId() );
shaders.push_back( &shader );
}
void ShaderProgram::link()
{
std::for_each( shaders.begin(), shaders.end(), std::mem_fun( &Shader::compile ) );
glLinkProgram( _programId );
GLint status;
glGetProgramiv(_programId, GL_LINK_STATUS, &status);
if(status == GL_FALSE)
{
GLint length;
glGetProgramiv(_programId, GL_INFO_LOG_LENGTH, &length);
std::vector< char > errorstr(length);
glGetProgramInfoLog(_programId, length, NULL, &errorstr[0]);
throw std::runtime_error("Link error(s): " + std::string(&errorstr[0]));
}
_linked = true;
}
void ShaderProgram::use()
{
if (!_linked)
link();
glUseProgram( _programId );
}
+
+std::auto_ptr< ShaderProgram >
+createShaderProgram(
+ const char * vertexFilename,
+ const char * fragmentFilename
+)
+{
+ ShaderSource vertexSource;
+ vertexSource.loadShaderSource( vertexFilename );
+ Shader vertexShader( Shader::VertexShader );
+ vertexShader.setSource( vertexSource );
+ ShaderSource fragmentSource;
+ fragmentSource.loadShaderSource( fragmentFilename );
+ Shader fragmentShader( Shader::FragmentShader );
+ fragmentShader.setSource( fragmentSource );
+ std::auto_ptr< ShaderProgram > program( new ShaderProgram() );
+ program->attachShader( vertexShader );
+ program->attachShader( fragmentShader );
+ program->link();
+ return program;
+}
diff --git a/src/shader.hpp b/src/shader.hpp
index accc5ce..7003117 100644
--- a/src/shader.hpp
+++ b/src/shader.hpp
@@ -1,112 +1,119 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _SHADER_HPP_
#define _SHADER_HPP_
#include <list>
#include <string>
#include <vector>
+#include <memory>
class ShaderSource
{
public:
ShaderSource() { }
~ShaderSource() { }
void addShaderSource( const std::string& source );
void loadShaderSource( const char * filename );
std::list< std::string > getSources() const
{
return _sources;
}
private:
std::list< std::string > _sources;
};
class Shader
{
public:
enum ShaderType {
VertexShader = GL_VERTEX_SHADER,
FragmentShader = GL_FRAGMENT_SHADER,
};
Shader(ShaderType shaderType)
: _shaderType( shaderType )
, _shaderId( glCreateShader(shaderType) )
{
}
void setSource(const ShaderSource& source);
void compile();
GLuint getGlId()
{
return _shaderId;
}
private:
ShaderType _shaderType;
GLuint _shaderId;
};
class ShaderProgram
{
public:
ShaderProgram()
: _programId( glCreateProgram() )
, _linked( false )
{
}
void attachShader( Shader& shader );
void link();
void use();
GLuint getGlId()
{
return _programId;
}
private:
std::vector< Shader* > shaders;
GLuint _programId;
bool _linked;
};
+std::auto_ptr< ShaderProgram >
+createShaderProgram(
+ const char * vertexFilename,
+ const char * fragmentFilename
+);
+
#endif // _SHADER_HPP_
|
devnev/skyways
|
a4eac87360b1d76c2c19e841b8d9975a27d6b960
|
Moved shader implementation into shader.cpp file, updated Makefile.
|
diff --git a/Makefile b/Makefile
index 34631fe..69a6f86 100644
--- a/Makefile
+++ b/Makefile
@@ -1,153 +1,155 @@
###########################
# prelude: do not change! #
###########################
CWD:=$(shell pwd)
default: all
BUILDFLAGS=CFLAGS CPPFLAGS CXXFLAGS LDFLAGS
define FLAGINIT_template
ifndef $(1)
$(1)=
endif
endef
$(foreach flag,$(BUILDFLAGS),$(eval $(call FLAGINIT_template,$(flag))))
######################################
# configuration: change things here. #
######################################
PROGRAMS=SkywaysGlut SkywaysQt SkywaysSdl
SkywaysGlut_BINARY=skyways.glut
SkywaysQt_BINARY=skyways.qt
SkywaysSdl_BINARY=skyways.sdl
HEADERS= \
src/aabb.hpp \
src/block.hpp \
src/collisionaccelerator.hpp \
src/configuration.hpp \
src/controller.hpp \
src/element.hpp \
src/map.hpp \
src/model.hpp \
src/objmodel.hpp \
+ src/shader.hpp \
src/ship.hpp \
src/textprinter.hpp \
src/vector.hpp \
src/world.hpp
SkywasyGlut_HEADERS= $(HEADERS) \
src/configparser.hpp
SkywasyQt_HEADERS= $(HEADERS) \
src/qtconfigparser.hpp \
src/qtwindow.hpp
SkywaysSdl_HEADERS= $(HEADERS) \
src/configparser.hpp
CXXSOURCES= \
src/block.cpp \
src/collisionaccelerator.cpp \
src/configuration.cpp \
src/controller.cpp \
src/element.cpp \
src/map.cpp \
src/objmodel.cpp \
+ src/shader.cpp \
src/ship.cpp \
src/textprinter.cpp \
src/world.cpp
SkywaysGlut_CXXSOURCES= $(CXXSOURCES) \
src/configparser.cpp \
src/glutmain.cpp
SkywaysQt_CXXSOURCES= $(CXXSOURCES) \
src/moc_qtwindow.cpp \
src/qtconfigparser.cpp \
src/qtmain.cpp \
src/qtwindow.cpp
SkywaysSdl_CXXSOURCES= $(CXXSOURCES) \
src/configparser.cpp \
src/sdlmain.cpp
CPPFLAGS+= -O2 -g -Wall -I/usr/include/FTGL -I/usr/include/freetype2
LDFLAGS+= -lGL -lboost_filesystem -lftgl -lGLEW
SkywaysGlut_LDFLAGS=-lglut -lboost_program_options
SkywaysQt_LDFLAGS=-lQtOpenGL -lQtGui -lQtCore -lGLU -lGL -lpthread
SkywaysQt_CPPFLAGS=-D_REENTRANT -DQT_NO_DEBUG -DQT_OPENGL_LIB -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED -I/usr/include/qt4/QtCore -I/usr/include/qt4/QtGui -I/usr/include/qt4/QtOpenGL -I/usr/include/qt4
SkywaysSdl_LDFLAGS=-lSDL -lboost_program_options
SkywaysSdl_CPPFLAGS=-I/usr/include/SDL
EXTRADIST=
######################################
# auto-configuration: do not change! #
######################################
$(foreach prog,$(PROGRAMS),$(eval $(prog)_SOURCES=$($(prog)_CSOURCES) $($(prog)_CXXSOURCES)))
$(foreach prog,$(PROGRAMS),$(eval $(prog)_OBJECTS=$(patsubst %.c,%_$(prog).o,$($(prog)_CSOURCES)) $(patsubst %.cpp,%_$(prog).o,$($(prog)_CXXSOURCES))))
$(foreach flag,CFLAGS CPPFLAGS CXXFLAGS LDFLAGS,$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_$(flag)=$($(flag)) $($(prog)_$(flag)))))
#CSOURCES=$(foreach prog,$(PROGRAMS),$($(prog)_CSOURCES))
#CXXSOURCES=$(foreach prog,$(PROGRAMS),$($(prog)_CXXSOURCES))
#SOURCES=$(CSOURCES) $(CXXSOURCES)
#HEADERS=$(foreach prog,$(PROGRAMS),$($(prog)_HEADERS))
OBJECTS=$(foreach prog,$(PROGRAMS),$($(prog)_OBJECTS))
BINARIES=$(foreach prog,$(PROGRAMS),$($(prog)_BINARY))
DEPENDS=$(patsubst %.o,%.d,$(OBJECTS))
define CDEP_template
%_$(1).d: %.c
set -e; rm -f "$$@" || true; \
$$(CC) -MM -MQ "`echo "$$<" | sed 's,\($$*\)\.c,\1_$(1).o,'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) "$$<" | \
sed 's,\($$*_$(1)\).o *:,\1.o $$@:,' >$$@
endef
define CXXDEP_template
%_$(1).d: %.cpp
set -e; rm -f "$$@" || true; \
$$(CXX) -MM -MQ "`echo "$$<" | sed 's,\($$*\)\.cpp,\1_$(1).o,'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) "$$<" | \
sed 's,\($$*_$(1)\).o *:,\1.o $$@:,' >$$@
endef
define CSRC_template
%_$(1).o: %.c
$$(CC) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) $$< -o $$@
endef
define CXXSRC_template
%_$(1).o: %.cpp
$$(CXX) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) $$< -o $$@
endef
define BINARY_template
$$($(1)_BINARY): $$($(1)_OBJECTS)
$$(CC) $$($(1)_ALL_LDFLAGS) $$^ $$(LOADLIBS) $$(LDLIBS) -o $$@
endef
$(foreach template,CDEP CXXDEP CSRC CXXSRC BINARY,$(foreach prog,$(PROGRAMS),$(eval $(call $(template)_template,$(prog)))))
all: $(BINARIES)
#################################
# extra stuff: change as needed #
#################################
clean:
rm $(OBJECTS) $(BINARIES) $(DEPENDS) $(DISTFILES) || true
moc_%.cpp: %.hpp
moc-qt4 $(SkywaysQt_CPPFLAGS) $(SkywaysQt_CXXFLAGS) $< -o $@
.PHONY: default clean
-include $(DEPENDS)
diff --git a/src/shader.cpp b/src/shader.cpp
new file mode 100644
index 0000000..144b28f
--- /dev/null
+++ b/src/shader.cpp
@@ -0,0 +1,118 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#include <list>
+#include <string>
+#include <sstream>
+#include <fstream>
+#include <iterator>
+#include <algorithm>
+#include <vector>
+#include <stdexcept>
+#include <GL/glew.h>
+#include "shader.hpp"
+
+void ShaderSource::addShaderSource( const std::string& source )
+{
+ _sources.push_back( source );
+}
+
+void ShaderSource::loadShaderSource( const char * filename )
+{
+ std::ifstream fin;
+ fin.exceptions( std::ios::badbit | std::ios::failbit );
+ std::ostringstream sout;
+ fin.open( filename );
+ sout << fin.rdbuf();
+ fin.close();
+ addShaderSource( sout.str() );
+}
+
+void Shader::setSource(const ShaderSource& source)
+{
+ std::list< std::string > sources = source.getSources();
+ if ( sources.size() == 0 )
+ {
+ throw std::runtime_error("Attempted to create shader with empty sources");
+ }
+ if ( sources.size() == 1 )
+ {
+ const char * cstr = sources.front().c_str();
+ glShaderSource(_shaderId, 1, &cstr, 0);
+ }
+ else
+ {
+ std::vector< const char* > strArray(sources.size(), 0);
+ size_t i = 0;
+ std::list< std::string >::iterator sourcestr = sources.begin();
+ for ( ; sourcestr != sources.end(); ++sourcestr, ++i )
+ {
+ strArray[i] = sourcestr->c_str();
+ }
+ glShaderSource(_shaderId, i, &strArray[0], 0);
+ }
+}
+
+void Shader::compile()
+{
+ glCompileShader(_shaderId);
+
+ GLint status;
+ glGetShaderiv(_shaderId, GL_COMPILE_STATUS, &status);
+ if(status == GL_FALSE)
+ {
+ GLint length;
+ glGetShaderiv(_shaderId, GL_INFO_LOG_LENGTH, &length);
+ std::vector< char > errorstr(length);
+ glGetShaderInfoLog(_shaderId, length, NULL, &errorstr[0]);
+ throw std::runtime_error("Compile errors(s): " + std::string(&errorstr[0]));
+ }
+}
+
+void ShaderProgram::attachShader( Shader& shader )
+{
+ glAttachShader( _programId, shader.getGlId() );
+ shaders.push_back( &shader );
+}
+
+void ShaderProgram::link()
+{
+ std::for_each( shaders.begin(), shaders.end(), std::mem_fun( &Shader::compile ) );
+ glLinkProgram( _programId );
+
+ GLint status;
+ glGetProgramiv(_programId, GL_LINK_STATUS, &status);
+ if(status == GL_FALSE)
+ {
+ GLint length;
+ glGetProgramiv(_programId, GL_INFO_LOG_LENGTH, &length);
+ std::vector< char > errorstr(length);
+ glGetProgramInfoLog(_programId, length, NULL, &errorstr[0]);
+ throw std::runtime_error("Link error(s): " + std::string(&errorstr[0]));
+ }
+
+ _linked = true;
+}
+
+void ShaderProgram::use()
+{
+ if (!_linked)
+ link();
+ glUseProgram( _programId );
+}
diff --git a/src/shader.hpp b/src/shader.hpp
index ece099d..accc5ce 100644
--- a/src/shader.hpp
+++ b/src/shader.hpp
@@ -1,192 +1,112 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _SHADER_HPP_
#define _SHADER_HPP_
#include <list>
#include <string>
-#include <sstream>
-#include <fstream>
-#include <iterator>
-#include <algorithm>
#include <vector>
-#include <stdexcept>
class ShaderSource
{
public:
ShaderSource() { }
~ShaderSource() { }
- void addShaderSource( const std::string& source )
- {
- _sources.push_back( source );
- }
+ void addShaderSource( const std::string& source );
- void loadShaderSource( const char * filename )
- {
- std::ifstream fin;
- fin.exceptions( std::ios::badbit | std::ios::failbit );
- std::ostringstream sout;
- fin.open( filename );
- sout << fin.rdbuf();
- fin.close();
- addShaderSource( sout.str() );
- }
+ void loadShaderSource( const char * filename );
std::list< std::string > getSources() const
{
return _sources;
}
private:
std::list< std::string > _sources;
};
class Shader
{
public:
enum ShaderType {
VertexShader = GL_VERTEX_SHADER,
FragmentShader = GL_FRAGMENT_SHADER,
};
Shader(ShaderType shaderType)
: _shaderType( shaderType )
, _shaderId( glCreateShader(shaderType) )
{
}
- void setSource(const ShaderSource& source)
- {
- std::list< std::string > sources = source.getSources();
- if ( sources.size() == 0 )
- {
- throw std::runtime_error("Attempted to create shader with empty sources");
- }
- if ( sources.size() == 1 )
- {
- const char * cstr = sources.front().c_str();
- glShaderSource(_shaderId, 1, &cstr, 0);
- }
- else
- {
- std::vector< const char* > strArray(sources.size(), 0);
- size_t i = 0;
- std::list< std::string >::iterator sourcestr = sources.begin();
- for ( ; sourcestr != sources.end(); ++sourcestr, ++i )
- {
- strArray[i] = sourcestr->c_str();
- }
- glShaderSource(_shaderId, i, &strArray[0], 0);
- }
- }
+ void setSource(const ShaderSource& source);
- void compile()
- {
- glCompileShader(_shaderId);
-
- GLint status;
- glGetShaderiv(_shaderId, GL_COMPILE_STATUS, &status);
- if(status == GL_FALSE)
- {
- GLint length;
- glGetShaderiv(_shaderId, GL_INFO_LOG_LENGTH, &length);
- std::vector< char > errorstr(length);
- glGetShaderInfoLog(_shaderId, length, NULL, &errorstr[0]);
- throw std::runtime_error("Compile errors(s): " + std::string(&errorstr[0]));
- }
- }
+ void compile();
GLuint getGlId()
{
return _shaderId;
}
private:
ShaderType _shaderType;
GLuint _shaderId;
};
class ShaderProgram
{
public:
ShaderProgram()
: _programId( glCreateProgram() )
, _linked( false )
{
}
- void attachShader( Shader& shader )
- {
- glAttachShader( _programId, shader.getGlId() );
- shaders.push_back( &shader );
- }
+ void attachShader( Shader& shader );
- void link()
- {
- std::for_each( shaders.begin(), shaders.end(), std::mem_fun( &Shader::compile ) );
- glLinkProgram( _programId );
-
- GLint status;
- glGetProgramiv(_programId, GL_LINK_STATUS, &status);
- if(status == GL_FALSE)
- {
- GLint length;
- glGetProgramiv(_programId, GL_INFO_LOG_LENGTH, &length);
- std::vector< char > errorstr(length);
- glGetProgramInfoLog(_programId, length, NULL, &errorstr[0]);
- throw std::runtime_error("Link error(s): " + std::string(&errorstr[0]));
- }
-
- _linked = true;
- }
+ void link();
- void use()
- {
- if (!_linked)
- link();
- glUseProgram( _programId );
- }
+ void use();
GLuint getGlId()
{
return _programId;
}
private:
std::vector< Shader* > shaders;
GLuint _programId;
bool _linked;
};
#endif // _SHADER_HPP_
|
devnev/skyways
|
42cc18db72338dd709a7ff67a84620d61a85f1e3
|
Added status check to shader program linking.
|
diff --git a/src/shader.hpp b/src/shader.hpp
index f37d90e..ece099d 100644
--- a/src/shader.hpp
+++ b/src/shader.hpp
@@ -1,180 +1,192 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _SHADER_HPP_
#define _SHADER_HPP_
#include <list>
#include <string>
#include <sstream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <vector>
#include <stdexcept>
class ShaderSource
{
public:
ShaderSource() { }
~ShaderSource() { }
void addShaderSource( const std::string& source )
{
_sources.push_back( source );
}
void loadShaderSource( const char * filename )
{
std::ifstream fin;
fin.exceptions( std::ios::badbit | std::ios::failbit );
std::ostringstream sout;
fin.open( filename );
sout << fin.rdbuf();
fin.close();
addShaderSource( sout.str() );
}
std::list< std::string > getSources() const
{
return _sources;
}
private:
std::list< std::string > _sources;
};
class Shader
{
public:
enum ShaderType {
VertexShader = GL_VERTEX_SHADER,
FragmentShader = GL_FRAGMENT_SHADER,
};
Shader(ShaderType shaderType)
: _shaderType( shaderType )
, _shaderId( glCreateShader(shaderType) )
{
}
void setSource(const ShaderSource& source)
{
std::list< std::string > sources = source.getSources();
if ( sources.size() == 0 )
{
throw std::runtime_error("Attempted to create shader with empty sources");
}
if ( sources.size() == 1 )
{
const char * cstr = sources.front().c_str();
glShaderSource(_shaderId, 1, &cstr, 0);
}
else
{
std::vector< const char* > strArray(sources.size(), 0);
size_t i = 0;
std::list< std::string >::iterator sourcestr = sources.begin();
for ( ; sourcestr != sources.end(); ++sourcestr, ++i )
{
strArray[i] = sourcestr->c_str();
}
glShaderSource(_shaderId, i, &strArray[0], 0);
}
}
void compile()
{
glCompileShader(_shaderId);
GLint status;
glGetShaderiv(_shaderId, GL_COMPILE_STATUS, &status);
if(status == GL_FALSE)
{
GLint length;
glGetShaderiv(_shaderId, GL_INFO_LOG_LENGTH, &length);
std::vector< char > errorstr(length);
glGetShaderInfoLog(_shaderId, length, NULL, &errorstr[0]);
throw std::runtime_error("Compile errors(s): " + std::string(&errorstr[0]));
}
}
GLuint getGlId()
{
return _shaderId;
}
private:
ShaderType _shaderType;
GLuint _shaderId;
};
class ShaderProgram
{
public:
ShaderProgram()
: _programId( glCreateProgram() )
, _linked( false )
{
}
void attachShader( Shader& shader )
{
glAttachShader( _programId, shader.getGlId() );
shaders.push_back( &shader );
}
void link()
{
std::for_each( shaders.begin(), shaders.end(), std::mem_fun( &Shader::compile ) );
glLinkProgram( _programId );
+
+ GLint status;
+ glGetProgramiv(_programId, GL_LINK_STATUS, &status);
+ if(status == GL_FALSE)
+ {
+ GLint length;
+ glGetProgramiv(_programId, GL_INFO_LOG_LENGTH, &length);
+ std::vector< char > errorstr(length);
+ glGetProgramInfoLog(_programId, length, NULL, &errorstr[0]);
+ throw std::runtime_error("Link error(s): " + std::string(&errorstr[0]));
+ }
+
_linked = true;
}
void use()
{
if (!_linked)
link();
glUseProgram( _programId );
}
GLuint getGlId()
{
return _programId;
}
private:
std::vector< Shader* > shaders;
GLuint _programId;
bool _linked;
};
#endif // _SHADER_HPP_
|
devnev/skyways
|
c58403c0fc029bf30114aceae378616f780b5858
|
Added status check to shader compilation.
|
diff --git a/src/shader.hpp b/src/shader.hpp
index 289998d..f37d90e 100644
--- a/src/shader.hpp
+++ b/src/shader.hpp
@@ -1,169 +1,180 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _SHADER_HPP_
#define _SHADER_HPP_
#include <list>
#include <string>
#include <sstream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <vector>
#include <stdexcept>
class ShaderSource
{
public:
ShaderSource() { }
~ShaderSource() { }
void addShaderSource( const std::string& source )
{
_sources.push_back( source );
}
void loadShaderSource( const char * filename )
{
std::ifstream fin;
fin.exceptions( std::ios::badbit | std::ios::failbit );
std::ostringstream sout;
fin.open( filename );
sout << fin.rdbuf();
fin.close();
addShaderSource( sout.str() );
}
std::list< std::string > getSources() const
{
return _sources;
}
private:
std::list< std::string > _sources;
};
class Shader
{
public:
enum ShaderType {
VertexShader = GL_VERTEX_SHADER,
FragmentShader = GL_FRAGMENT_SHADER,
};
Shader(ShaderType shaderType)
: _shaderType( shaderType )
, _shaderId( glCreateShader(shaderType) )
{
}
void setSource(const ShaderSource& source)
{
std::list< std::string > sources = source.getSources();
if ( sources.size() == 0 )
{
throw std::runtime_error("Attempted to create shader with empty sources");
}
if ( sources.size() == 1 )
{
const char * cstr = sources.front().c_str();
glShaderSource(_shaderId, 1, &cstr, 0);
}
else
{
std::vector< const char* > strArray(sources.size(), 0);
size_t i = 0;
std::list< std::string >::iterator sourcestr = sources.begin();
for ( ; sourcestr != sources.end(); ++sourcestr, ++i )
{
strArray[i] = sourcestr->c_str();
}
glShaderSource(_shaderId, i, &strArray[0], 0);
}
}
void compile()
{
glCompileShader(_shaderId);
+
+ GLint status;
+ glGetShaderiv(_shaderId, GL_COMPILE_STATUS, &status);
+ if(status == GL_FALSE)
+ {
+ GLint length;
+ glGetShaderiv(_shaderId, GL_INFO_LOG_LENGTH, &length);
+ std::vector< char > errorstr(length);
+ glGetShaderInfoLog(_shaderId, length, NULL, &errorstr[0]);
+ throw std::runtime_error("Compile errors(s): " + std::string(&errorstr[0]));
+ }
}
GLuint getGlId()
{
return _shaderId;
}
private:
ShaderType _shaderType;
GLuint _shaderId;
};
class ShaderProgram
{
public:
ShaderProgram()
: _programId( glCreateProgram() )
, _linked( false )
{
}
void attachShader( Shader& shader )
{
glAttachShader( _programId, shader.getGlId() );
shaders.push_back( &shader );
}
void link()
{
std::for_each( shaders.begin(), shaders.end(), std::mem_fun( &Shader::compile ) );
glLinkProgram( _programId );
_linked = true;
}
void use()
{
if (!_linked)
link();
glUseProgram( _programId );
}
GLuint getGlId()
{
return _programId;
}
private:
std::vector< Shader* > shaders;
GLuint _programId;
bool _linked;
};
#endif // _SHADER_HPP_
|
devnev/skyways
|
9de2544caa559f3067e4b85646b12edc37e808b2
|
Added preliminary OpenGL shader support.
|
diff --git a/shaders/shader.glslf b/shaders/shader.glslf
new file mode 100644
index 0000000..5d7b89e
--- /dev/null
+++ b/shaders/shader.glslf
@@ -0,0 +1,4 @@
+void main()
+{
+ gl_FragColor = gl_Color;
+}
diff --git a/shaders/shader.glslv b/shaders/shader.glslv
new file mode 100644
index 0000000..567512d
--- /dev/null
+++ b/shaders/shader.glslv
@@ -0,0 +1,5 @@
+void main()
+{
+ gl_FrontColor = gl_Color;
+ gl_Position = ftransform();
+}
diff --git a/src/controller.cpp b/src/controller.cpp
index 1398731..bc00c91 100644
--- a/src/controller.cpp
+++ b/src/controller.cpp
@@ -1,192 +1,207 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#include <GL/glew.h>
#include <GL/gl.h>
#include <boost/format.hpp>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include "textprinter.hpp"
+#include "shader.hpp"
#include "controller.hpp"
Controller::Controller(
std::auto_ptr< World > world
, double cameraheight, double cameradistance, double camerarotation
, Controller::QuitCallback cbQuit
, std::auto_ptr< TextPrinter > printer
)
: _world( world ), _map( 10 )
, _camy( cameraheight ), _camz( cameradistance ), _camrot( camerarotation )
, _dead( false ), _quitcb( cbQuit )
, _printer( printer )
, _windowwidth( 1 ), _windowheight( 1 )
{
_world->setMap( _map );
}
Controller::~Controller()
{
}
void Controller::keydown( int key )
{
switch ( key )
{
case STRAFE_L_KEY: _world->setStrafe( -1 ); break;
case STRAFE_R_KEY: _world->setStrafe( 1 ); break;
case ACCEL_KEY: _world->setAcceleration( 1 ); break;
case DECEL_KEY: _world->setAcceleration( -1 ); break;
case JUMP_KEY: _world->startJump(); break;
case QUIT_KEY:
if ( _dead )
{
_quitcb();
}
else
{
std::cout <<
"You committed suicide!\n"
"Distance traveled: " << _world->distanceTraveled() << std::endl;
_dead = true;
}
break;
}
}
void Controller::keyup( int key )
{
switch ( key )
{
case STRAFE_L_KEY:
_world->setStrafe( 0 );
break;
case STRAFE_R_KEY:
_world->setStrafe( 0 );
break;
case ACCEL_KEY:
_world->setAcceleration( 0 );
break;
case DECEL_KEY:
_world->setAcceleration( 0 );
break;
}
}
void Controller::loadMap( std::string filename )
{
_map.loadBlocks();
std::ifstream mapFile( filename.c_str() );
_map.loadMap( mapFile );
}
void Controller::generateMap()
{
_map.loadBlocks();
srand(time(0));
_map.generateMap();
}
void Controller::initialize()
{
GLenum err = glewInit();
if (err != GLEW_OK)
throw std::runtime_error((const char*)glewGetErrorString(err));
if (!GLEW_VERSION_2_0)
throw std::runtime_error("Nead OpenGL >= 2.0 for shaders. Update your graphics drivers!");
+ ShaderSource vertexSource;
+ vertexSource.loadShaderSource( "shaders/shader.glslv" );
+ Shader vertexShader( Shader::VertexShader );
+ vertexShader.setSource( vertexSource );
+ ShaderSource fragmentSource;
+ fragmentSource.loadShaderSource( "shaders/shader.glslf" );
+ Shader fragmentShader( Shader::FragmentShader );
+ fragmentShader.setSource( fragmentSource );
+ _shaderProgram.reset( new ShaderProgram() );
+ _shaderProgram->attachShader( vertexShader );
+ _shaderProgram->attachShader( fragmentShader );
+ _shaderProgram->link();
+ _shaderProgram->use();
+
glClearColor( 0.2, 0.2, 0.2, 0 );
glClearDepth( 1.0 );
glEnable( GL_DEPTH_TEST );
glDepthFunc( GL_LEQUAL );
glEnable( GL_CULL_FACE );
glEnable( GL_LIGHTING );
glShadeModel( GL_SMOOTH );
glEnable( GL_COLOR_MATERIAL );
glEnable( GL_NORMALIZE );
glEnable( GL_BLEND );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
glEnable( GL_LINE_SMOOTH );
glHint( GL_LINE_SMOOTH_HINT, GL_NICEST );
float ambient[] = { 0.2f, 0.2f, 0.2f, 1.0f };
float diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f };
float position[] = { 0.0f, 4.0f, -2.0f, 1.0f };
glLightfv( GL_LIGHT1, GL_AMBIENT, ambient );
glLightfv( GL_LIGHT1, GL_DIFFUSE, diffuse );
glLightfv( GL_LIGHT1, GL_POSITION, position );
glEnable( GL_LIGHT1 );
_map.optimize();
}
void Controller::resize( int width, int height )
{
glViewport( 0, 0, width, height );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
double fH = tan( 30.0 / 180.0 * 3.14159265358979323846 );
double fW = ( (double)width ) / ( (double)height ) * fH;
glFrustum( -fW, fW, -fH, fH, 1.0, 1000.0 );
glMatrixMode( GL_MODELVIEW );
_windowwidth = width;
_windowheight = height;
}
void Controller::draw()
{
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glLoadIdentity();
glRotatef( _camrot, 1, 0, 0 );
glTranslated( 0.0, -_camy, -_camz );
_world->draw( _camz );
if ( _dead )
{
_printer->print(
( boost::format( "Distance Traveled: %1%" ) % _world->distanceTraveled() ).str(),
_windowwidth / 2, _windowheight / 4 * 3,
TextPrinter::ALIGN_CENTER
);
}
}
void Controller::update( int difference )
{
if ( _dead )
return;
_world->update( difference );
if ( _world->droppedOut() )
{
std::cout <<
"You dropped into the void!\n"
"Distance traveled: " << _world->distanceTraveled() << std::endl;
_dead = true;
}
}
diff --git a/src/controller.hpp b/src/controller.hpp
index 073bcd5..86b7603 100644
--- a/src/controller.hpp
+++ b/src/controller.hpp
@@ -1,75 +1,77 @@
//
// This file is part of the game Skyways.
// Copyright (C) 2009 Mark Nevill
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifndef _CONTROLLER_HPP_
#define _CONTROLLER_HPP_
#include <memory>
#include "map.hpp"
#include "world.hpp"
class TextPrinter;
+class ShaderProgram;
class Controller
{
public:
typedef void (*QuitCallback)();
Controller(
std::auto_ptr< World > world
, double cameraheight, double cameradistance, double camerarotation
, QuitCallback cbQuit
, std::auto_ptr< TextPrinter > printer
);
~Controller();
enum {
JUMP_KEY = 1,
STRAFE_L_KEY = 2,
STRAFE_R_KEY = 3,
ACCEL_KEY = 4,
DECEL_KEY = 5,
QUIT_KEY = 6,
};
void keydown( int key );
void keyup( int key );
void loadMap( std::string filename );
void generateMap();
void initialize();
void resize( int width, int height );
void draw();
void update( int difference );
private:
std::auto_ptr< World > _world;
Map _map;
double _camy, _camz, _camrot;
bool _dead;
QuitCallback _quitcb;
std::auto_ptr< TextPrinter > _printer;
size_t _windowwidth, _windowheight;
+ std::auto_ptr< ShaderProgram > _shaderProgram;
};
#endif // _CONTROLLER_HPP_
diff --git a/src/shader.hpp b/src/shader.hpp
new file mode 100644
index 0000000..289998d
--- /dev/null
+++ b/src/shader.hpp
@@ -0,0 +1,169 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#ifndef _SHADER_HPP_
+#define _SHADER_HPP_
+
+#include <list>
+#include <string>
+#include <sstream>
+#include <fstream>
+#include <iterator>
+#include <algorithm>
+#include <vector>
+#include <stdexcept>
+
+class ShaderSource
+{
+
+public:
+
+ ShaderSource() { }
+ ~ShaderSource() { }
+
+ void addShaderSource( const std::string& source )
+ {
+ _sources.push_back( source );
+ }
+
+ void loadShaderSource( const char * filename )
+ {
+ std::ifstream fin;
+ fin.exceptions( std::ios::badbit | std::ios::failbit );
+ std::ostringstream sout;
+ fin.open( filename );
+ sout << fin.rdbuf();
+ fin.close();
+ addShaderSource( sout.str() );
+ }
+
+ std::list< std::string > getSources() const
+ {
+ return _sources;
+ }
+
+private:
+
+ std::list< std::string > _sources;
+
+};
+
+class Shader
+{
+
+public:
+
+ enum ShaderType {
+ VertexShader = GL_VERTEX_SHADER,
+ FragmentShader = GL_FRAGMENT_SHADER,
+ };
+
+ Shader(ShaderType shaderType)
+ : _shaderType( shaderType )
+ , _shaderId( glCreateShader(shaderType) )
+ {
+ }
+
+ void setSource(const ShaderSource& source)
+ {
+ std::list< std::string > sources = source.getSources();
+ if ( sources.size() == 0 )
+ {
+ throw std::runtime_error("Attempted to create shader with empty sources");
+ }
+ if ( sources.size() == 1 )
+ {
+ const char * cstr = sources.front().c_str();
+ glShaderSource(_shaderId, 1, &cstr, 0);
+ }
+ else
+ {
+ std::vector< const char* > strArray(sources.size(), 0);
+ size_t i = 0;
+ std::list< std::string >::iterator sourcestr = sources.begin();
+ for ( ; sourcestr != sources.end(); ++sourcestr, ++i )
+ {
+ strArray[i] = sourcestr->c_str();
+ }
+ glShaderSource(_shaderId, i, &strArray[0], 0);
+ }
+ }
+
+ void compile()
+ {
+ glCompileShader(_shaderId);
+ }
+
+ GLuint getGlId()
+ {
+ return _shaderId;
+ }
+
+private:
+
+ ShaderType _shaderType;
+ GLuint _shaderId;
+
+};
+
+class ShaderProgram
+{
+
+public:
+
+ ShaderProgram()
+ : _programId( glCreateProgram() )
+ , _linked( false )
+ {
+ }
+
+ void attachShader( Shader& shader )
+ {
+ glAttachShader( _programId, shader.getGlId() );
+ shaders.push_back( &shader );
+ }
+
+ void link()
+ {
+ std::for_each( shaders.begin(), shaders.end(), std::mem_fun( &Shader::compile ) );
+ glLinkProgram( _programId );
+ _linked = true;
+ }
+
+ void use()
+ {
+ if (!_linked)
+ link();
+ glUseProgram( _programId );
+ }
+
+ GLuint getGlId()
+ {
+ return _programId;
+ }
+
+private:
+
+ std::vector< Shader* > shaders;
+ GLuint _programId;
+ bool _linked;
+
+};
+
+#endif // _SHADER_HPP_
|
devnev/skyways
|
12cb531cc0b288f31a83f44054f4ebea24119ba5
|
Added SDL-dependant binary to gitignore.
|
diff --git a/.gitignore b/.gitignore
index 008a1b0..1cc84c3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,6 @@
*.o
*.d
skyways.glut
skyways.qt
+skyways.sdl
src/moc_qtwindow.cpp
|
devnev/skyways
|
d2fc00d2d76d14a8b066682cef4bfab61e2fc4f2
|
Added GLEW includes and initialization.
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..008a1b0
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,5 @@
+*.o
+*.d
+skyways.glut
+skyways.qt
+src/moc_qtwindow.cpp
diff --git a/COPYING b/COPYING
new file mode 100644
index 0000000..d511905
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,339 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ 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 2 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, write to the Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) year name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ <signature of Ty Coon>, 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
diff --git a/DejaVuSans.ttf b/DejaVuSans.ttf
new file mode 100644
index 0000000..3546657
Binary files /dev/null and b/DejaVuSans.ttf differ
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..34631fe
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,153 @@
+
+###########################
+# prelude: do not change! #
+###########################
+
+CWD:=$(shell pwd)
+
+default: all
+
+BUILDFLAGS=CFLAGS CPPFLAGS CXXFLAGS LDFLAGS
+
+define FLAGINIT_template
+ ifndef $(1)
+ $(1)=
+ endif
+endef
+
+$(foreach flag,$(BUILDFLAGS),$(eval $(call FLAGINIT_template,$(flag))))
+
+######################################
+# configuration: change things here. #
+######################################
+
+PROGRAMS=SkywaysGlut SkywaysQt SkywaysSdl
+
+SkywaysGlut_BINARY=skyways.glut
+SkywaysQt_BINARY=skyways.qt
+SkywaysSdl_BINARY=skyways.sdl
+
+HEADERS= \
+ src/aabb.hpp \
+ src/block.hpp \
+ src/collisionaccelerator.hpp \
+ src/configuration.hpp \
+ src/controller.hpp \
+ src/element.hpp \
+ src/map.hpp \
+ src/model.hpp \
+ src/objmodel.hpp \
+ src/ship.hpp \
+ src/textprinter.hpp \
+ src/vector.hpp \
+ src/world.hpp
+
+SkywasyGlut_HEADERS= $(HEADERS) \
+ src/configparser.hpp
+
+SkywasyQt_HEADERS= $(HEADERS) \
+ src/qtconfigparser.hpp \
+ src/qtwindow.hpp
+
+SkywaysSdl_HEADERS= $(HEADERS) \
+ src/configparser.hpp
+
+CXXSOURCES= \
+ src/block.cpp \
+ src/collisionaccelerator.cpp \
+ src/configuration.cpp \
+ src/controller.cpp \
+ src/element.cpp \
+ src/map.cpp \
+ src/objmodel.cpp \
+ src/ship.cpp \
+ src/textprinter.cpp \
+ src/world.cpp
+
+SkywaysGlut_CXXSOURCES= $(CXXSOURCES) \
+ src/configparser.cpp \
+ src/glutmain.cpp
+
+SkywaysQt_CXXSOURCES= $(CXXSOURCES) \
+ src/moc_qtwindow.cpp \
+ src/qtconfigparser.cpp \
+ src/qtmain.cpp \
+ src/qtwindow.cpp
+
+SkywaysSdl_CXXSOURCES= $(CXXSOURCES) \
+ src/configparser.cpp \
+ src/sdlmain.cpp
+
+CPPFLAGS+= -O2 -g -Wall -I/usr/include/FTGL -I/usr/include/freetype2
+LDFLAGS+= -lGL -lboost_filesystem -lftgl -lGLEW
+
+SkywaysGlut_LDFLAGS=-lglut -lboost_program_options
+SkywaysQt_LDFLAGS=-lQtOpenGL -lQtGui -lQtCore -lGLU -lGL -lpthread
+SkywaysQt_CPPFLAGS=-D_REENTRANT -DQT_NO_DEBUG -DQT_OPENGL_LIB -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED -I/usr/include/qt4/QtCore -I/usr/include/qt4/QtGui -I/usr/include/qt4/QtOpenGL -I/usr/include/qt4
+SkywaysSdl_LDFLAGS=-lSDL -lboost_program_options
+SkywaysSdl_CPPFLAGS=-I/usr/include/SDL
+
+EXTRADIST=
+
+######################################
+# auto-configuration: do not change! #
+######################################
+
+$(foreach prog,$(PROGRAMS),$(eval $(prog)_SOURCES=$($(prog)_CSOURCES) $($(prog)_CXXSOURCES)))
+$(foreach prog,$(PROGRAMS),$(eval $(prog)_OBJECTS=$(patsubst %.c,%_$(prog).o,$($(prog)_CSOURCES)) $(patsubst %.cpp,%_$(prog).o,$($(prog)_CXXSOURCES))))
+$(foreach flag,CFLAGS CPPFLAGS CXXFLAGS LDFLAGS,$(foreach prog,$(PROGRAMS),$(eval $(prog)_ALL_$(flag)=$($(flag)) $($(prog)_$(flag)))))
+
+#CSOURCES=$(foreach prog,$(PROGRAMS),$($(prog)_CSOURCES))
+#CXXSOURCES=$(foreach prog,$(PROGRAMS),$($(prog)_CXXSOURCES))
+#SOURCES=$(CSOURCES) $(CXXSOURCES)
+#HEADERS=$(foreach prog,$(PROGRAMS),$($(prog)_HEADERS))
+OBJECTS=$(foreach prog,$(PROGRAMS),$($(prog)_OBJECTS))
+BINARIES=$(foreach prog,$(PROGRAMS),$($(prog)_BINARY))
+DEPENDS=$(patsubst %.o,%.d,$(OBJECTS))
+
+define CDEP_template
+ %_$(1).d: %.c
+ set -e; rm -f "$$@" || true; \
+ $$(CC) -MM -MQ "`echo "$$<" | sed 's,\($$*\)\.c,\1_$(1).o,'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) "$$<" | \
+ sed 's,\($$*_$(1)\).o *:,\1.o $$@:,' >$$@
+endef
+
+define CXXDEP_template
+ %_$(1).d: %.cpp
+ set -e; rm -f "$$@" || true; \
+ $$(CXX) -MM -MQ "`echo "$$<" | sed 's,\($$*\)\.cpp,\1_$(1).o,'`" $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) "$$<" | \
+ sed 's,\($$*_$(1)\).o *:,\1.o $$@:,' >$$@
+endef
+
+define CSRC_template
+ %_$(1).o: %.c
+ $$(CC) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CFLAGS) $$< -o $$@
+endef
+
+define CXXSRC_template
+ %_$(1).o: %.cpp
+ $$(CXX) -c $$($(1)_ALL_CPPFLAGS) $$($(1)_ALL_CXXFLAGS) $$< -o $$@
+endef
+
+define BINARY_template
+ $$($(1)_BINARY): $$($(1)_OBJECTS)
+ $$(CC) $$($(1)_ALL_LDFLAGS) $$^ $$(LOADLIBS) $$(LDLIBS) -o $$@
+endef
+
+$(foreach template,CDEP CXXDEP CSRC CXXSRC BINARY,$(foreach prog,$(PROGRAMS),$(eval $(call $(template)_template,$(prog)))))
+
+all: $(BINARIES)
+
+#################################
+# extra stuff: change as needed #
+#################################
+
+clean:
+ rm $(OBJECTS) $(BINARIES) $(DEPENDS) $(DISTFILES) || true
+
+moc_%.cpp: %.hpp
+ moc-qt4 $(SkywaysQt_CPPFLAGS) $(SkywaysQt_CXXFLAGS) $< -o $@
+
+.PHONY: default clean
+
+-include $(DEPENDS)
diff --git a/README b/README
new file mode 100644
index 0000000..bd8032c
--- /dev/null
+++ b/README
@@ -0,0 +1,14 @@
+SkyWays
+=======
+
+Skyways is a toy project to create a game roughly based on the DOS game called
+"Skyroads". The aim is not to recreate the original game, just make something
+similarly fun, and to explore possibilities along the way.
+
+Depends
+-------
+
+One of: SDL, Qt4, freeglut, OpenGlut (remove the unavailable parts from the
+ PROGRAMS line in the Makefile.)
+
+All of: Boost, OpenGL, FTGL
diff --git a/blocks/cube b/blocks/cube
new file mode 100644
index 0000000..e691ab6
--- /dev/null
+++ b/blocks/cube
@@ -0,0 +1,25 @@
+v 0 0 0
+v 0 0 1
+v 0 1 0
+v 0 1 1
+v 1 0 0
+v 1 0 1
+v 1 1 0
+v 1 1 1
+# unit cube
+
+vn 1 0 0
+vn 0 1 0
+vn 0 0 1
+vn -1 0 0
+vn 0 -1 0
+vn 0 0 -1
+
+f 1//4 3//4 4//4 2//4
+f 5//1 6//1 8//1 7//1
+f 1//5 2//5 6//5 5//5
+f 3//2 7//2 8//2 4//2
+f 1//6 5//6 7//6 3//6
+f 2//3 4//3 8//3 6//3
+
+b 0 0 0 1 1 1
diff --git a/blocks/flat b/blocks/flat
new file mode 100644
index 0000000..3e1977b
--- /dev/null
+++ b/blocks/flat
@@ -0,0 +1,25 @@
+# flattened cube
+v 0 0 0
+v 0 0 1
+v 0 0.25 0
+v 0 0.25 1
+v 1 0 0
+v 1 0 1
+v 1 0.25 0
+v 1 0.25 1
+
+vn 1 0 0
+vn 0 1 0
+vn 0 0 1
+vn -1 0 0
+vn 0 -1 0
+vn 0 0 -1
+
+f 1//4 3//4 4//4 2//4
+f 5//1 6//1 8//1 7//1
+f 1//5 2//5 6//5 5//5
+f 3//2 7//2 8//2 4//2
+f 1//6 5//6 7//6 3//6
+f 2//3 4//3 8//3 6//3
+
+b 0 0 0 1 0.25 1
diff --git a/blocks/tunnel b/blocks/tunnel
new file mode 100644
index 0000000..1cd30a2
--- /dev/null
+++ b/blocks/tunnel
@@ -0,0 +1,46 @@
+v 0 0 0
+v 0.05 0 0
+v 0.95 0 0
+v 1 0 0
+v 0 1 0
+v 0.05 0.95 0
+v 0.95 0.95 0
+v 1 1 0
+v 0 0 1
+v 0.05 0 1
+v 0.95 0 1
+v 1 0 1
+v 0 1 1
+v 0.05 0.95 1
+v 0.95 0.95 1
+v 1 1 1
+
+vn 1 0 0
+vn 0 1 0
+vn 0 0 1
+vn -1 0 0
+vn 0 -1 0
+vn 0 0 -1
+
+# front
+f 1//6 2//6 6//6 5//6
+f 5//6 6//6 7//6 8//6
+f 8//6 7//6 3//6 4//6
+
+# left side
+f 1//4 5//4 13//4 9//4
+f 2//1 10//1 14//1 6//1
+# top
+f 5//2 8//2 16//2 13//2
+# right side
+f 4//1 8//1 16//1 12//1
+f 3//4 11//4 15//4 7//4
+
+# back - not visible
+# f 9//3 10//3 14//3 13//3
+# f 13//3 14//3 15//3 16//3
+# f 15//3 16//3 12//3 11//3
+
+b 0 0 0 0.05 1 1
+b 0 0.95 0 1 1 1
+b 0.95 0 0 1 1 1
diff --git a/src/aabb.hpp b/src/aabb.hpp
new file mode 100644
index 0000000..097975b
--- /dev/null
+++ b/src/aabb.hpp
@@ -0,0 +1,66 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#ifndef _AABB_HPP_
+#define _AABB_HPP_
+
+struct AABB
+{
+ AABB()
+ : p1(Vector3(0, 0, 0))
+ , p2(Vector3(0, 0, 0))
+ {
+ }
+
+ AABB(const Vector3& p1_, const Vector3& p2_)
+ : p1(p1_), p2(p2_)
+ {
+ }
+
+ AABB offset( const Vector3& d ) const throw()
+ {
+ return AABB(p1.offset(d), p2.offset(d));
+ }
+
+ AABB offset( double x, double y, double z ) const throw()
+ {
+ return AABB(p1.offset( x, y, z ), p2.offset( x, y, z ));
+ }
+
+ Vector3 size() const throw()
+ {
+ return Vector3(p2.x-p1.x, p2.y-p1.y, p2.z-p1.z);
+ }
+
+ bool collide(const AABB& other) const throw()
+ {
+ int c = 0;
+ c |= (p1.x > other.p1.x && p1.x < other.p2.x) ? 0x01 : 0;
+ c |= (p1.y > other.p1.y && p1.y < other.p2.y) ? 0x02 : 0;
+ c |= (p1.z > other.p1.z && p1.z < other.p2.z) ? 0x04 : 0;
+ c |= (p2.x > other.p1.x && p2.x < other.p2.x) ? 0x01 : 0;
+ c |= (p2.y > other.p1.y && p2.y < other.p2.y) ? 0x02 : 0;
+ c |= (p2.z > other.p1.z && p2.z < other.p2.z) ? 0x04 : 0;
+ return c == 0x07;
+ }
+
+ Vector3 p1, p2;
+};
+
+#endif // _AABB_HPP_
diff --git a/src/block.cpp b/src/block.cpp
new file mode 100644
index 0000000..d89335c
--- /dev/null
+++ b/src/block.cpp
@@ -0,0 +1,131 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#include <GL/gl.h>
+#include <stdexcept>
+#include <sstream>
+#include <fstream>
+#include <string>
+#include "objmodel.hpp"
+#include "block.hpp"
+
+void Block::draw()
+{
+ if (model.vertices.size() > 0)
+ {
+ glScalef( 1, 1, -1 );
+ model.draw();
+ glScalef( 1, 1, -1 );
+ }
+ else
+ {
+ glBegin( GL_QUADS );
+ glNormal3f( 0, 0, 1 );
+ glVertex3f( 0, 0, 0 );
+ glVertex3f( 1, 0, 0 );
+ glVertex3f( 1, 1, 0 );
+ glVertex3f( 0, 1, 0 );
+
+ glNormal3f( 1, 0, 0 );
+ glVertex3f( 1, 0, 0 );
+ glVertex3f( 1, 0, -1 );
+ glVertex3f( 1, 1, -1 );
+ glVertex3f( 1, 1, 0 );
+
+ glNormal3f( 0, 0, -1 );
+ glVertex3f( 1, 0, -1 );
+ glVertex3f( 0, 0, -1 );
+ glVertex3f( 0, 1, -1 );
+ glVertex3f( 1, 1, -1 );
+
+ glNormal3f( -1, 0, 0 );
+ glVertex3f( 0, 0, -1 );
+ glVertex3f( 0, 0, 0 );
+ glVertex3f( 0, 1, 0 );
+ glVertex3f( 0, 1, -1 );
+
+ glNormal3f( 0, -1, 0 );
+ glVertex3f( 0, 0, 0 );
+ glVertex3f( 0, 0, -1 );
+ glVertex3f( 1, 0, -1 );
+ glVertex3f( 1, 0, 0 );
+
+ glNormal3f( 0, 1, 0 );
+ glVertex3f( 0, 1, 0 );
+ glVertex3f( 1, 1, 0 );
+ glVertex3f( 1, 1, -1 );
+ glVertex3f( 0, 1, -1 );
+ glEnd();
+ }
+}
+
+void Block::drawDl()
+{
+ if ( _blockDl == 0 )
+ {
+ _blockDl = glGenLists( 1 );
+ glNewList( _blockDl, GL_COMPILE_AND_EXECUTE );
+ draw();
+ glEndList();
+ }
+ else
+ {
+ glCallList( _blockDl );
+ }
+}
+
+std::auto_ptr< Block > Block::fromFile( const std::string& filename )
+{
+ std::auto_ptr< Block > block( new Block() );
+ ObjUnknownsList objunknowns;
+
+ loadObjModel( filename.c_str(), block->model, false, &objunknowns, "b\0" );
+
+ for ( ObjUnknownsList::iterator unknown = objunknowns.begin();
+ unknown != objunknowns.end(); ++unknown )
+ {
+ if ( unknown->first == "b" )
+ {
+ std::istringstream iss( unknown->second );
+ std::string cmd;
+ iss >> cmd;
+
+ AABB aabb;
+ iss >> aabb.p1.x >> aabb.p1.y >> aabb.p1.z
+ >> aabb.p2.x >> aabb.p2.y >> aabb.p2.z;
+ block->bounds.push_back( aabb );
+ }
+ }
+ return block;
+}
+
+bool Block::collide( const AABB& aabb ) const throw()
+{
+ if ( model.vertices.size() == 0 )
+ {
+ return aabb.collide( AABB( Vector3( 0, 0, 0 ), Vector3( 1, 1, 1 ) ) );
+ }
+ for ( AabbList::const_iterator iter = bounds.begin();
+ iter != bounds.end(); ++iter )
+ {
+ if ( aabb.collide( *iter ) )
+ return true;
+ }
+ return false;
+}
diff --git a/src/block.hpp b/src/block.hpp
new file mode 100644
index 0000000..665056d
--- /dev/null
+++ b/src/block.hpp
@@ -0,0 +1,56 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#ifndef _BLOCK_HPP_
+#define _BLOCK_HPP_
+
+#include <memory>
+#include <vector>
+#include <istream>
+#include <GL/gl.h>
+#include "vector.hpp"
+#include "model.hpp"
+#include "aabb.hpp"
+
+class Block
+{
+
+public:
+
+ Block() : _blockDl( 0 ) { }
+
+ void draw();
+ void drawDl();
+
+ static std::auto_ptr< Block > fromStream( std::istream& is );
+ static std::auto_ptr< Block > fromFile( const std::string& filename );
+
+ bool collide( const AABB& aabb ) const throw();
+
+private:
+
+ Model model;
+ typedef std::vector< AABB > AabbList;
+ AabbList bounds;
+
+ GLuint _blockDl;
+
+};
+
+#endif // _BLOCK_HPP_
diff --git a/src/collisionaccelerator.cpp b/src/collisionaccelerator.cpp
new file mode 100644
index 0000000..3c6b3fe
--- /dev/null
+++ b/src/collisionaccelerator.cpp
@@ -0,0 +1,92 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#include "collisionaccelerator.hpp"
+#include <cmath>
+
+CollisionAccelerator::CollisionAccelerator( double sectionSize )
+ : _sectionSize( sectionSize )
+{
+}
+
+void CollisionAccelerator::addElement( const Element& e )
+{
+ const Element * const pe = &e;
+
+ const double beginDistance = pe->zoff();
+ size_t beginSection = (size_t)(beginDistance / _sectionSize);
+ size_t sectionCount = (size_t)((pe->length() + fmod(beginDistance, _sectionSize)) / _sectionSize);
+
+ // make sure section array has sufficient space
+ if ( sections.size() <= ( beginSection + sectionCount ) )
+ sections.resize( beginSection + sectionCount + 1 );
+
+ if ( sectionCount == 0 ) // fully contained in one section
+ {
+ sections[ beginSection ].complete.push_back( pe );
+ return;
+ }
+
+ sections[ beginSection ].beginning.push_back( pe );
+ ++beginSection; --sectionCount;
+
+ for ( ; sectionCount > 0 ; --sectionCount, ++beginSection )
+ {
+ sections[ beginSection ].running.push_back( pe );
+ }
+
+ sections[ beginSection ].ending.push_back( pe );
+}
+
+const Element * CollisionAccelerator::collide(const AABB& aabb) const
+{
+ size_t section1 = ( (size_t)aabb.p1.z ) / _sectionSize,
+ section2 = ( (size_t)aabb.p2.z ) / _sectionSize;
+ if ( section1 >= sections.size() )
+ return 0;
+ const Element * result = collide(aabb, sections[ section1 ]);
+ if ( !result && section2 != section1 && section2 < sections.size() )
+ result = collide(aabb, sections[ section2 ]);
+ return result;
+}
+
+const Element * CollisionAccelerator::collide(const AABB& aabb, const MapSection& section) const
+{
+ const Element * result = 0;
+ (result = collide(aabb, section.beginning)) ||
+ (result = collide(aabb, section.running)) ||
+ (result = collide(aabb, section.ending)) ||
+ (result = collide(aabb, section.complete));
+ return result;
+}
+
+const Element * CollisionAccelerator::collide(const AABB& aabb, const std::vector< const Element* >& elemreflist) const
+{
+ typedef std::vector< const Element* > ElemRefList;
+ typedef ElemRefList::const_iterator ElemRefIter;
+
+ for ( ElemRefIter elemref = elemreflist.begin() ;
+ elemref != elemreflist.end(); ++elemref )
+ {
+ if ( (*elemref)->collide( aabb ) )
+ return *elemref;
+ }
+ return 0;
+}
+
diff --git a/src/collisionaccelerator.hpp b/src/collisionaccelerator.hpp
new file mode 100644
index 0000000..c3e8861
--- /dev/null
+++ b/src/collisionaccelerator.hpp
@@ -0,0 +1,59 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#ifndef _COLLISIONACCELERATOR_HPP_
+#define _COLLISIONACCELERATOR_HPP_
+
+#include <vector>
+#include "element.hpp"
+#include "aabb.hpp"
+
+class CollisionAccelerator
+{
+
+public:
+
+ CollisionAccelerator( double sectionSize );
+
+ void addElement( const Element& e );
+ void clear() { sections.clear(); }
+
+ double sectionSize() const throw() { return _sectionSize; }
+
+ const Element * collide( const AABB& aabb ) const;
+
+private:
+
+ double _sectionSize;
+ typedef struct
+ {
+ std::vector< const Element* >
+ beginning, running, ending, complete;
+ } MapSection;
+ typedef std::vector< MapSection > SectionList;
+ SectionList sections;
+
+ size_t _elementsDrawn; // for statistics
+
+ const Element * collide( const AABB& aabb, const MapSection& section ) const;
+ const Element * collide( const AABB& aabb, const std::vector< const Element* >& elemreflist ) const;
+
+};
+
+#endif // _COLLISIONACCELERATOR_HPP_
diff --git a/src/configparser.cpp b/src/configparser.cpp
new file mode 100644
index 0000000..a0ee0ce
--- /dev/null
+++ b/src/configparser.cpp
@@ -0,0 +1,47 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#include <iostream>
+#include "configparser.hpp"
+
+ConfigParser::ConfigParser( Configuration& config )
+ : _config( config )
+{
+ namespace po = boost::program_options;
+ options.add_options()
+ ("help,h", "print help message")
+ ("map,w",
+ po::value<std::string>()->default_value(std::string()),
+ "set map to load")
+ ;
+}
+
+bool ConfigParser::args(int argc, char * argv[])
+{
+ namespace po = boost::program_options;
+ po::store(po::command_line_parser(argc, argv).options(options).run(), vm);
+ po::notify(vm);
+ if (vm.count("help"))
+ {
+ std::cout << options << '\n';
+ return false;
+ }
+ _config.setMap(vm["map"].as<std::string>());
+ return true;
+}
diff --git a/src/configparser.hpp b/src/configparser.hpp
new file mode 100644
index 0000000..34eafab
--- /dev/null
+++ b/src/configparser.hpp
@@ -0,0 +1,48 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#ifndef _CONFIGPARSER_HPP_
+#define _CONFIGPARSER_HPP_
+
+#ifdef _QTCONFIGPARSER_HPP_
+#error "Invalid build: cannot include qtconfigparser.hpp and configparser.hpp"
+#endif // _QTCONFIGPARSER_HPP_
+
+#include <boost/program_options.hpp>
+#include "configuration.hpp"
+
+class ConfigParser
+{
+
+public:
+
+ ConfigParser( Configuration& config );
+
+ bool args(int argc, char * argv[]);
+
+private:
+
+ Configuration& _config;
+
+ boost::program_options::options_description options;
+ boost::program_options::variables_map vm;
+
+};
+
+#endif // _CONFIGPARSER_HPP_
diff --git a/src/configuration.cpp b/src/configuration.cpp
new file mode 100644
index 0000000..10236a0
--- /dev/null
+++ b/src/configuration.cpp
@@ -0,0 +1,42 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#include "textprinter.hpp"
+#include "controller.hpp"
+#include "configuration.hpp"
+
+Configuration::Configuration()
+{
+}
+
+std::auto_ptr< Controller > Configuration::buildController( Controller::QuitCallback cbquit )
+{
+ std::auto_ptr< TextPrinter > printer( new TextPrinter( "DejaVuSans.ttf" ) );
+ std::auto_ptr< World > world( new World(
+ 10, 5, 100, 20, 1.5
+ ) );
+ std::auto_ptr< Controller > controller( new Controller (
+ world, 3.5, 6, 10, cbquit, printer
+ ) );
+ if ( _map.length() )
+ controller->loadMap( _map );
+ else
+ controller->generateMap();
+ return controller;
+}
diff --git a/src/configuration.hpp b/src/configuration.hpp
new file mode 100644
index 0000000..90236dc
--- /dev/null
+++ b/src/configuration.hpp
@@ -0,0 +1,43 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#ifndef _CONFIGURATION_HPP_
+#define _CONFIGURATION_HPP_
+
+#include <memory>
+#include "controller.hpp"
+
+class Configuration
+{
+
+public:
+
+ Configuration();
+
+ void setMap( const std::string& map ) { _map = map; }
+
+ std::auto_ptr< Controller > buildController( Controller::QuitCallback cbquit );
+
+private:
+
+ std::string _map;
+
+};
+
+#endif // _CONFIGURATION_HPP_
diff --git a/src/controller.cpp b/src/controller.cpp
new file mode 100644
index 0000000..1398731
--- /dev/null
+++ b/src/controller.cpp
@@ -0,0 +1,192 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#include <GL/glew.h>
+#include <GL/gl.h>
+#include <boost/format.hpp>
+#include <iostream>
+#include <fstream>
+#include <cstdlib>
+#include <ctime>
+#include <cmath>
+#include "textprinter.hpp"
+#include "controller.hpp"
+
+Controller::Controller(
+ std::auto_ptr< World > world
+ , double cameraheight, double cameradistance, double camerarotation
+ , Controller::QuitCallback cbQuit
+ , std::auto_ptr< TextPrinter > printer
+)
+ : _world( world ), _map( 10 )
+ , _camy( cameraheight ), _camz( cameradistance ), _camrot( camerarotation )
+ , _dead( false ), _quitcb( cbQuit )
+ , _printer( printer )
+ , _windowwidth( 1 ), _windowheight( 1 )
+{
+ _world->setMap( _map );
+}
+
+Controller::~Controller()
+{
+}
+
+void Controller::keydown( int key )
+{
+ switch ( key )
+ {
+ case STRAFE_L_KEY: _world->setStrafe( -1 ); break;
+ case STRAFE_R_KEY: _world->setStrafe( 1 ); break;
+ case ACCEL_KEY: _world->setAcceleration( 1 ); break;
+ case DECEL_KEY: _world->setAcceleration( -1 ); break;
+ case JUMP_KEY: _world->startJump(); break;
+ case QUIT_KEY:
+ if ( _dead )
+ {
+ _quitcb();
+ }
+ else
+ {
+ std::cout <<
+ "You committed suicide!\n"
+ "Distance traveled: " << _world->distanceTraveled() << std::endl;
+ _dead = true;
+ }
+ break;
+ }
+}
+
+void Controller::keyup( int key )
+{
+ switch ( key )
+ {
+ case STRAFE_L_KEY:
+ _world->setStrafe( 0 );
+ break;
+ case STRAFE_R_KEY:
+ _world->setStrafe( 0 );
+ break;
+ case ACCEL_KEY:
+ _world->setAcceleration( 0 );
+ break;
+ case DECEL_KEY:
+ _world->setAcceleration( 0 );
+ break;
+ }
+}
+
+void Controller::loadMap( std::string filename )
+{
+ _map.loadBlocks();
+ std::ifstream mapFile( filename.c_str() );
+ _map.loadMap( mapFile );
+}
+
+void Controller::generateMap()
+{
+ _map.loadBlocks();
+ srand(time(0));
+ _map.generateMap();
+}
+
+void Controller::initialize()
+{
+ GLenum err = glewInit();
+ if (err != GLEW_OK)
+ throw std::runtime_error((const char*)glewGetErrorString(err));
+ if (!GLEW_VERSION_2_0)
+ throw std::runtime_error("Nead OpenGL >= 2.0 for shaders. Update your graphics drivers!");
+
+ glClearColor( 0.2, 0.2, 0.2, 0 );
+ glClearDepth( 1.0 );
+
+ glEnable( GL_DEPTH_TEST );
+ glDepthFunc( GL_LEQUAL );
+ glEnable( GL_CULL_FACE );
+
+ glEnable( GL_LIGHTING );
+ glShadeModel( GL_SMOOTH );
+ glEnable( GL_COLOR_MATERIAL );
+ glEnable( GL_NORMALIZE );
+
+ glEnable( GL_BLEND );
+ glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
+
+ glEnable( GL_LINE_SMOOTH );
+ glHint( GL_LINE_SMOOTH_HINT, GL_NICEST );
+
+ float ambient[] = { 0.2f, 0.2f, 0.2f, 1.0f };
+ float diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f };
+ float position[] = { 0.0f, 4.0f, -2.0f, 1.0f };
+ glLightfv( GL_LIGHT1, GL_AMBIENT, ambient );
+ glLightfv( GL_LIGHT1, GL_DIFFUSE, diffuse );
+ glLightfv( GL_LIGHT1, GL_POSITION, position );
+ glEnable( GL_LIGHT1 );
+
+ _map.optimize();
+}
+
+void Controller::resize( int width, int height )
+{
+ glViewport( 0, 0, width, height );
+
+ glMatrixMode( GL_PROJECTION );
+ glLoadIdentity();
+ double fH = tan( 30.0 / 180.0 * 3.14159265358979323846 );
+ double fW = ( (double)width ) / ( (double)height ) * fH;
+ glFrustum( -fW, fW, -fH, fH, 1.0, 1000.0 );
+ glMatrixMode( GL_MODELVIEW );
+
+ _windowwidth = width;
+ _windowheight = height;
+}
+
+void Controller::draw()
+{
+ glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
+ glLoadIdentity();
+ glRotatef( _camrot, 1, 0, 0 );
+ glTranslated( 0.0, -_camy, -_camz );
+ _world->draw( _camz );
+ if ( _dead )
+ {
+ _printer->print(
+ ( boost::format( "Distance Traveled: %1%" ) % _world->distanceTraveled() ).str(),
+ _windowwidth / 2, _windowheight / 4 * 3,
+ TextPrinter::ALIGN_CENTER
+ );
+ }
+}
+
+void Controller::update( int difference )
+{
+ if ( _dead )
+ return;
+
+ _world->update( difference );
+
+ if ( _world->droppedOut() )
+ {
+ std::cout <<
+ "You dropped into the void!\n"
+ "Distance traveled: " << _world->distanceTraveled() << std::endl;
+ _dead = true;
+ }
+
+}
diff --git a/src/controller.hpp b/src/controller.hpp
new file mode 100644
index 0000000..073bcd5
--- /dev/null
+++ b/src/controller.hpp
@@ -0,0 +1,75 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#ifndef _CONTROLLER_HPP_
+#define _CONTROLLER_HPP_
+
+#include <memory>
+#include "map.hpp"
+#include "world.hpp"
+
+class TextPrinter;
+
+class Controller
+{
+
+public:
+
+ typedef void (*QuitCallback)();
+
+ Controller(
+ std::auto_ptr< World > world
+ , double cameraheight, double cameradistance, double camerarotation
+ , QuitCallback cbQuit
+ , std::auto_ptr< TextPrinter > printer
+ );
+
+ ~Controller();
+
+ enum {
+ JUMP_KEY = 1,
+ STRAFE_L_KEY = 2,
+ STRAFE_R_KEY = 3,
+ ACCEL_KEY = 4,
+ DECEL_KEY = 5,
+ QUIT_KEY = 6,
+ };
+
+ void keydown( int key );
+ void keyup( int key );
+ void loadMap( std::string filename );
+ void generateMap();
+ void initialize();
+ void resize( int width, int height );
+ void draw();
+ void update( int difference );
+
+private:
+
+ std::auto_ptr< World > _world;
+ Map _map;
+ double _camy, _camz, _camrot;
+ bool _dead;
+ QuitCallback _quitcb;
+ std::auto_ptr< TextPrinter > _printer;
+ size_t _windowwidth, _windowheight;
+
+};
+
+#endif // _CONTROLLER_HPP_
diff --git a/src/element.cpp b/src/element.cpp
new file mode 100644
index 0000000..8d66a43
--- /dev/null
+++ b/src/element.cpp
@@ -0,0 +1,51 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#include <GL/gl.h>
+#include "element.hpp"
+
+void Element::glDraw()
+{
+ glPushMatrix();
+
+ glColor4d( _color.x, _color.y, _color.z, 0.5 );
+ glTranslated( _pos.x, _pos.y, -_pos.z );
+ glScaled( 1, 1, _length );
+
+ glEnable( GL_POLYGON_OFFSET_FILL );
+ glPolygonOffset( 0.01f, 0.01f );
+ _block->drawDl();
+ glDisable( GL_POLYGON_OFFSET_FILL );
+
+ glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
+ glColor3f( 0.75f, 0.75f, 0.75f );
+ glLineWidth( 1.0f );
+ _block->drawDl();
+ glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
+
+ glPopMatrix();
+}
+
+bool Element::collide( const AABB& aabb ) const
+{
+ AABB _aabb( aabb.offset( -_pos.x, -_pos.y, -_pos.z ) );
+ _aabb.p1.z /= _length;
+ _aabb.p2.z /= _length;
+ return _block->collide( _aabb );
+}
diff --git a/src/element.hpp b/src/element.hpp
new file mode 100644
index 0000000..5b43bc6
--- /dev/null
+++ b/src/element.hpp
@@ -0,0 +1,53 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#ifndef _ELEMENT_HPP_
+#define _ELEMENT_HPP_
+
+#include "block.hpp"
+
+class Element
+{
+public:
+
+ Element( double x, double y, double z, double l, Block * b, const Vector3& color )
+ : _pos(Vector3( x, y, z)), _length( l ), _block( b ), _color( color )
+ {
+ }
+
+ void glDraw();
+
+ const Vector3& pos() const throw() { return _pos; }
+ double xoff() const throw() { return _pos.x; }
+ double yoff() const throw() { return _pos.y; }
+ double zoff() const throw() { return _pos.z; }
+ double length() const throw() { return _length; }
+
+ bool collide( const AABB& aabb ) const;
+
+private:
+
+ Vector3 _pos;
+ double _length;
+ Block * _block;
+ Vector3 _color;
+
+};
+
+#endif // _ELEMENT_HPP_
diff --git a/src/glutmain.cpp b/src/glutmain.cpp
new file mode 100644
index 0000000..3183354
--- /dev/null
+++ b/src/glutmain.cpp
@@ -0,0 +1,149 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#ifdef __APPLE__
+#include <GLUT/glut.h>
+#else
+#include <GL/glut.h>
+#endif
+
+#if defined(FREEGLUT)
+# include <GL/freeglut_ext.h>
+#elif defined(OPENGLUT)
+# include <GL/openglut_ext.h>
+#else
+# error "Unknown GLUT implementation. Need glutLeaveMainLoop extension."
+#endif
+
+#include "controller.hpp"
+#include "configparser.hpp"
+#include "configuration.hpp"
+
+std::auto_ptr< Controller > controller;
+
+static void resize( int width, int height )
+{
+ controller->resize(width, height);
+
+ glutPostRedisplay();
+}
+
+static void display()
+{
+ controller->draw();
+
+ glutSwapBuffers();
+}
+
+static void keyDown( unsigned char key, int x, int y )
+{
+ switch ( key )
+ {
+ case ' ':
+ return controller->keydown( Controller::JUMP_KEY );
+ case 27: // ESCAPE
+ return controller->keydown( Controller::QUIT_KEY );
+ }
+
+ glutPostRedisplay();
+}
+
+static void specialKeyDown( int key, int x, int y )
+{
+ switch ( key )
+ {
+ case GLUT_KEY_LEFT:
+ return controller->keydown( Controller::STRAFE_L_KEY );
+ case GLUT_KEY_RIGHT:
+ return controller->keydown( Controller::STRAFE_R_KEY );
+ case GLUT_KEY_UP:
+ return controller->keydown( Controller::ACCEL_KEY );
+ case GLUT_KEY_DOWN:
+ return controller->keydown( Controller::DECEL_KEY );
+ }
+
+ glutPostRedisplay();
+}
+
+static void keyUp( unsigned char key, int x, int y )
+{
+ switch ( key )
+ {
+ case ' ':
+ return controller->keyup( Controller::JUMP_KEY );
+ }
+
+ glutPostRedisplay();
+}
+
+static void specialKeyUp( int key, int x, int y )
+{
+ switch ( key )
+ {
+ case GLUT_KEY_LEFT:
+ return controller->keyup( Controller::STRAFE_L_KEY );
+ case GLUT_KEY_RIGHT:
+ return controller->keyup( Controller::STRAFE_R_KEY );
+ case GLUT_KEY_UP:
+ return controller->keyup( Controller::ACCEL_KEY );
+ case GLUT_KEY_DOWN:
+ return controller->keyup( Controller::DECEL_KEY );
+ }
+
+ glutPostRedisplay();
+}
+
+static void idle()
+{
+ static int tick = glutGet( GLUT_ELAPSED_TIME );
+ int newTick = glutGet( GLUT_ELAPSED_TIME );
+ controller->update( newTick - tick );
+ tick = newTick;
+
+ glutPostRedisplay();
+}
+
+int main( int argc, char * argv[] )
+{
+ glutInit( &argc, argv );
+ glutInitDisplayMode( GLUT_DOUBLE | GLUT_DEPTH );
+ glutInitWindowSize( 800, 600 );
+ glutCreateWindow( "Skyways" );
+
+ Configuration config;
+ ConfigParser configParser( config );
+ if ( !configParser.args( argc, argv ) )
+ return 0;
+ controller = config.buildController( &glutLeaveMainLoop );
+
+ glutReshapeFunc( resize );
+ glutDisplayFunc( display );
+ glutKeyboardFunc( keyDown );
+ glutKeyboardUpFunc( keyUp );
+ glutSpecialFunc( specialKeyDown );
+ glutSpecialUpFunc( specialKeyUp );
+ glutIdleFunc( idle );
+
+ controller->initialize();
+
+ glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION);
+ glutMainLoop();
+
+ return 0;
+}
diff --git a/src/map.cpp b/src/map.cpp
new file mode 100644
index 0000000..1504f97
--- /dev/null
+++ b/src/map.cpp
@@ -0,0 +1,238 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#include <boost/filesystem.hpp>
+#include <boost/filesystem/fstream.hpp>
+#include <algorithm>
+#include <functional>
+#include <fstream>
+#include <string>
+#include <sstream>
+#include <list>
+#include "map.hpp"
+
+Map::Map( size_t sectionSize )
+ : _accelerator( sectionSize )
+{
+ std::string empty;
+ blocks.insert( empty, new Block() );
+}
+
+void Map::glDraw( double )
+{
+ for ( ElementList::iterator elem = elements.begin() ;
+ elem != elements.end(); ++elem )
+ {
+ elem->glDraw();
+ }
+ _elementsDrawn = elements.size();
+}
+
+void Map::loadBlocks()
+{
+ using namespace boost::filesystem;
+ path block_dir( "blocks" );
+ if ( !exists( block_dir ) )
+ return;
+ for ( recursive_directory_iterator block_fs_entry( block_dir ) ;
+ block_fs_entry != recursive_directory_iterator() ;
+ ++block_fs_entry )
+ {
+ if ( is_directory( block_fs_entry->status() ) )
+ continue;
+ std::string block_path;
+ path::iterator iter = block_fs_entry->path().begin();
+ ++iter;
+ if ( iter != block_fs_entry->path().end() )
+ block_path = *iter;
+ for ( ++iter ; iter != block_fs_entry->path().end() ; ++iter )
+ block_path = block_path + "/" + *iter;
+ blocks.insert( block_path, Block::fromFile( block_fs_entry->path().string() ) );
+ }
+}
+
+void Map::optimize()
+{
+ for ( ElementList::iterator elem = elements.begin() ;
+ elem != elements.end(); ++elem )
+ {
+ _accelerator.addElement( *elem );
+ }
+}
+
+bool Map::collide( const AABB& aabb )
+{
+ return _accelerator.collide( aabb );
+}
+
+void Map::generateMap()
+{
+ _accelerator.clear();
+ elements.clear();
+ elements.push_back(Element(
+ 0, -1, 0, 20, block( "" ), Vector3( 1, 1, 1 )
+ ));
+ for (size_t i = 0; i < 100; ++i)
+ {
+ elements.push_back(Element(
+ rand() % 7 - 3,
+ ((double)(rand() % 5))/4 - 0.5,
+ rand() % 400,
+ rand() % 20 + 2,
+ block( "" ),
+ Vector3(
+ ( (double)rand() ) / RAND_MAX,
+ ( (double)rand() ) / RAND_MAX,
+ ( (double)rand() ) / RAND_MAX
+ )
+ ));
+ }
+}
+
+struct Column
+{
+ char key;
+ double start, length;
+};
+
+struct BlockPos
+{
+ BlockPos() : block(), ypos(0.0) { }
+ std::string block;
+ double ypos;
+};
+
+void Map::loadMap( std::istream& is )
+{
+ std::string line;
+ std::vector< std::list< BlockPos > > aliases(256);
+ std::vector< Element > newElements;
+
+ while ( std::getline( is, line ) )
+ {
+ if ( line == "%%" )
+ break;
+ std::istringstream iss( line );
+ char key;
+ iss >> key;
+ if ( key < 0 )
+ throw std::runtime_error( std::string("Invalid alias name ") + key );
+ BlockPos pos;
+ while ( iss >> pos.block >> pos.ypos )
+ {
+ if ( blocks.find( pos.block ) == blocks.end() )
+ throw std::runtime_error( "Unknown block " + pos.block );
+ aliases[ key ].push_back( pos );
+ }
+ }
+ if ( !is || !std::getline( is, line ) )
+ throw std::runtime_error( "Unexpected eof before map." );
+
+ size_t columns;
+ {
+ std::istringstream iss( line );
+ iss >> columns;
+ }
+
+ Column emptyColumn = { ' ', 0, 0 };
+
+ std::vector< Column > runningdata(columns, emptyColumn);
+
+ double rowlength, position = 0.0;
+
+ while ( std::getline( is, line ) )
+ {
+ size_t seperator = line.find(':');
+ if ( seperator == std::string::npos )
+ throw std::runtime_error( "Missing seperator in map row." );
+ if ( sscanf( line.substr(0, seperator).c_str(), " %lf ", &rowlength ) != 1 )
+ throw std::runtime_error( "Invalid row length in map row." );
+ std::string row = line.substr( seperator+1 );
+ if ( row.length() > columns )
+ throw std::runtime_error( "Bad row size." );
+ else if ( row.length() < columns )
+ row.resize( columns, ' ' );
+ for (size_t i = 0; i < columns; ++i)
+ {
+ char key = row[i];
+ if ( key < 0 || ( key != ' ' && aliases[key].empty() ) )
+ throw std::runtime_error( std::string("Invalid alias name ") + key );
+ if ( key == runningdata[i].key )
+ {
+ runningdata[i].length += rowlength;
+ }
+ else
+ {
+ if ( runningdata[i].key != ' ' )
+ {
+ for ( std::list< BlockPos >::iterator posIter =
+ aliases[runningdata[i].key].begin();
+ posIter != aliases[runningdata[i].key].end();
+ ++posIter)
+ {
+ newElements.push_back(Element(
+ ( (double)i ) - ( (double)columns ) / 2,
+ posIter->ypos,
+ runningdata[i].start,
+ runningdata[i].length,
+ blocks.find( posIter->block )->second,
+ Vector3(
+ ( (double)rand() ) / RAND_MAX,
+ ( (double)rand() ) / RAND_MAX,
+ ( (double)rand() ) / RAND_MAX
+ )
+ ));
+ }
+ }
+ runningdata[i].key = key;
+ runningdata[i].start = position;
+ runningdata[i].length = rowlength;
+ }
+ }
+ position += rowlength;
+ }
+ for (size_t i = 0; i < columns; ++i)
+ {
+ if ( runningdata[i].key != ' ' )
+ {
+ for ( std::list< BlockPos >::iterator posIter =
+ aliases[runningdata[i].key].begin();
+ posIter != aliases[runningdata[i].key].end();
+ ++posIter)
+ {
+ newElements.push_back(Element(
+ ( (double)i ) - ( (double)columns ) / 2,
+ posIter->ypos,
+ runningdata[i].start,
+ runningdata[i].length,
+ blocks.find( posIter->block )->second,
+ Vector3(
+ ( (double)rand() ) / RAND_MAX,
+ ( (double)rand() ) / RAND_MAX,
+ ( (double)rand() ) / RAND_MAX
+ )
+ ));
+ }
+ }
+ }
+
+ _accelerator.clear();
+ using std::swap;
+ swap( elements, newElements );
+}
diff --git a/src/map.hpp b/src/map.hpp
new file mode 100644
index 0000000..6cf0439
--- /dev/null
+++ b/src/map.hpp
@@ -0,0 +1,69 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#ifndef _MAP_HPP_
+#define _MAP_HPP_
+
+#include <vector>
+#include <istream>
+#include <boost/ptr_container/ptr_map.hpp>
+#include "element.hpp"
+#include "aabb.hpp"
+#include "collisionaccelerator.hpp"
+
+class Map
+{
+public:
+
+ Map( size_t sectionSize );
+
+ void glDraw( double zmin = 0 );
+
+ void loadBlocks();
+
+ void generateMap();
+ void loadMap( std::istream& is );
+ void optimize();
+
+ Block * block( const char * name ) { return &blocks.at( name ); }
+
+ // statistic functions
+
+ size_t elementsDrawn() const throw() { return _elementsDrawn; }
+ size_t blocksLoaded() const throw() { return blocks.size(); }
+ double lowestPoint() const throw() { return -1; /* TODO: calculate */ }
+
+ // collide AABB with map.
+ // assumes aabb.size().z<sectionSize
+ bool collide( const AABB& aabb );
+
+private:
+
+ CollisionAccelerator _accelerator;
+
+ typedef std::vector< Element > ElementList;
+ ElementList elements;
+
+ size_t _elementsDrawn; // for statistics
+
+ boost::ptr_map< std::string, Block > blocks;
+
+};
+
+#endif // _MAP_HPP_
diff --git a/src/model.hpp b/src/model.hpp
new file mode 100644
index 0000000..417915a
--- /dev/null
+++ b/src/model.hpp
@@ -0,0 +1,105 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#ifndef _MODEL_HPP_
+#define _MODEL_HPP_
+
+#include <vector>
+#include <GL/gl.h>
+#include "vector.hpp"
+
+typedef struct
+{
+
+ size_t ix[3];
+
+} Triangle;
+
+typedef struct
+{
+
+ size_t ix[4];
+
+} Quad;
+
+template<size_t N>
+struct Face
+{
+
+ size_t vertices[N];
+ size_t normals[N];
+
+ bool valid()
+ {
+ for (size_t i = 0; i < N; ++i)
+ {
+ if ( vertices[i] == vertices[(i+1)%N] )
+ return false;
+ }
+ return true;
+ }
+
+};
+
+typedef struct
+{
+
+ std::vector< Vector3 > vertices;
+ std::vector< Vector3 > normals;
+ std::vector< Face<3> > trifaces;
+ std::vector< Face<4> > quadfaces;
+
+ void draw()
+ {
+ glBegin( GL_TRIANGLES );
+ for ( size_t i = 0; i < trifaces.size(); ++i )
+ drawFace( trifaces[i] );
+ glEnd();
+ glBegin( GL_QUADS );
+ for ( size_t i = 0; i < quadfaces.size(); ++i )
+ drawFace( quadfaces[i] );
+ glEnd();
+ }
+
+private:
+
+ template<size_t N>
+ void drawFace( Face<N>& face )
+ {
+ for ( size_t i = 0; i < N; ++i )
+ {
+ if ( normals.size() > 0 )
+ {
+ glNormal3d(
+ normals[face.normals[i]].x,
+ normals[face.normals[i]].y,
+ normals[face.normals[i]].z
+ );
+ }
+ glVertex3d(
+ vertices[face.vertices[i]].x,
+ vertices[face.vertices[i]].y,
+ vertices[face.vertices[i]].z
+ );
+ }
+ }
+
+} Model;
+
+#endif // _MODEL_HPP_
diff --git a/src/objmodel.cpp b/src/objmodel.cpp
new file mode 100644
index 0000000..04accfa
--- /dev/null
+++ b/src/objmodel.cpp
@@ -0,0 +1,281 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#include <fstream>
+#include <string>
+#include <sstream>
+#include <iostream>
+#include <stdexcept>
+#include <set>
+#include "vector.hpp"
+#include "range.hpp"
+#include "objmodel.hpp"
+
+static bool parseFacePoint(const char* str, size_t& v, size_t& vt, size_t& vn)
+{
+ // parse 3 numbers from string, seperated by slashes.
+ // missing numbers are set to 0, e.g. "3//2"->3,0,2
+ // only 1 slash means only vertex and texture
+ // 0 slashes means only vertex
+ v = vt = vn = 0;
+ for ( ; (*str) && (*str) != '/'; ++str)
+ v = v*10 + ((*str)-'0');
+ if (!(*str)) return true; else ++str;
+ for ( ; (*str) && (*str) != '/'; ++str)
+ vt = vt*10 + ((*str)-'0');
+ if (!(*str)) return true; else ++str;
+ for ( ; (*str); ++str)
+ vn = vn*10 + ((*str)-'0');
+ return true;
+}
+
+void loadObjModel(const char* filename, Model& model, bool unify,
+ std::vector< std::pair< std::string, std::string > >* unknowns,
+ const char * expectedUnknowns)
+{
+ // Loading the mesh.
+ // Lines begin with either '#' to indicate a comment, 'v' to indicate a vertex
+ // ('vt' indicating skin vertex and 'vn' a vector normal) or 'f' to indicat a face.
+ // ** Comments are ignored.
+ // ** Vertex indices (in 'f' lines) are one based, so they start with one and not zero.
+ // ** Faces may have three or four indices so they must be triangles or quads.
+ // ** Any other tag in the file is ignored.
+
+ std::vector< Vector3 >& vertices = model.vertices;
+ std::vector< Vector3 >& normals = model.normals;
+ std::vector< Face<3> >& triangles = model.trifaces;
+ std::vector< Face<4> >& quads = model.quadfaces;
+
+ // open file
+ std::ifstream file(filename);
+ if (!file.is_open())
+ throw std::runtime_error(std::string("Unable to open OBJ file ") + filename);
+
+ std::string line;
+ bool unknownWarning = false;
+ Range<size_t> vertexRange = makeInvalidRange<size_t>()
+#if 0
+ , textureRange = makeInvalidRange<size_t>()
+#endif
+ , normalRange = makeInvalidRange<size_t>()
+ ;
+ std::vector< Vector3 > _vertices;
+ std::vector< Vector3 > _normals;
+ std::vector< Face<3> > _triangles;
+ std::vector< Face<4> > _quads;
+
+ Range<double> xrange, yrange, zrange;
+
+ std::set<std::string> _expectedUnknowns;
+ if (expectedUnknowns)
+ {
+ const char * eubeg = expectedUnknowns;
+ while (*eubeg)
+ {
+ std::string eucur(eubeg);
+ _expectedUnknowns.insert(eucur);
+ eubeg += eucur.length();
+ }
+ }
+
+ while (getline(file, line))
+ {
+ std::istringstream iss(line);
+ std::string cmd;
+ // ignore empty lines and lines with '#' as first non-space char
+ if (!(iss >> cmd) || cmd[0] == '#')
+ continue;
+ else if (cmd == "vn")
+ {
+ double x, y, z;
+ if (!(iss >> x >> y >> z))
+ throw std::runtime_error("Invalid vertex normal: " + line);
+ _normals.push_back(Vector3(x, y, z));
+ }
+ else if (cmd == "vt")
+ {
+#if 0
+ double tx, ty;
+ if (!(iss >> tx >> ty))
+ throw std::runtime_error("Invalid vertex texcoord: " + line);
+ m_texpoints.push_back(SkinVertex(tx, ty));
+#endif
+ }
+ else if (cmd == "v")
+ {
+ double x, y, z;
+ if (!(iss >> x >> y >> z))
+ throw std::runtime_error("Invalid vertex: " + line);
+ xrange.include(x); yrange.include(y), zrange.include(z);
+ _vertices.push_back(Vector3(x, y, z));
+ }
+ else if (cmd == "f")
+ {
+ std::string fp[3];
+ if (!(iss >> fp[0] >> fp[1] >> fp[2]))
+ throw std::runtime_error("Invalid face: " + line);
+ Face<3> triangle; size_t it; // it: dummy
+ for (size_t i = 0; i < 3; ++i)
+ {
+ // parse indices from triplets
+ // note that even though indices are 1-based in the file, they
+ // are not decremented here. this is so the min/max ranges can
+ // be used for validation
+ if (!parseFacePoint(fp[i].c_str(), triangle.vertices[i], it, triangle.normals[i]))
+ throw std::runtime_error("Invalid face: " + line);
+ vertexRange.include(triangle.vertices[i]);
+#if 0
+ textureRange.include(face.it[i]);
+#endif
+ normalRange.include(triangle.normals[i]);
+ }
+ if (iss >> fp[0]) // theres a fourth corner -> it's a quad
+ {
+ Face<4> quad;
+ for (size_t i = 0; i < 3; ++i)
+ {
+ quad.vertices[i] = triangle.vertices[i];
+ quad.normals[i] = triangle.normals[i];
+ }
+ if (!parseFacePoint(fp[0].c_str(), quad.vertices[3], it, quad.normals[3]))
+ throw std::runtime_error("Invalid face: " + line);
+ vertexRange.include(quad.vertices[3]);
+#if 0
+ textureRange.include(quad.it[3]);
+#endif
+ normalRange.include(quad.normals[3]);
+ if (quad.valid())
+ _quads.push_back(quad);
+ }
+ else if (triangle.valid())
+ _triangles.push_back(triangle);
+ }
+ else
+ {
+ if (!unknownWarning && _expectedUnknowns.find(cmd) == _expectedUnknowns.end())
+ {
+ std::cerr << "Unknown token \"" << cmd << "\" encountered. (Additional warnings suppressed.)\n";
+ unknownWarning = true;
+ }
+ if (unknowns)
+ {
+ unknowns->push_back( make_pair(cmd, line) );
+ }
+ }
+ }
+ file.close();
+
+ // validate loaded object
+ if (_vertices.size() == 0) // must have vertices
+ throw std::runtime_error("Bad OBJ file: no vertices");
+ if (_triangles.size() == 0 && _quads.size() == 0) // must have faces
+ throw std::runtime_error("Bad OBJ file: no faces");
+ if (vertexRange.min == 0)
+ throw std::runtime_error("Bad OBJ file: faces with invalid vertex indices");
+ if (vertexRange.max > _vertices.size())
+ throw std::runtime_error("Bad OBJ file: out-of-range vertex indices");
+#if 0
+ if (textureRange.max > m_texpoints.size())
+ throw std::runtime_error("Bad OBJ file: out-of-range texture indices");
+ if (textureRange.min == 0 && textureRange.max != 0)
+ throw std::runtime_error("Bad OBJ file: mixed texture usage on faces");
+#endif
+ if (normalRange.max > _normals.size())
+ throw std::runtime_error("Bad OBJ file: out-of-range normal indices");
+ if (normalRange.min == 0 && normalRange.max != 0)
+ throw std::runtime_error("Bad OBJ file: mixed normal usage on faces");
+
+ if (normalRange.max == 0)
+ _normals.clear();
+
+#if 0
+ // this is currently hardcoded, it may be parametrized later on
+ bool recalculateNormals = false;
+
+ // if there are no normals, force normal recalculation
+ if (m_normals.size() == 0 || normalRange.max == 0)
+ recalculateNormals = true;
+
+ if (recalculateNormals)
+ {
+ // recalculate normals, one normal per vertex
+ m_normals.clear();
+ m_normals.resize(m_vertices.size(), Vector3(0, 0, 0));
+ for (std::vector<Face>::iterator face = m_faces.begin(); face != m_faces.end(); ++face)
+ {
+ const Vector3 faceNormal((m_vertices[face->i[1]-1] - m_vertices[face->i[0]-1]).cross(m_vertices[face->i[2]-1] - m_vertices[face->i[0]-1]).normalized());
+ m_normals[face->i[0]-1] += faceNormal;
+ m_normals[face->i[1]-1] += faceNormal;
+ m_normals[face->i[2]-1] += faceNormal;
+ std::copy(face->i, face->i+3, face->in);
+ }
+ // normalize generated normals
+ for (std::vector<Vector3>::iterator normal = m_normals.begin(); normal != m_normals.end(); ++normal)
+ {
+ // only normalize normals that have been set (i.e. unused vertices will still have 0-length normals)
+ if (normal->lengthSquared() > 0)
+ normal->normalize();
+ }
+ }
+#endif
+
+#if 0
+ // turn on textures if used
+ m_textures = textureRange.min > 0;
+#endif
+
+ if (unify)
+ {
+ double scale =
+ std::max( xrange.difference(),
+ std::max( yrange.difference(), zrange.difference() ) );
+ for ( size_t i = 0; i < _vertices.size(); ++i )
+ {
+ _vertices[i].x -= xrange.center();
+ _vertices[i].x /= scale;
+ _vertices[i].y -= yrange.center();
+ _vertices[i].y /= scale;
+ _vertices[i].z -= zrange.center();
+ _vertices[i].z /= scale;
+ }
+ }
+
+ for ( size_t i = 0; i < _triangles.size(); ++i )
+ {
+ for ( size_t j = 0; j < 3; ++j )
+ {
+ _triangles[i].vertices[j] -= 1;
+ _triangles[i].normals[j] -= 1;
+ }
+ }
+ for ( size_t i = 0; i < _quads.size(); ++i )
+ {
+ for ( size_t j = 0; j < 4; ++j )
+ {
+ _quads[i].vertices[j] -= 1;
+ _quads[i].normals[j] -= 1;
+ }
+ }
+
+ using std::swap;
+ swap( vertices, _vertices );
+ swap( normals, _normals );
+ swap( triangles, _triangles );
+ swap( quads, _quads );
+}
diff --git a/src/objmodel.hpp b/src/objmodel.hpp
new file mode 100644
index 0000000..f7f7f60
--- /dev/null
+++ b/src/objmodel.hpp
@@ -0,0 +1,33 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#ifndef _OBJMODEL_HPP_
+#define _OBJMODEL_HPP_
+
+#include <vector>
+#include <utility>
+#include "vector.hpp"
+#include "model.hpp"
+
+typedef std::vector< std::pair< std::string, std::string > > ObjUnknownsList;
+
+void loadObjModel(const char* filename, Model& model, bool unify = true,
+ ObjUnknownsList* unknowns = 0, const char * expectedUnknowns = 0);
+
+#endif
diff --git a/src/qtconfigparser.cpp b/src/qtconfigparser.cpp
new file mode 100644
index 0000000..9ff164c
--- /dev/null
+++ b/src/qtconfigparser.cpp
@@ -0,0 +1,39 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#include <QSettings>
+#include "qtconfigparser.hpp"
+
+ConfigParser::ConfigParser( Configuration& config )
+ : _config( config )
+{
+}
+
+void ConfigParser::readSettings()
+{
+ QSettings settings(
+ QSettings::IniFormat, QSettings::UserScope,
+ "Unspecified", "Skyways"
+ );
+ _config.setMap(
+ settings.value("mapfile", QString(""))
+ .toString().toStdString()
+ );
+}
+
diff --git a/src/qtconfigparser.hpp b/src/qtconfigparser.hpp
new file mode 100644
index 0000000..d532b74
--- /dev/null
+++ b/src/qtconfigparser.hpp
@@ -0,0 +1,44 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#ifndef _QTCONFIGPARSER_HPP_
+#define _QTCONFIGPARSER_HPP_
+
+#ifdef _CONFIGPARSER_HPP_
+#error "Invalid build: cannot include qtconfigparser.hpp and configparser.hpp"
+#endif // _CONFIGPARSER_HPP_
+
+#include "configuration.hpp"
+
+class ConfigParser
+{
+
+public:
+
+ ConfigParser( Configuration& config );
+
+ void readSettings();
+
+private:
+
+ Configuration& _config;
+
+};
+
+#endif // _QTCONFIGPARSER_HPP_
diff --git a/src/qtmain.cpp b/src/qtmain.cpp
new file mode 100644
index 0000000..8752ed3
--- /dev/null
+++ b/src/qtmain.cpp
@@ -0,0 +1,29 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#include <QApplication>
+#include "qtwindow.hpp"
+
+int main ( int argc, char** argv )
+{
+ QApplication app( argc, argv );
+ Window window;
+ window.show();
+ return app.exec();
+}
diff --git a/src/qtwindow.cpp b/src/qtwindow.cpp
new file mode 100644
index 0000000..5c43537
--- /dev/null
+++ b/src/qtwindow.cpp
@@ -0,0 +1,115 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#include <QCoreApplication>
+#include <QKeyEvent>
+#include <QTimer>
+#include <QTime>
+#include <iostream>
+#include <cmath>
+#include "qtconfigparser.hpp"
+#include "configuration.hpp"
+#include "controller.hpp"
+#include "qtwindow.hpp"
+
+void quitFunc()
+{
+ qApp->quit();
+}
+
+Window::Window( QWidget * parent )
+ : QGLWidget( parent )
+{
+ timer = new QTimer( this );
+ connect( timer, SIGNAL(timeout()), this, SLOT(update()) );
+ timer->start( 0 );
+ time = new QTime();
+ setFocusPolicy( Qt::StrongFocus );
+ Configuration config;
+ ConfigParser configParser( config );
+ configParser.readSettings();
+ controller = config.buildController( &quitFunc );
+}
+
+Window::~Window()
+{
+}
+
+void Window::update()
+{
+ if ( time->isNull() )
+ {
+ time->start();
+ return;
+ }
+ else
+ {
+ controller->update( time->restart() );
+ }
+ ( (QWidget*)this )->update();
+}
+
+int Window::mapKey( int key )
+{
+ switch ( key )
+ {
+ case Qt::Key_Left: return Controller::STRAFE_L_KEY;
+ case Qt::Key_Right: return Controller::STRAFE_R_KEY;
+ case Qt::Key_Up: return Controller::ACCEL_KEY;
+ case Qt::Key_Down: return Controller::DECEL_KEY;
+ case Qt::Key_Space: return Controller::JUMP_KEY;
+ case Qt::Key_Escape: return Controller::QUIT_KEY;
+ default: return 0;
+ }
+}
+
+void Window::keyPressEvent( QKeyEvent * event )
+{
+ if ( !event->isAutoRepeat() )
+ {
+ int key = mapKey( event->key() );
+ if ( key > 0 )
+ controller->keydown( key );
+ }
+}
+
+void Window::keyReleaseEvent( QKeyEvent * event )
+{
+ if ( !event->isAutoRepeat() )
+ {
+ int key = mapKey( event->key() );
+ if ( key > 0 )
+ controller->keyup( key );
+ }
+}
+
+void Window::initializeGL()
+{
+ controller->initialize();
+}
+
+void Window::resizeGL( int width, int height )
+{
+ controller->resize( width, height );
+}
+
+void Window::paintGL()
+{
+ controller->draw();
+}
diff --git a/src/qtwindow.hpp b/src/qtwindow.hpp
new file mode 100644
index 0000000..04d86c7
--- /dev/null
+++ b/src/qtwindow.hpp
@@ -0,0 +1,58 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#ifndef _WINDOW_HPP_
+#define _WINDOW_HPP_
+
+#include <QGLWidget>
+#include <memory>
+
+class Controller;
+
+class QKeyEvent;
+class QTimer;
+class QTime;
+
+class Window : public QGLWidget
+{
+ Q_OBJECT
+
+public:
+ Window( QWidget * parent = 0 );
+ virtual ~Window();
+
+public slots:
+ void update();
+
+protected:
+ virtual void keyPressEvent( QKeyEvent * event );
+ virtual void keyReleaseEvent( QKeyEvent * event );
+ virtual void initializeGL();
+ virtual void resizeGL( int width, int height );
+ virtual void paintGL();
+
+private:
+ int mapKey( int key );
+
+ std::auto_ptr< Controller > controller;
+ QTimer * timer;
+ QTime * time;
+};
+
+#endif // _WINDOW_HPP_
diff --git a/src/range.hpp b/src/range.hpp
new file mode 100644
index 0000000..1b342cb
--- /dev/null
+++ b/src/range.hpp
@@ -0,0 +1,101 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#ifndef _RANGE_HPP_
+#define _RANGE_HPP_
+
+#include <limits>
+#include <algorithm>
+
+/// Represents a range of numbers for some numeric type T.
+template<class T>
+struct Range
+{
+ T min, max;
+ /// Is the range valid, i.e. min <= max?
+ bool valid() const throw() { return min <= max; }
+ /// Is a value contained in the range?
+ bool contains(const T& value) const throw() { return (min <= value) && (value <= max); }
+ /// Do two ranges overlap?
+ bool overlaps(const Range& range) const throw() { return max >= range.min && min <= range.max; }
+ /// Extend range to include another range.
+ void merge(const Range& other)
+ {
+ using std::min;
+ using std::max;
+ this->min = min(this->min, other.min);
+ this->max = max(this->max, other.max);
+ }
+ /// Extend range to include a point.
+ void include(const T& value)
+ {
+ using std::min;
+ using std::max;
+ this->min = min(this->min, value);
+ this->max = max(this->max, value);
+ }
+ /// Distance between min and max
+ T difference()
+ {
+ return max - min;
+ }
+ /// Center between min and max
+ T center()
+ {
+ return (max + min) / 2;
+ }
+};
+
+/// Basic inline range constructor.
+/// @relatesalso Range
+template<class T>
+inline Range<T> makeRange(const T& min, const T& max)
+{
+ Range<T> r = { min, max };
+ return r;
+}
+
+/// Construct range containing all points.
+/// @relatesalso Range
+template<class T>
+inline Range<T> makeMaxRange()
+{
+ using std::numeric_limits;
+ Range<T> r = { numeric_limits<T>::min(), numeric_limits<T>::max() };
+ return r;
+}
+
+/// Construct reverse of maximum range, i.e. maximize range.min and minimize range.max.
+/// @relatesalso Range
+template<class T>
+inline Range<T> makeInvalidRange()
+{
+ using std::numeric_limits;
+ Range<T> r = { numeric_limits<T>::max(), numeric_limits<T>::min() };
+ return r;
+}
+
+/// @relatesalso Range
+template<class OStream, class T>
+OStream& operator<<(OStream& os, const Range<T>& range)
+{
+ return os << "(range: " << range.min << ' ' << range.max << ')';
+}
+
+#endif
diff --git a/src/sdlmain.cpp b/src/sdlmain.cpp
new file mode 100644
index 0000000..baeff0d
--- /dev/null
+++ b/src/sdlmain.cpp
@@ -0,0 +1,115 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#include <stdexcept>
+#include <boost/format.hpp>
+#include <SDL.h>
+#include "controller.hpp"
+#include "configparser.hpp"
+#include "configuration.hpp"
+
+void SdlThrowError( const char * message )
+{
+ throw new std::runtime_error( (
+ boost::format("%1%: %2%") % message % SDL_GetError()
+ ).str() );
+}
+
+class SdlInit
+{
+public:
+ SdlInit()
+ {
+ if ( SDL_Init(SDL_INIT_VIDEO) < 0 )
+ SdlThrowError( "Unable to init SDL" );
+ }
+ ~SdlInit() { SDL_Quit(); }
+};
+
+class SdlScreen
+{
+public:
+ SdlScreen( SDL_Surface * screen )
+ {
+ _screen = screen;
+ if ( !_screen )
+ SdlThrowError( "Unable to set video mode" );
+ }
+private:
+ SDL_Surface * _screen;
+};
+
+int mapSdlKey( SDLKey key )
+{
+ switch ( key )
+ {
+ case SDLK_ESCAPE: return Controller::QUIT_KEY;
+ case SDLK_SPACE: return Controller::JUMP_KEY;
+ case SDLK_LEFT: return Controller::STRAFE_L_KEY;
+ case SDLK_RIGHT: return Controller::STRAFE_R_KEY;
+ case SDLK_UP: return Controller::ACCEL_KEY;
+ case SDLK_DOWN: return Controller::DECEL_KEY;
+ default: return -1;
+ }
+}
+
+std::auto_ptr< Controller > controller;
+
+bool g_running;
+
+void endMainLoop() { g_running = false; }
+
+int main(int argc, char* argv[])
+{
+ SdlInit init;
+ SdlScreen screen( SDL_SetVideoMode( 800, 600, 32, SDL_OPENGL ) );
+
+ Configuration config;
+ ConfigParser configParser( config );
+ if ( !configParser.args( argc, argv ) )
+ return 0;
+ controller = config.buildController( &endMainLoop );
+
+ controller->initialize();
+ controller->resize( 800, 600 );
+ g_running = true;
+
+ int time = SDL_GetTicks();
+ while ( g_running )
+ {
+ int newTime = SDL_GetTicks();
+ controller->update( newTime - time );
+ time = newTime;
+
+ controller->draw();
+ SDL_GL_SwapBuffers();
+
+ SDL_Event event;
+ int key;
+ while ( SDL_PollEvent(&event) )
+ {
+ if ( event.type == SDL_QUIT )
+ endMainLoop();
+ else if ( event.type == SDL_KEYDOWN && ( key = mapSdlKey( event.key.keysym.sym ) ) != -1 )
+ controller->keydown( key );
+ else if ( event.type == SDL_KEYUP && ( key = mapSdlKey( event.key.keysym.sym ) ) != -1 )
+ controller->keyup( key );
+ }
+ }
+}
diff --git a/src/ship.cpp b/src/ship.cpp
new file mode 100644
index 0000000..0efd51b
--- /dev/null
+++ b/src/ship.cpp
@@ -0,0 +1,128 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#include <GL/gl.h>
+#include <cmath>
+#include <iostream>
+#include <stdexcept>
+#include "ship.hpp"
+#include "objmodel.hpp"
+
+Ship::Ship()
+ : _pos(Vector3(0, 0, 0))
+ , _size(Vector3(0.8, 0.5, 1.0))
+ , _shipDl(0)
+{
+}
+
+Ship::~Ship()
+{
+}
+
+void Ship::initialize()
+{
+ try
+ {
+ loadObjModel("ship.obj", _model, true, 0, "mtl\0");
+ std::cout << "loaded "
+ << _model.vertices.size() << " vertices and "
+ << _model.trifaces.size() + _model.quadfaces.size()
+ << " faces for ship." << std::endl;
+ }
+ catch (std::runtime_error& e)
+ {
+ std::cerr <<
+ "Warning: failed to load ship model, "
+ "falling back to box ship.\n"
+ "Exception caught was: "
+ << e.what() << '\n';
+ }
+}
+
+void Ship::draw()
+{
+ glTranslated( 0, _size.y / 2, -_size.z / 2 );
+ if ( _model.vertices.size() && _model.trifaces.size() )
+ {
+ glScaled( _size.x, _size.y, -_size.z );
+ _model.draw();
+ }
+ else
+ {
+ glScaled( _size.x, _size.y, _size.z );
+
+ glEnable( GL_POLYGON_OFFSET_FILL );
+ glPolygonOffset( 0.01f, 0.01f );
+ drawSimple();
+ glDisable( GL_POLYGON_OFFSET_FILL );
+
+ glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
+ glColor3f( 0.75f, 0.75f, 0.75f );
+ glLineWidth( 1.0f );
+ drawSimple();
+ glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
+ }
+}
+
+void Ship::drawDl()
+{
+ if ( _shipDl == 0 )
+ {
+ _shipDl = glGenLists( 1 );
+ glNewList( _shipDl, GL_COMPILE_AND_EXECUTE );
+ draw();
+ glEndList();
+ }
+ else
+ {
+ glCallList( _shipDl );
+ }
+}
+
+void Ship::drawSimple()
+{
+ glBegin( GL_QUADS );
+ glNormal3d( 0, 0, 1 );
+ glVertex3d( -0.5, 0.5, 0.5 );
+ glVertex3d( -0.5, -0.5, 0.5 );
+ glVertex3d( 0.5, -0.5, 0.5 );
+ glVertex3d( 0.5, 0.5, 0.5 );
+ glEnd();
+ glBegin( GL_TRIANGLES );
+ glNormal3d( -1, 0, -0.5 );
+ glVertex3d( -0.5, -0.5, 0.5 );
+ glVertex3d( -0.5, 0.5, 0.5 );
+ glVertex3d( 0, 0, -1.0 );
+
+ glNormal3d( 0, 1, -0.5 );
+ glVertex3d( -0.5, 0.5, 0.5 );
+ glVertex3d( 0.5, 0.5, 0.5 );
+ glVertex3d( 0, 0, -1.0 );
+
+ glNormal3d( 1, 0, -0.5 );
+ glVertex3d( 0.5, 0.5, 0.5 );
+ glVertex3d( 0.5, -0.5, 0.5 );
+ glVertex3d( 0, 0, -1.0 );
+
+ glNormal3d( 0, -1, -0.5 );
+ glVertex3d( 0.5, -0.5, 0.5 );
+ glVertex3d( -0.5, -0.5, 0.5 );
+ glVertex3d( 0, 0, -1.0 );
+ glEnd();
+}
diff --git a/src/ship.hpp b/src/ship.hpp
new file mode 100644
index 0000000..060c586
--- /dev/null
+++ b/src/ship.hpp
@@ -0,0 +1,60 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#ifndef _SHIP_HPP_
+#define _SHIP_HPP_
+
+#include <vector>
+#include <GL/gl.h>
+#include "vector.hpp"
+#include "model.hpp"
+
+class Ship
+{
+public:
+
+ Ship();
+ ~Ship();
+
+ void initialize();
+
+ double xpos() const throw() { return _pos.x; }
+ double ypos() const throw() { return _pos.y; }
+ double zpos() const throw() { return _pos.z; }
+ const Vector3& pos() const throw() { return _pos; }
+ Vector3& pos() throw() { return _pos; }
+ const Vector3& size() const throw() { return _size; }
+
+ void draw();
+ void drawDl();
+
+private:
+
+ void drawSimple();
+
+ Vector3 _pos;
+ Vector3 _size;
+
+ Model _model;
+
+ GLuint _shipDl;
+
+};
+
+#endif // _SHIP_HPP_
diff --git a/src/textprinter.cpp b/src/textprinter.cpp
new file mode 100644
index 0000000..129ad19
--- /dev/null
+++ b/src/textprinter.cpp
@@ -0,0 +1,48 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#include <ftgl.h>
+#include "textprinter.hpp"
+
+TextPrinter::TextPrinter( const std::string& fontfilename )
+ : font( 0 )
+{
+ font = new FTGLPixmapFont( fontfilename.c_str() );
+ if ( font->Error() )
+ delete font;
+}
+
+TextPrinter::~TextPrinter()
+{
+ delete font;
+}
+
+void TextPrinter::print( const std::string& text,
+ double x, double y,
+ TextPrinter::Alignment align
+)
+{
+ font->FaceSize( 28 );
+ if ( align == ALIGN_CENTER )
+ {
+ float w = font->Advance( text.c_str(), text.length() );
+ x -= w / 2;
+ }
+ font->Render( text.c_str(), text.length(), FTPoint( x, y ) );
+}
diff --git a/src/textprinter.hpp b/src/textprinter.hpp
new file mode 100644
index 0000000..f4b1114
--- /dev/null
+++ b/src/textprinter.hpp
@@ -0,0 +1,51 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#ifndef _TEXTPRINTER_HPP_
+#define _TEXTPRINTER_HPP_
+
+#include <string>
+
+class FTGLPixmapFont;
+
+class TextPrinter
+{
+
+public:
+
+ TextPrinter( const std::string& fontfilename );
+ ~TextPrinter();
+
+ enum Alignment {
+ ALIGN_LEFT,
+ ALIGN_CENTER,
+ };
+
+ void print( const std::string& text,
+ double x, double y,
+ Alignment align = ALIGN_LEFT
+ );
+
+private:
+
+ FTGLPixmapFont * font;
+
+};
+
+#endif // _TEXTPRINTER_HPP_
diff --git a/src/vector.hpp b/src/vector.hpp
new file mode 100644
index 0000000..4f4c603
--- /dev/null
+++ b/src/vector.hpp
@@ -0,0 +1,52 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#ifndef _POINT_HPP_
+#define _POINT_HPP_
+
+#include <cstddef>
+
+struct Vector3
+{
+
+ Vector3()
+ : x( 0 ), y( 0 ), z( 0 )
+ {
+ }
+
+ Vector3(double x_, double y_, double z_)
+ : x( x_ ), y( y_ ), z( z_ )
+ {
+ }
+
+ Vector3 offset(double dx, double dy, double dz) const throw()
+ {
+ return Vector3( x + dx, y + dy, z + dz );
+ }
+
+ Vector3 offset(const Vector3& d) const throw()
+ {
+ return offset( d.x, d.y, d.z );
+ }
+
+ double x, y, z;
+
+};
+
+#endif // _POINT_HPP_
diff --git a/src/world.cpp b/src/world.cpp
new file mode 100644
index 0000000..65318b7
--- /dev/null
+++ b/src/world.cpp
@@ -0,0 +1,125 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#include <GL/gl.h>
+#include <cstdlib>
+#include <ctime>
+#include <cmath>
+#include "world.hpp"
+
+World::World(
+ double acceleration, double strafespeed, double speedlimit
+ , double gravity, double jumpstrength
+)
+ : _ship(), _map( 0 )
+ , _currAcc( 0 ), _maxAcc( acceleration )
+ , _currStrafe( 0 ), _maxStrafe( strafespeed )
+ , _maxSpeed( speedlimit ), _zspeed( 0 )
+ , _yapex( 0 ), _tapex( 0 ), _gravity( gravity )
+ , _jstrength( jumpstrength ), _grounded( true )
+{
+ _ship.initialize();
+ _ship.pos().x = 0.5;
+}
+
+void World::startJump()
+{
+ if ( _grounded ||
+ _map->collide( AABB(
+ _ship.pos().offset(0, -0.2, 0),
+ _ship.pos().offset(0, -0.2, 0).offset(_ship.size())
+ ) ) )
+ {
+ _yapex = _ship.ypos() + _jstrength;
+ _tapex = sqrt( _jstrength / _gravity );
+ }
+}
+
+void World::draw( double zminClip )
+{
+ glPushMatrix();
+ glTranslated( _ship.xpos() - 0.5, _ship.ypos(), 0.0 );
+ glColor4f( 1, 0, 0, 0.25 );
+ _ship.drawDl();
+ glPopMatrix();
+ glColor3f( 0.8f, 1, 1 );
+ glTranslatef( -0.5, 0.0, _ship.zpos() );
+ _map->glDraw( _ship.zpos() - zminClip );
+}
+
+void World::update( int difference )
+{
+ double multiplier = ( (double)difference ) / 1000;
+
+ Vector3 newPos = _ship.pos();
+
+ AABB shipAabb(
+ Vector3( -_ship.size().x/2, 0, 0 ),
+ Vector3( _ship.size().x/2, _ship.size().y, _ship.size().z )
+ );
+
+ if ( _currAcc < -_maxAcc ) _currAcc = -_maxAcc;
+ else if ( _currAcc > _maxAcc ) _currAcc = _maxAcc;
+ _zspeed += _currAcc*multiplier;
+ if ( _zspeed < 0 ) _zspeed = 0;
+ if ( _zspeed > _maxSpeed ) _zspeed = _maxSpeed;
+
+ newPos.z += multiplier * _zspeed;
+ if ( _map->collide( shipAabb.offset( newPos ) ) )
+ {
+ newPos.z = _ship.pos().z;
+ _zspeed = 0;
+ }
+ else
+ _ship.pos().z = newPos.z;
+
+ if ( _currStrafe < -_maxStrafe ) _currStrafe = -_maxStrafe;
+ if ( _currStrafe > _maxStrafe ) _currStrafe = _maxStrafe;
+ if ( _currStrafe != 0 )
+ {
+ newPos.x += _currStrafe*multiplier;
+ if ( _map->collide( shipAabb.offset( newPos ) ) )
+ newPos.x = _ship.pos().x;
+ else
+ _ship.pos().x = newPos.x;
+ }
+
+ if ( _tapex <= 0 && _grounded )
+ {
+ _tapex = 0;
+ _yapex = _ship.pos().y;
+ }
+
+ _tapex -= multiplier;
+ newPos.y = _yapex - _gravity * ( _tapex*_tapex );
+ if ( _map->collide( shipAabb.offset( newPos ) ) )
+ {
+ newPos.y = _ship.pos().y;
+ if (_tapex < 0)
+ _grounded = true;
+ _tapex = 0;
+ _yapex = _ship.pos().y;
+ }
+ else
+ {
+ _ship.pos().y = newPos.y;
+ _grounded = false;
+ }
+
+}
diff --git a/src/world.hpp b/src/world.hpp
new file mode 100644
index 0000000..b81f536
--- /dev/null
+++ b/src/world.hpp
@@ -0,0 +1,62 @@
+//
+// This file is part of the game Skyways.
+// Copyright (C) 2009 Mark Nevill
+//
+// 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 2
+// 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, write to the Free Software
+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+//
+
+#ifndef _WORLD_HPP_
+#define _WORLD_HPP_
+
+#include "ship.hpp"
+#include "map.hpp"
+
+class World
+{
+
+public:
+
+ World(
+ double acceleration, double strafespeed, double speedlimit
+ , double gravity, double jumpstrength
+ );
+
+ void setMap(Map& map) throw() { _map = ↦ }
+
+ void setAcceleration( double accel ) { _currAcc = accel*_maxAcc; }
+ void setStrafe( double strafe ) { _currStrafe = strafe*_maxStrafe; }
+ void startJump();
+
+ void draw( double zminClip );
+ void update( int difference );
+
+ double distanceTraveled() const throw() { return _ship.pos().z; }
+ bool droppedOut() const throw() {
+ return _ship.pos().y < _map->lowestPoint() - 1;
+ }
+
+private:
+
+ Ship _ship;
+ Map* _map;
+ double _currAcc, _maxAcc;
+ double _currStrafe, _maxStrafe;
+ double _maxSpeed, _zspeed;
+ double _yapex, _tapex, _gravity;
+ double _jstrength;
+ bool _grounded;
+};
+
+#endif // _WORLD_HPP_
diff --git a/world b/world
new file mode 100644
index 0000000..65072a0
--- /dev/null
+++ b/world
@@ -0,0 +1,23 @@
+. flat 0
+_ cube -1
+- cube 0.25
+a tunnel 1.0
+o flat 0.75 tunnel 1.0
+b cube 1.5
+= cube 0 cube 2
+%%
+4
+10 : _
+30 : .
+20 : .
+10 :. -
+15 : -
+10 :. o
+10 :_ =
+10 : b
+10 : _
+10 :b
+10 :b _
+10 :
+10 : _
+10 : _
|
rbonvall/grasp-crew-scheduling
|
80a989086020e392bfdb167b7a201a3ba6e94b97
|
Find best solution
|
diff --git a/ga.py b/ga.py
index 412394e..2a2eb1e 100755
--- a/ga.py
+++ b/ga.py
@@ -1,170 +1,172 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
from csp import CrewSchedulingProblem, namedtuple
from random import choice, randrange
from numpy import dot, zeros, array, matrix, random, sum, abs, transpose
from operator import attrgetter
from itertools import izip as zip
range = xrange
class Problem:
# fields: A, c
def __init__(self, problem_file):
csp = CrewSchedulingProblem(problem_file)
columns, costs = [], []
for rotation in csp.generate_rotations():
column = zeros(len(csp.tasks), dtype='uint8')
for task in rotation.tasks:
column[task] = 1
columns.append(column)
costs.append(rotation.cost)
A = array(columns).transpose()
m, n = A.shape
alpha = [set() for row in range(m)]
beta = [set() for col in range(n)]
for row, col in transpose(A.nonzero()):
alpha[row].add(col)
beta [col].add(row)
self.A = A
self.costs = array(costs)
self.nr_tasks, self.nr_rotations = m, n
self.alpha = map(frozenset, alpha)
self.beta = map(frozenset, beta)
def __repr__(self):
return '<CSP problem, %dx%d>' % (self.nr_tasks, self.nr_rotations)
Solution = namedtuple('Solution', 'columns covering fitness unfitness')
def make_solution(problem, columns):
covering = dot(problem.A, columns)
fitness = dot(problem.costs, columns)
unfitness = sum(abs(covering - 1))
return Solution(columns, covering, fitness, unfitness)
def initial_solution(problem):
columns = zeros(problem.nr_rotations, dtype='uint8')
I = frozenset(range(problem.nr_tasks))
S, U = set(), set(I)
while U:
i = choice(list(U))
J = [j for j in problem.alpha[i] if not (problem.beta[j] & (I - U))]
if J:
j = choice(J)
columns[j] = 1
U -= problem.beta[j]
else:
U.remove(i)
#columns = random.randint(2, size=problem.nr_rotations).astype('uint8')
return make_solution(problem, columns)
def binary_tournament(population):
population_size = len(population)
candidates = [randrange(population_size) for _ in range(2)]
return min(candidates, key=lambda index: population[index].fitness)
def matching_selection(problem, population):
'''Indices of the solutions selected for crossover.'''
P1 = binary_tournament(population)
if population[P1].unfitness == 0:
P2 = binary_tournament(population)
else:
cols_P1 = population[P1].columns
def compatibility(k):
cols_Pk = population[k].columns
comp = sum(cols_P1 | cols_Pk) - sum(cols_P1 & cols_Pk)
return comp, population[P1].fitness # use fitness to break ties
P2 = max((k for k, sol in enumerate(population) if k != P1),
key=compatibility)
return (P1, P2)
def uniform_crossover(parent1, parent2):
'''Columns of the child after crossover.'''
mask = random.randint(2, size=parent1.columns.size)
return mask * parent1.columns + (1 - mask) * parent2.columns
def static_mutation(columns, M_s=3):
for _ in range(M_s):
j = randrange(columns.size)
columns[j] = 1 - columns[j]
return columns
def adaptive_mutation(columns, M_a=5, epsilon=0.5):
return columns
def repair(solution):
# ...
return solution
def ranking_replacement(population, child):
# Labels for solutions according to relation with child.
# Keys are pairs: (better fitness than child?, better unfitness than child?)
groups = {
(False, False): 1, (True, False): 2,
(False, True): 3, (True, True): 4,
}
solution_group = (groups[solution.fitness < child.fitness,
solution.unfitness < child.unfitness]
for solution in population)
# replacement criteria:
# 1. group with smallest label
# 2. worst unfitness
# 3. worst fitness
sort_key = lambda (k, (sol, group)): (group, -sol.unfitness, -sol.fitness)
worst_k, (worst_sol, worst_group) = min(
((k, (sol, group)) for k, (sol, group) in enumerate(zip(population, solution_group))),
key=sort_key)
population[worst_k] = child
return worst_k
def best_solution(population):
- # ...
- return 0
+ sort_key = lambda (k, sol): (sol.unfitness, sol.fitness)
+ best_k, best_sol = min(((k, sol) for k, sol in enumerate(population)),
+ key=sort_key)
+ return best_k
def ga(problem, population_size=100, nr_iterations=1000):
population = [initial_solution(problem) for k in range(population_size)]
best_k = best_solution(population)
for t in range(nr_iterations):
p1, p2 = matching_selection(problem, population)
child = uniform_crossover(population[p1], population[p2])
child = static_mutation(child)
child = adaptive_mutation(child)
child = repair(child)
ranking_replacement(population, child)
best_k = best_solution([best_solution, child])
return population[best_k]
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
(options, args) = parser.parse_args()
if not args:
parser.print_usage()
return
problem = Problem(open(args[0]))
print ga(problem)
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
d8f417f8711dda63cb6e892bad8dadedd731c38a
|
Ranking replacement implementation
|
diff --git a/ga.py b/ga.py
index 685628f..412394e 100755
--- a/ga.py
+++ b/ga.py
@@ -1,148 +1,170 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
from csp import CrewSchedulingProblem, namedtuple
from random import choice, randrange
from numpy import dot, zeros, array, matrix, random, sum, abs, transpose
from operator import attrgetter
+from itertools import izip as zip
range = xrange
class Problem:
# fields: A, c
def __init__(self, problem_file):
csp = CrewSchedulingProblem(problem_file)
columns, costs = [], []
for rotation in csp.generate_rotations():
column = zeros(len(csp.tasks), dtype='uint8')
for task in rotation.tasks:
column[task] = 1
columns.append(column)
costs.append(rotation.cost)
A = array(columns).transpose()
m, n = A.shape
alpha = [set() for row in range(m)]
beta = [set() for col in range(n)]
for row, col in transpose(A.nonzero()):
alpha[row].add(col)
beta [col].add(row)
self.A = A
self.costs = array(costs)
self.nr_tasks, self.nr_rotations = m, n
self.alpha = map(frozenset, alpha)
self.beta = map(frozenset, beta)
def __repr__(self):
return '<CSP problem, %dx%d>' % (self.nr_tasks, self.nr_rotations)
Solution = namedtuple('Solution', 'columns covering fitness unfitness')
def make_solution(problem, columns):
covering = dot(problem.A, columns)
fitness = dot(problem.costs, columns)
unfitness = sum(abs(covering - 1))
return Solution(columns, covering, fitness, unfitness)
def initial_solution(problem):
columns = zeros(problem.nr_rotations, dtype='uint8')
I = frozenset(range(problem.nr_tasks))
S, U = set(), set(I)
while U:
i = choice(list(U))
J = [j for j in problem.alpha[i] if not (problem.beta[j] & (I - U))]
if J:
j = choice(J)
columns[j] = 1
U -= problem.beta[j]
else:
U.remove(i)
#columns = random.randint(2, size=problem.nr_rotations).astype('uint8')
return make_solution(problem, columns)
def binary_tournament(population):
population_size = len(population)
candidates = [randrange(population_size) for _ in range(2)]
return min(candidates, key=lambda index: population[index].fitness)
def matching_selection(problem, population):
'''Indices of the solutions selected for crossover.'''
P1 = binary_tournament(population)
if population[P1].unfitness == 0:
P2 = binary_tournament(population)
else:
cols_P1 = population[P1].columns
def compatibility(k):
cols_Pk = population[k].columns
comp = sum(cols_P1 | cols_Pk) - sum(cols_P1 & cols_Pk)
return comp, population[P1].fitness # use fitness to break ties
P2 = max((k for k, sol in enumerate(population) if k != P1),
key=compatibility)
return (P1, P2)
def uniform_crossover(parent1, parent2):
'''Columns of the child after crossover.'''
mask = random.randint(2, size=parent1.columns.size)
return mask * parent1.columns + (1 - mask) * parent2.columns
def static_mutation(columns, M_s=3):
for _ in range(M_s):
j = randrange(columns.size)
columns[j] = 1 - columns[j]
return columns
def adaptive_mutation(columns, M_a=5, epsilon=0.5):
return columns
def repair(solution):
# ...
return solution
-def ranking_replacement(population, solution):
- # ...
- return
+def ranking_replacement(population, child):
+ # Labels for solutions according to relation with child.
+ # Keys are pairs: (better fitness than child?, better unfitness than child?)
+ groups = {
+ (False, False): 1, (True, False): 2,
+ (False, True): 3, (True, True): 4,
+ }
+ solution_group = (groups[solution.fitness < child.fitness,
+ solution.unfitness < child.unfitness]
+ for solution in population)
+
+ # replacement criteria:
+ # 1. group with smallest label
+ # 2. worst unfitness
+ # 3. worst fitness
+ sort_key = lambda (k, (sol, group)): (group, -sol.unfitness, -sol.fitness)
+ worst_k, (worst_sol, worst_group) = min(
+ ((k, (sol, group)) for k, (sol, group) in enumerate(zip(population, solution_group))),
+ key=sort_key)
+
+ population[worst_k] = child
+ return worst_k
+
+
def best_solution(population):
# ...
return 0
def ga(problem, population_size=100, nr_iterations=1000):
population = [initial_solution(problem) for k in range(population_size)]
best_k = best_solution(population)
for t in range(nr_iterations):
p1, p2 = matching_selection(problem, population)
child = uniform_crossover(population[p1], population[p2])
child = static_mutation(child)
child = adaptive_mutation(child)
child = repair(child)
ranking_replacement(population, child)
best_k = best_solution([best_solution, child])
return population[best_k]
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
(options, args) = parser.parse_args()
if not args:
parser.print_usage()
return
problem = Problem(open(args[0]))
print ga(problem)
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
faf8cae0c5b0edbe57a33845928512d3c445b99e
|
Smart solution construction
|
diff --git a/ga.py b/ga.py
index 12ccb5c..685628f 100755
--- a/ga.py
+++ b/ga.py
@@ -1,137 +1,148 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
from csp import CrewSchedulingProblem, namedtuple
from random import choice, randrange
from numpy import dot, zeros, array, matrix, random, sum, abs, transpose
from operator import attrgetter
range = xrange
class Problem:
# fields: A, c
def __init__(self, problem_file):
csp = CrewSchedulingProblem(problem_file)
columns, costs = [], []
for rotation in csp.generate_rotations():
column = zeros(len(csp.tasks), dtype='uint8')
for task in rotation.tasks:
column[task] = 1
columns.append(column)
costs.append(rotation.cost)
A = array(columns).transpose()
m, n = A.shape
alpha = [set() for row in range(m)]
beta = [set() for col in range(n)]
for row, col in transpose(A.nonzero()):
alpha[row].add(col)
beta [col].add(row)
self.A = A
self.costs = array(costs)
self.nr_tasks, self.nr_rotations = m, n
self.alpha = map(frozenset, alpha)
self.beta = map(frozenset, beta)
def __repr__(self):
return '<CSP problem, %dx%d>' % (self.nr_tasks, self.nr_rotations)
Solution = namedtuple('Solution', 'columns covering fitness unfitness')
def make_solution(problem, columns):
covering = dot(problem.A, columns)
fitness = dot(problem.costs, columns)
unfitness = sum(abs(covering - 1))
return Solution(columns, covering, fitness, unfitness)
-def construct_solution(problem):
- # TODO: smarter solution construction
- columns = random.randint(2, size=problem.nr_rotations).astype('uint8')
+def initial_solution(problem):
+ columns = zeros(problem.nr_rotations, dtype='uint8')
+ I = frozenset(range(problem.nr_tasks))
+ S, U = set(), set(I)
+ while U:
+ i = choice(list(U))
+ J = [j for j in problem.alpha[i] if not (problem.beta[j] & (I - U))]
+ if J:
+ j = choice(J)
+ columns[j] = 1
+ U -= problem.beta[j]
+ else:
+ U.remove(i)
+ #columns = random.randint(2, size=problem.nr_rotations).astype('uint8')
return make_solution(problem, columns)
def binary_tournament(population):
population_size = len(population)
candidates = [randrange(population_size) for _ in range(2)]
return min(candidates, key=lambda index: population[index].fitness)
def matching_selection(problem, population):
'''Indices of the solutions selected for crossover.'''
P1 = binary_tournament(population)
if population[P1].unfitness == 0:
P2 = binary_tournament(population)
else:
cols_P1 = population[P1].columns
def compatibility(k):
cols_Pk = population[k].columns
comp = sum(cols_P1 | cols_Pk) - sum(cols_P1 & cols_Pk)
return comp, population[P1].fitness # use fitness to break ties
P2 = max((k for k, sol in enumerate(population) if k != P1),
key=compatibility)
return (P1, P2)
def uniform_crossover(parent1, parent2):
'''Columns of the child after crossover.'''
mask = random.randint(2, size=parent1.columns.size)
return mask * parent1.columns + (1 - mask) * parent2.columns
def static_mutation(columns, M_s=3):
for _ in range(M_s):
j = randrange(columns.size)
columns[j] = 1 - columns[j]
return columns
def adaptive_mutation(columns, M_a=5, epsilon=0.5):
return columns
def repair(solution):
# ...
return solution
def ranking_replacement(population, solution):
# ...
return
def best_solution(population):
# ...
return 0
def ga(problem, population_size=100, nr_iterations=1000):
- population = [construct_solution(problem) for k in range(population_size)]
+ population = [initial_solution(problem) for k in range(population_size)]
best_k = best_solution(population)
for t in range(nr_iterations):
p1, p2 = matching_selection(problem, population)
child = uniform_crossover(population[p1], population[p2])
child = static_mutation(child)
child = adaptive_mutation(child)
child = repair(child)
ranking_replacement(population, child)
best_k = best_solution([best_solution, child])
return population[best_k]
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
(options, args) = parser.parse_args()
if not args:
parser.print_usage()
return
problem = Problem(open(args[0]))
print ga(problem)
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
0cf0d7ef35a4bfb3c60d1ef64f09add77971c3d2
|
Copy code from gamatrix to init alpha and beta
|
diff --git a/ga.py b/ga.py
index 62c4cb5..12ccb5c 100755
--- a/ga.py
+++ b/ga.py
@@ -1,120 +1,137 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
from csp import CrewSchedulingProblem, namedtuple
from random import choice, randrange
-from numpy import dot, zeros, array, matrix, random, sum, abs
+from numpy import dot, zeros, array, matrix, random, sum, abs, transpose
from operator import attrgetter
range = xrange
class Problem:
# fields: A, c
def __init__(self, problem_file):
csp = CrewSchedulingProblem(problem_file)
columns, costs = [], []
for rotation in csp.generate_rotations():
column = zeros(len(csp.tasks), dtype='uint8')
for task in rotation.tasks:
column[task] = 1
columns.append(column)
costs.append(rotation.cost)
- self.A = matrix(columns).transpose()
+
+ A = array(columns).transpose()
+ m, n = A.shape
+
+ alpha = [set() for row in range(m)]
+ beta = [set() for col in range(n)]
+ for row, col in transpose(A.nonzero()):
+ alpha[row].add(col)
+ beta [col].add(row)
+
+ self.A = A
self.costs = array(costs)
- self.nr_tasks, self.nr_rotations = self.A.shape
+ self.nr_tasks, self.nr_rotations = m, n
+ self.alpha = map(frozenset, alpha)
+ self.beta = map(frozenset, beta)
+
+ def __repr__(self):
+ return '<CSP problem, %dx%d>' % (self.nr_tasks, self.nr_rotations)
+
+
Solution = namedtuple('Solution', 'columns covering fitness unfitness')
def make_solution(problem, columns):
covering = dot(problem.A, columns)
fitness = dot(problem.costs, columns)
unfitness = sum(abs(covering - 1))
return Solution(columns, covering, fitness, unfitness)
def construct_solution(problem):
# TODO: smarter solution construction
columns = random.randint(2, size=problem.nr_rotations).astype('uint8')
return make_solution(problem, columns)
def binary_tournament(population):
population_size = len(population)
candidates = [randrange(population_size) for _ in range(2)]
return min(candidates, key=lambda index: population[index].fitness)
def matching_selection(problem, population):
'''Indices of the solutions selected for crossover.'''
P1 = binary_tournament(population)
if population[P1].unfitness == 0:
P2 = binary_tournament(population)
else:
cols_P1 = population[P1].columns
def compatibility(k):
cols_Pk = population[k].columns
comp = sum(cols_P1 | cols_Pk) - sum(cols_P1 & cols_Pk)
return comp, population[P1].fitness # use fitness to break ties
P2 = max((k for k, sol in enumerate(population) if k != P1),
key=compatibility)
return (P1, P2)
def uniform_crossover(parent1, parent2):
'''Columns of the child after crossover.'''
mask = random.randint(2, size=parent1.columns.size)
return mask * parent1.columns + (1 - mask) * parent2.columns
def static_mutation(columns, M_s=3):
for _ in range(M_s):
j = randrange(columns.size)
columns[j] = 1 - columns[j]
return columns
def adaptive_mutation(columns, M_a=5, epsilon=0.5):
return columns
def repair(solution):
# ...
return solution
def ranking_replacement(population, solution):
# ...
return
def best_solution(population):
# ...
return 0
def ga(problem, population_size=100, nr_iterations=1000):
population = [construct_solution(problem) for k in range(population_size)]
best_k = best_solution(population)
for t in range(nr_iterations):
p1, p2 = matching_selection(problem, population)
child = uniform_crossover(population[p1], population[p2])
child = static_mutation(child)
child = adaptive_mutation(child)
child = repair(child)
ranking_replacement(population, child)
best_k = best_solution([best_solution, child])
return population[best_k]
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
(options, args) = parser.parse_args()
if not args:
parser.print_usage()
return
problem = Problem(open(args[0]))
print ga(problem)
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
d80b24c43c0bb2eebda6abf0a568d5fd2a8b3409
|
Use unsigned matrices
|
diff --git a/ga.py b/ga.py
index 3e7d588..62c4cb5 100755
--- a/ga.py
+++ b/ga.py
@@ -1,120 +1,120 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
from csp import CrewSchedulingProblem, namedtuple
from random import choice, randrange
from numpy import dot, zeros, array, matrix, random, sum, abs
from operator import attrgetter
range = xrange
class Problem:
# fields: A, c
def __init__(self, problem_file):
csp = CrewSchedulingProblem(problem_file)
columns, costs = [], []
for rotation in csp.generate_rotations():
- column = zeros(len(csp.tasks), dtype='int8')
+ column = zeros(len(csp.tasks), dtype='uint8')
for task in rotation.tasks:
column[task] = 1
columns.append(column)
costs.append(rotation.cost)
self.A = matrix(columns).transpose()
self.costs = array(costs)
self.nr_tasks, self.nr_rotations = self.A.shape
Solution = namedtuple('Solution', 'columns covering fitness unfitness')
def make_solution(problem, columns):
covering = dot(problem.A, columns)
fitness = dot(problem.costs, columns)
unfitness = sum(abs(covering - 1))
return Solution(columns, covering, fitness, unfitness)
def construct_solution(problem):
# TODO: smarter solution construction
- columns = random.randint(2, size=problem.nr_rotations).astype('int8')
+ columns = random.randint(2, size=problem.nr_rotations).astype('uint8')
return make_solution(problem, columns)
def binary_tournament(population):
population_size = len(population)
candidates = [randrange(population_size) for _ in range(2)]
return min(candidates, key=lambda index: population[index].fitness)
def matching_selection(problem, population):
'''Indices of the solutions selected for crossover.'''
P1 = binary_tournament(population)
if population[P1].unfitness == 0:
P2 = binary_tournament(population)
else:
cols_P1 = population[P1].columns
def compatibility(k):
cols_Pk = population[k].columns
comp = sum(cols_P1 | cols_Pk) - sum(cols_P1 & cols_Pk)
return comp, population[P1].fitness # use fitness to break ties
P2 = max((k for k, sol in enumerate(population) if k != P1),
key=compatibility)
return (P1, P2)
def uniform_crossover(parent1, parent2):
'''Columns of the child after crossover.'''
mask = random.randint(2, size=parent1.columns.size)
return mask * parent1.columns + (1 - mask) * parent2.columns
def static_mutation(columns, M_s=3):
for _ in range(M_s):
j = randrange(columns.size)
columns[j] = 1 - columns[j]
return columns
def adaptive_mutation(columns, M_a=5, epsilon=0.5):
return columns
def repair(solution):
# ...
return solution
def ranking_replacement(population, solution):
# ...
return
def best_solution(population):
# ...
return 0
def ga(problem, population_size=100, nr_iterations=1000):
population = [construct_solution(problem) for k in range(population_size)]
best_k = best_solution(population)
for t in range(nr_iterations):
p1, p2 = matching_selection(problem, population)
child = uniform_crossover(population[p1], population[p2])
child = static_mutation(child)
child = adaptive_mutation(child)
child = repair(child)
ranking_replacement(population, child)
best_k = best_solution([best_solution, child])
return population[best_k]
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
(options, args) = parser.parse_args()
if not args:
parser.print_usage()
return
problem = Problem(open(args[0]))
print ga(problem)
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
9910e95b325ebc5b958a28c861fef520a7c05f51
|
Print solution
|
diff --git a/ga.py b/ga.py
index c20d4aa..3e7d588 100755
--- a/ga.py
+++ b/ga.py
@@ -1,119 +1,120 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
from csp import CrewSchedulingProblem, namedtuple
from random import choice, randrange
from numpy import dot, zeros, array, matrix, random, sum, abs
from operator import attrgetter
range = xrange
class Problem:
# fields: A, c
def __init__(self, problem_file):
csp = CrewSchedulingProblem(problem_file)
columns, costs = [], []
for rotation in csp.generate_rotations():
column = zeros(len(csp.tasks), dtype='int8')
for task in rotation.tasks:
column[task] = 1
columns.append(column)
costs.append(rotation.cost)
self.A = matrix(columns).transpose()
self.costs = array(costs)
self.nr_tasks, self.nr_rotations = self.A.shape
Solution = namedtuple('Solution', 'columns covering fitness unfitness')
def make_solution(problem, columns):
covering = dot(problem.A, columns)
fitness = dot(problem.costs, columns)
unfitness = sum(abs(covering - 1))
return Solution(columns, covering, fitness, unfitness)
def construct_solution(problem):
# TODO: smarter solution construction
columns = random.randint(2, size=problem.nr_rotations).astype('int8')
return make_solution(problem, columns)
def binary_tournament(population):
population_size = len(population)
candidates = [randrange(population_size) for _ in range(2)]
return min(candidates, key=lambda index: population[index].fitness)
def matching_selection(problem, population):
'''Indices of the solutions selected for crossover.'''
P1 = binary_tournament(population)
if population[P1].unfitness == 0:
P2 = binary_tournament(population)
else:
cols_P1 = population[P1].columns
def compatibility(k):
cols_Pk = population[k].columns
comp = sum(cols_P1 | cols_Pk) - sum(cols_P1 & cols_Pk)
return comp, population[P1].fitness # use fitness to break ties
P2 = max((k for k, sol in enumerate(population) if k != P1),
key=compatibility)
return (P1, P2)
def uniform_crossover(parent1, parent2):
'''Columns of the child after crossover.'''
mask = random.randint(2, size=parent1.columns.size)
return mask * parent1.columns + (1 - mask) * parent2.columns
def static_mutation(columns, M_s=3):
for _ in range(M_s):
j = randrange(columns.size)
columns[j] = 1 - columns[j]
return columns
def adaptive_mutation(columns, M_a=5, epsilon=0.5):
return columns
def repair(solution):
# ...
return solution
def ranking_replacement(population, solution):
# ...
return
def best_solution(population):
# ...
return 0
def ga(problem, population_size=100, nr_iterations=1000):
population = [construct_solution(problem) for k in range(population_size)]
best_k = best_solution(population)
for t in range(nr_iterations):
p1, p2 = matching_selection(problem, population)
child = uniform_crossover(population[p1], population[p2])
child = static_mutation(child)
child = adaptive_mutation(child)
child = repair(child)
ranking_replacement(population, child)
best_k = best_solution([best_solution, child])
return population[best_k]
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
(options, args) = parser.parse_args()
if not args:
parser.print_usage()
return
problem = Problem(open(args[0]))
+ print ga(problem)
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
115564b402f0f9e96e81b8afd1512f5152cdac49
|
Split mutation into static_ and adaptive_mutation
|
diff --git a/ga.py b/ga.py
index 346aaa8..c20d4aa 100755
--- a/ga.py
+++ b/ga.py
@@ -1,117 +1,119 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
from csp import CrewSchedulingProblem, namedtuple
from random import choice, randrange
from numpy import dot, zeros, array, matrix, random, sum, abs
from operator import attrgetter
range = xrange
class Problem:
# fields: A, c
def __init__(self, problem_file):
csp = CrewSchedulingProblem(problem_file)
columns, costs = [], []
for rotation in csp.generate_rotations():
column = zeros(len(csp.tasks), dtype='int8')
for task in rotation.tasks:
column[task] = 1
columns.append(column)
costs.append(rotation.cost)
self.A = matrix(columns).transpose()
self.costs = array(costs)
self.nr_tasks, self.nr_rotations = self.A.shape
Solution = namedtuple('Solution', 'columns covering fitness unfitness')
def make_solution(problem, columns):
covering = dot(problem.A, columns)
fitness = dot(problem.costs, columns)
unfitness = sum(abs(covering - 1))
return Solution(columns, covering, fitness, unfitness)
def construct_solution(problem):
# TODO: smarter solution construction
columns = random.randint(2, size=problem.nr_rotations).astype('int8')
return make_solution(problem, columns)
def binary_tournament(population):
population_size = len(population)
candidates = [randrange(population_size) for _ in range(2)]
return min(candidates, key=lambda index: population[index].fitness)
def matching_selection(problem, population):
'''Indices of the solutions selected for crossover.'''
P1 = binary_tournament(population)
if population[P1].unfitness == 0:
P2 = binary_tournament(population)
else:
cols_P1 = population[P1].columns
def compatibility(k):
cols_Pk = population[k].columns
comp = sum(cols_P1 | cols_Pk) - sum(cols_P1 & cols_Pk)
return comp, population[P1].fitness # use fitness to break ties
P2 = max((k for k, sol in enumerate(population) if k != P1),
key=compatibility)
return (P1, P2)
def uniform_crossover(parent1, parent2):
'''Columns of the child after crossover.'''
mask = random.randint(2, size=parent1.columns.size)
return mask * parent1.columns + (1 - mask) * parent2.columns
-def mutation(columns, M_s=3, M_a=5, epsilon=0.5):
- # static mutation
+def static_mutation(columns, M_s=3):
for _ in range(M_s):
j = randrange(columns.size)
columns[j] = 1 - columns[j]
- # adaptive mutation
- # ...
return columns
+def adaptive_mutation(columns, M_a=5, epsilon=0.5):
+ return columns
+
+
def repair(solution):
# ...
return solution
def ranking_replacement(population, solution):
# ...
return
def best_solution(population):
# ...
return 0
def ga(problem, population_size=100, nr_iterations=1000):
population = [construct_solution(problem) for k in range(population_size)]
best_k = best_solution(population)
for t in range(nr_iterations):
p1, p2 = matching_selection(problem, population)
child = uniform_crossover(population[p1], population[p2])
- child = mutation(child)
+ child = static_mutation(child)
+ child = adaptive_mutation(child)
child = repair(child)
ranking_replacement(population, child)
best_k = best_solution([best_solution, child])
return population[best_k]
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
(options, args) = parser.parse_args()
if not args:
parser.print_usage()
return
problem = Problem(open(args[0]))
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
6df74d8e2bb11743b7474028cd39788845cc7d49
|
Static mutation implemented
|
diff --git a/ga.py b/ga.py
index c4d6fe1..346aaa8 100755
--- a/ga.py
+++ b/ga.py
@@ -1,111 +1,117 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
from csp import CrewSchedulingProblem, namedtuple
-from random import choice
+from random import choice, randrange
from numpy import dot, zeros, array, matrix, random, sum, abs
from operator import attrgetter
range = xrange
class Problem:
# fields: A, c
def __init__(self, problem_file):
csp = CrewSchedulingProblem(problem_file)
columns, costs = [], []
for rotation in csp.generate_rotations():
column = zeros(len(csp.tasks), dtype='int8')
for task in rotation.tasks:
column[task] = 1
columns.append(column)
costs.append(rotation.cost)
self.A = matrix(columns).transpose()
self.costs = array(costs)
self.nr_tasks, self.nr_rotations = self.A.shape
Solution = namedtuple('Solution', 'columns covering fitness unfitness')
def make_solution(problem, columns):
covering = dot(problem.A, columns)
fitness = dot(problem.costs, columns)
unfitness = sum(abs(covering - 1))
return Solution(columns, covering, fitness, unfitness)
def construct_solution(problem):
# TODO: smarter solution construction
columns = random.randint(2, size=problem.nr_rotations).astype('int8')
return make_solution(problem, columns)
def binary_tournament(population):
population_size = len(population)
candidates = [randrange(population_size) for _ in range(2)]
return min(candidates, key=lambda index: population[index].fitness)
def matching_selection(problem, population):
'''Indices of the solutions selected for crossover.'''
P1 = binary_tournament(population)
if population[P1].unfitness == 0:
P2 = binary_tournament(population)
else:
cols_P1 = population[P1].columns
def compatibility(k):
cols_Pk = population[k].columns
comp = sum(cols_P1 | cols_Pk) - sum(cols_P1 & cols_Pk)
return comp, population[P1].fitness # use fitness to break ties
P2 = max((k for k, sol in enumerate(population) if k != P1),
key=compatibility)
return (P1, P2)
def uniform_crossover(parent1, parent2):
+ '''Columns of the child after crossover.'''
mask = random.randint(2, size=parent1.columns.size)
return mask * parent1.columns + (1 - mask) * parent2.columns
-def mutation(solution, M_s=3, M_a=5, epsilon=0.5):
- # ...
- return solution
+def mutation(columns, M_s=3, M_a=5, epsilon=0.5):
+ # static mutation
+ for _ in range(M_s):
+ j = randrange(columns.size)
+ columns[j] = 1 - columns[j]
+ # adaptive mutation
+ # ...
+ return columns
def repair(solution):
# ...
return solution
def ranking_replacement(population, solution):
# ...
return
def best_solution(population):
# ...
return 0
def ga(problem, population_size=100, nr_iterations=1000):
population = [construct_solution(problem) for k in range(population_size)]
best_k = best_solution(population)
for t in range(nr_iterations):
p1, p2 = matching_selection(problem, population)
child = uniform_crossover(population[p1], population[p2])
child = mutation(child)
child = repair(child)
ranking_replacement(population, child)
best_k = best_solution([best_solution, child])
return population[best_k]
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
(options, args) = parser.parse_args()
if not args:
parser.print_usage()
return
problem = Problem(open(args[0]))
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
e9e21be03a86c8337859b5df665e0f3b285b7207
|
chmod +x ga.py
|
diff --git a/ga.py b/ga.py
old mode 100644
new mode 100755
|
rbonvall/grasp-crew-scheduling
|
c8d988eb339e1f960d9c507f53ecb56b7254866c
|
Remove more numpy references
|
diff --git a/ga.py b/ga.py
index 67f4bdc..d153e44 100644
--- a/ga.py
+++ b/ga.py
@@ -1,111 +1,111 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
from csp import CrewSchedulingProblem, namedtuple
from random import choice
from numpy import dot, zeros, array, matrix, random, sum, abs
from operator import attrgetter
range = xrange
class Problem:
# fields: A, c
def __init__(self, problem_file):
csp = CrewSchedulingProblem(problem_file)
columns, costs = [], []
for rotation in csp.generate_rotations():
column = zeros(len(csp.tasks), dtype='int8')
for task in rotation.tasks:
column[task] = 1
columns.append(column)
costs.append(rotation.cost)
- self.A = numpy.matrix(columns).transpose()
- self.costs = numpy.array(costs)
+ self.A = matrix(columns).transpose()
+ self.costs = array(costs)
self.nr_tasks, self.nr_rotations = self.A.shape
Solution = namedtuple('Solution', 'columns covering fitness unfitness')
def make_solution(problem, columns):
covering = dot(problem.A, columns)
fitness = dot(problem.costs, columns)
unfitness = sum(abs(covering - 1))
return Solution(columns, covering, fitness, unfitness)
def construct_solution(problem):
# TODO: smarter solution construction
columns = random.randint(2, size=problem.nr_rotations).astype('int8')
return make_solution(problem, columns)
def binary_tournament(population):
population_size = len(population)
candidates = [randrange(population_size) for _ in range(2)]
return min(candidates, key=lambda index: population[index].fitness)
def matching_selection(problem, population):
'''Indices of the solutions selected for crossover.'''
P1 = binary_tournament(population)
if population[P1].unfitness == 0:
P2 = binary_tournament(population)
else:
cols_P1 = population[P1].columns
def compatibility(k):
cols_Pk = population[k].columns
comp = sum(cols_P1 | cols_Pk) - sum(cols_P1 & cols_Pk)
return comp, population[P1].fitness # use fitness to break ties
P2 = max((k for k, sol in enumerate(population) if k != P1),
key=compatibility)
return (P1, P2)
def uniform_crossover(parent1, parent2):
mask = random.randint(2, size=parent1.columns.size)
return mask * parent1.columns + (1 - mask) * parent2.columns
def mutation(solution, M_s=3, M_a=5, epsilon=0.5):
# ...
return solution
def repair(solution):
# ...
return solution
def ranking_replacement(population, solution):
# ...
return
def best_solution(population):
# ...
return 0
def ga(problem, population_size=100, nr_iterations=1000):
population = [construct_solution(problem) for k in range(population_size)]
best_k = best_solution(population)
for t in range(nr_iterations):
p1, p2 = matching_selection(problem, population)
child = uniform_crossover(population[p1], population[p2])
child = mutation(child)
child = repair(child)
ranking_replacement(population, child)
best_k = best_solution([best_solution, child])
return population[best_k]
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
(options, args) = parser.parse_args()
if not args:
parser.print_help()
return
problem = Problem(open(args[0]))
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
05e98c70d3c27a4b6e5d62aeccd36c6eba0c2fb8
|
numpy.zeros -> zeros call
|
diff --git a/ga.py b/ga.py
index b7a0981..67f4bdc 100644
--- a/ga.py
+++ b/ga.py
@@ -1,111 +1,111 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
from csp import CrewSchedulingProblem, namedtuple
from random import choice
from numpy import dot, zeros, array, matrix, random, sum, abs
from operator import attrgetter
range = xrange
class Problem:
# fields: A, c
def __init__(self, problem_file):
csp = CrewSchedulingProblem(problem_file)
columns, costs = [], []
for rotation in csp.generate_rotations():
- column = numpy.zeros(len(csp.tasks), dtype='int8')
+ column = zeros(len(csp.tasks), dtype='int8')
for task in rotation.tasks:
column[task] = 1
columns.append(column)
costs.append(rotation.cost)
self.A = numpy.matrix(columns).transpose()
self.costs = numpy.array(costs)
self.nr_tasks, self.nr_rotations = self.A.shape
Solution = namedtuple('Solution', 'columns covering fitness unfitness')
def make_solution(problem, columns):
covering = dot(problem.A, columns)
fitness = dot(problem.costs, columns)
unfitness = sum(abs(covering - 1))
return Solution(columns, covering, fitness, unfitness)
def construct_solution(problem):
# TODO: smarter solution construction
columns = random.randint(2, size=problem.nr_rotations).astype('int8')
return make_solution(problem, columns)
def binary_tournament(population):
population_size = len(population)
candidates = [randrange(population_size) for _ in range(2)]
return min(candidates, key=lambda index: population[index].fitness)
def matching_selection(problem, population):
'''Indices of the solutions selected for crossover.'''
P1 = binary_tournament(population)
if population[P1].unfitness == 0:
P2 = binary_tournament(population)
else:
cols_P1 = population[P1].columns
def compatibility(k):
cols_Pk = population[k].columns
comp = sum(cols_P1 | cols_Pk) - sum(cols_P1 & cols_Pk)
return comp, population[P1].fitness # use fitness to break ties
P2 = max((k for k, sol in enumerate(population) if k != P1),
key=compatibility)
return (P1, P2)
def uniform_crossover(parent1, parent2):
mask = random.randint(2, size=parent1.columns.size)
return mask * parent1.columns + (1 - mask) * parent2.columns
def mutation(solution, M_s=3, M_a=5, epsilon=0.5):
# ...
return solution
def repair(solution):
# ...
return solution
def ranking_replacement(population, solution):
# ...
return
def best_solution(population):
# ...
return 0
def ga(problem, population_size=100, nr_iterations=1000):
population = [construct_solution(problem) for k in range(population_size)]
best_k = best_solution(population)
for t in range(nr_iterations):
p1, p2 = matching_selection(problem, population)
child = uniform_crossover(population[p1], population[p2])
child = mutation(child)
child = repair(child)
ranking_replacement(population, child)
best_k = best_solution([best_solution, child])
return population[best_k]
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
(options, args) = parser.parse_args()
if not args:
parser.print_help()
return
problem = Problem(open(args[0]))
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
dd8ec8e60493c8924bc8dda6dc3ca2366aaf52d0
|
Print usage instead of help
|
diff --git a/ga.py b/ga.py
index e808df2..d977c0b 100644
--- a/ga.py
+++ b/ga.py
@@ -1,118 +1,118 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
from csp import CrewSchedulingProblem, namedtuple
from random import choice
import numpy
from operator import attrgetter
range = xrange
class Problem:
# fields: A, c
def __init__(self, problem_file):
csp = CrewSchedulingProblem(problem_file)
columns, costs = [], []
for rotation in csp.generate_rotations():
column = numpy.zeros(len(csp.tasks), dtype='int8')
for task in rotation.tasks:
column[task] = 1
columns.append(column)
costs.append(rotation.cost)
self.A = numpy.matrix(columns).transpose()
self.costs = numpy.array(costs)
class Solution:
__slots__ = ['columns', 'fitness', 'unfitness']
def __init__(self, columns, problem):
self.columns = numpy.array(columns).astype('int8')
self.fitness = fitness(problem, self.columns)
self.unfitness = unfitness(problem, self.columns)
def __eq__(self, other):
return (self.columns == other.columns).all()
def __neq__(self, other):
return not (self == other)
def __repr__(self):
return 'Solution(%s, f=%d, u=%d)' % (
str.join('', map(str, columns)), self.fitness, self.unfitness)
def fitness(problem, solution):
return numpy.dot(problem.costs, solution)
def unfitness(problem, solution):
w = numpy.dot(problem.A, solution)
return numpy.sum(numpy.abs(w - 1))
def construct_solution():
# s = ...
return Solution(s)
def binary_tournament(population):
candidates = [choice(population), choice(population)]
return min(candidates, key=attrgetter('fitness'))
def most_compatible(population, P1):
#P2 = ...
return P2
def matching_selection(population):
P1 = binary_tournament(population)
if P1.unfitness == 0:
P2 = binary_tournament(population)
else:
P2 = most_compatible(population, P1)
return (P1, P2)
def uniform_crossover(P1, P2):
mask = numpy.random.randint(2, size=P1.size)
child = mask * P1.columns + (1 - mask) * P2.columns
return Solution(child)
def mutation(solution, M_s, M_a, epsilon):
return solution
def repair(solution):
return solution
def ranking_replacement(population, solution):
return
def best_solution(solutions):
return solutions[0]
def ga(population_size, nr_iterations):
population = [construct_solution() for k in range(population_size)]
best = best_solution(population)
for t in range(nr_iterations):
P1, P2 = matching_selection(population)
C = uniform_crossover(P1, P2)
C = mutation(C, M_s, M_a, epsilon)
C = repair(C)
ranking_replacement(population, C)
best = best_solution([best_solution, C])
return best
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
(options, args) = parser.parse_args()
if not args:
- parser.print_help()
+ parser.print_usage()
return
problem = Problem(open(args[0]))
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
b5ebc282a334e0acf9e491812fb125c408f517d5
|
Rewrite matching related functions
|
diff --git a/ga.py b/ga.py
index 448c114..b7a0981 100644
--- a/ga.py
+++ b/ga.py
@@ -1,107 +1,111 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
from csp import CrewSchedulingProblem, namedtuple
from random import choice
from numpy import dot, zeros, array, matrix, random, sum, abs
from operator import attrgetter
range = xrange
class Problem:
# fields: A, c
def __init__(self, problem_file):
csp = CrewSchedulingProblem(problem_file)
columns, costs = [], []
for rotation in csp.generate_rotations():
column = numpy.zeros(len(csp.tasks), dtype='int8')
for task in rotation.tasks:
column[task] = 1
columns.append(column)
costs.append(rotation.cost)
self.A = numpy.matrix(columns).transpose()
self.costs = numpy.array(costs)
self.nr_tasks, self.nr_rotations = self.A.shape
Solution = namedtuple('Solution', 'columns covering fitness unfitness')
def make_solution(problem, columns):
covering = dot(problem.A, columns)
fitness = dot(problem.costs, columns)
unfitness = sum(abs(covering - 1))
return Solution(columns, covering, fitness, unfitness)
def construct_solution(problem):
# TODO: smarter solution construction
columns = random.randint(2, size=problem.nr_rotations).astype('int8')
return make_solution(problem, columns)
def binary_tournament(population):
- candidates = [choice(population), choice(population)]
- return min(candidates, key=attrgetter('fitness'))
+ population_size = len(population)
+ candidates = [randrange(population_size) for _ in range(2)]
+ return min(candidates, key=lambda index: population[index].fitness)
-def most_compatible(population, P1):
- #P2 = ...
- return P2
-
-def matching_selection(population):
+def matching_selection(problem, population):
+ '''Indices of the solutions selected for crossover.'''
P1 = binary_tournament(population)
- if P1.unfitness == 0:
+ if population[P1].unfitness == 0:
P2 = binary_tournament(population)
else:
- P2 = most_compatible(population, P1)
+ cols_P1 = population[P1].columns
+ def compatibility(k):
+ cols_Pk = population[k].columns
+ comp = sum(cols_P1 | cols_Pk) - sum(cols_P1 & cols_Pk)
+ return comp, population[P1].fitness # use fitness to break ties
+ P2 = max((k for k, sol in enumerate(population) if k != P1),
+ key=compatibility)
return (P1, P2)
def uniform_crossover(parent1, parent2):
mask = random.randint(2, size=parent1.columns.size)
return mask * parent1.columns + (1 - mask) * parent2.columns
def mutation(solution, M_s=3, M_a=5, epsilon=0.5):
# ...
return solution
def repair(solution):
# ...
return solution
def ranking_replacement(population, solution):
# ...
return
def best_solution(population):
# ...
return 0
def ga(problem, population_size=100, nr_iterations=1000):
population = [construct_solution(problem) for k in range(population_size)]
best_k = best_solution(population)
for t in range(nr_iterations):
p1, p2 = matching_selection(problem, population)
child = uniform_crossover(population[p1], population[p2])
child = mutation(child)
child = repair(child)
ranking_replacement(population, child)
best_k = best_solution([best_solution, child])
return population[best_k]
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
(options, args) = parser.parse_args()
if not args:
parser.print_help()
return
problem = Problem(open(args[0]))
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
fc53758bbb5f5b5edfc6d1a686a3e7261ecb43b5
|
Rewrite uniform_crossover function
|
diff --git a/ga.py b/ga.py
index 6f9df8f..448c114 100644
--- a/ga.py
+++ b/ga.py
@@ -1,109 +1,107 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
from csp import CrewSchedulingProblem, namedtuple
from random import choice
from numpy import dot, zeros, array, matrix, random, sum, abs
from operator import attrgetter
range = xrange
class Problem:
# fields: A, c
def __init__(self, problem_file):
csp = CrewSchedulingProblem(problem_file)
columns, costs = [], []
for rotation in csp.generate_rotations():
column = numpy.zeros(len(csp.tasks), dtype='int8')
for task in rotation.tasks:
column[task] = 1
columns.append(column)
costs.append(rotation.cost)
self.A = numpy.matrix(columns).transpose()
self.costs = numpy.array(costs)
self.nr_tasks, self.nr_rotations = self.A.shape
Solution = namedtuple('Solution', 'columns covering fitness unfitness')
def make_solution(problem, columns):
covering = dot(problem.A, columns)
fitness = dot(problem.costs, columns)
unfitness = sum(abs(covering - 1))
return Solution(columns, covering, fitness, unfitness)
def construct_solution(problem):
# TODO: smarter solution construction
columns = random.randint(2, size=problem.nr_rotations).astype('int8')
return make_solution(problem, columns)
def binary_tournament(population):
candidates = [choice(population), choice(population)]
return min(candidates, key=attrgetter('fitness'))
def most_compatible(population, P1):
#P2 = ...
return P2
def matching_selection(population):
P1 = binary_tournament(population)
if P1.unfitness == 0:
P2 = binary_tournament(population)
else:
P2 = most_compatible(population, P1)
return (P1, P2)
-def uniform_crossover(P1, P2):
- mask = numpy.random.randint(2, size=P1.size)
- child = mask * P1.columns + (1 - mask) * P2.columns
- return Solution(child)
-
+def uniform_crossover(parent1, parent2):
+ mask = random.randint(2, size=parent1.columns.size)
+ return mask * parent1.columns + (1 - mask) * parent2.columns
def mutation(solution, M_s=3, M_a=5, epsilon=0.5):
# ...
return solution
def repair(solution):
# ...
return solution
def ranking_replacement(population, solution):
# ...
return
def best_solution(population):
# ...
return 0
def ga(problem, population_size=100, nr_iterations=1000):
population = [construct_solution(problem) for k in range(population_size)]
best_k = best_solution(population)
for t in range(nr_iterations):
p1, p2 = matching_selection(problem, population)
child = uniform_crossover(population[p1], population[p2])
child = mutation(child)
child = repair(child)
ranking_replacement(population, child)
best_k = best_solution([best_solution, child])
return population[best_k]
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
(options, args) = parser.parse_args()
if not args:
parser.print_help()
return
problem = Problem(open(args[0]))
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
c550a8baff62fda3fc3b7a0477779aaab1e593b5
|
Rewrite some no-op functions
|
diff --git a/ga.py b/ga.py
index 55df06b..6f9df8f 100644
--- a/ga.py
+++ b/ga.py
@@ -1,105 +1,109 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
from csp import CrewSchedulingProblem, namedtuple
from random import choice
from numpy import dot, zeros, array, matrix, random, sum, abs
from operator import attrgetter
range = xrange
class Problem:
# fields: A, c
def __init__(self, problem_file):
csp = CrewSchedulingProblem(problem_file)
columns, costs = [], []
for rotation in csp.generate_rotations():
column = numpy.zeros(len(csp.tasks), dtype='int8')
for task in rotation.tasks:
column[task] = 1
columns.append(column)
costs.append(rotation.cost)
self.A = numpy.matrix(columns).transpose()
self.costs = numpy.array(costs)
self.nr_tasks, self.nr_rotations = self.A.shape
Solution = namedtuple('Solution', 'columns covering fitness unfitness')
def make_solution(problem, columns):
covering = dot(problem.A, columns)
fitness = dot(problem.costs, columns)
unfitness = sum(abs(covering - 1))
return Solution(columns, covering, fitness, unfitness)
def construct_solution(problem):
# TODO: smarter solution construction
columns = random.randint(2, size=problem.nr_rotations).astype('int8')
return make_solution(problem, columns)
def binary_tournament(population):
candidates = [choice(population), choice(population)]
return min(candidates, key=attrgetter('fitness'))
def most_compatible(population, P1):
#P2 = ...
return P2
def matching_selection(population):
P1 = binary_tournament(population)
if P1.unfitness == 0:
P2 = binary_tournament(population)
else:
P2 = most_compatible(population, P1)
return (P1, P2)
def uniform_crossover(P1, P2):
mask = numpy.random.randint(2, size=P1.size)
child = mask * P1.columns + (1 - mask) * P2.columns
return Solution(child)
-def mutation(solution, M_s, M_a, epsilon):
+
+def mutation(solution, M_s=3, M_a=5, epsilon=0.5):
+ # ...
return solution
def repair(solution):
+ # ...
return solution
def ranking_replacement(population, solution):
+ # ...
return
-def best_solution(solutions):
- return solutions[0]
-
+def best_solution(population):
+ # ...
+ return 0
def ga(problem, population_size=100, nr_iterations=1000):
population = [construct_solution(problem) for k in range(population_size)]
best_k = best_solution(population)
for t in range(nr_iterations):
p1, p2 = matching_selection(problem, population)
child = uniform_crossover(population[p1], population[p2])
child = mutation(child)
child = repair(child)
ranking_replacement(population, child)
best_k = best_solution([best_solution, child])
return population[best_k]
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
(options, args) = parser.parse_args()
if not args:
parser.print_help()
return
problem = Problem(open(args[0]))
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
05741b19d8dac7cea8f9fe690e295732838be57f
|
Rewrite ga function
|
diff --git a/ga.py b/ga.py
index 1640fc9..55df06b 100644
--- a/ga.py
+++ b/ga.py
@@ -1,105 +1,105 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
from csp import CrewSchedulingProblem, namedtuple
from random import choice
from numpy import dot, zeros, array, matrix, random, sum, abs
from operator import attrgetter
range = xrange
class Problem:
# fields: A, c
def __init__(self, problem_file):
csp = CrewSchedulingProblem(problem_file)
columns, costs = [], []
for rotation in csp.generate_rotations():
column = numpy.zeros(len(csp.tasks), dtype='int8')
for task in rotation.tasks:
column[task] = 1
columns.append(column)
costs.append(rotation.cost)
self.A = numpy.matrix(columns).transpose()
self.costs = numpy.array(costs)
self.nr_tasks, self.nr_rotations = self.A.shape
Solution = namedtuple('Solution', 'columns covering fitness unfitness')
def make_solution(problem, columns):
covering = dot(problem.A, columns)
fitness = dot(problem.costs, columns)
unfitness = sum(abs(covering - 1))
return Solution(columns, covering, fitness, unfitness)
def construct_solution(problem):
# TODO: smarter solution construction
columns = random.randint(2, size=problem.nr_rotations).astype('int8')
return make_solution(problem, columns)
def binary_tournament(population):
candidates = [choice(population), choice(population)]
return min(candidates, key=attrgetter('fitness'))
def most_compatible(population, P1):
#P2 = ...
return P2
def matching_selection(population):
P1 = binary_tournament(population)
if P1.unfitness == 0:
P2 = binary_tournament(population)
else:
P2 = most_compatible(population, P1)
return (P1, P2)
def uniform_crossover(P1, P2):
mask = numpy.random.randint(2, size=P1.size)
child = mask * P1.columns + (1 - mask) * P2.columns
return Solution(child)
def mutation(solution, M_s, M_a, epsilon):
return solution
def repair(solution):
return solution
def ranking_replacement(population, solution):
return
def best_solution(solutions):
return solutions[0]
-def ga(population_size, nr_iterations):
- population = [construct_solution() for k in range(population_size)]
- best = best_solution(population)
+def ga(problem, population_size=100, nr_iterations=1000):
+ population = [construct_solution(problem) for k in range(population_size)]
+ best_k = best_solution(population)
for t in range(nr_iterations):
- P1, P2 = matching_selection(population)
- C = uniform_crossover(P1, P2)
- C = mutation(C, M_s, M_a, epsilon)
- C = repair(C)
- ranking_replacement(population, C)
- best = best_solution([best_solution, C])
- return best
+ p1, p2 = matching_selection(problem, population)
+ child = uniform_crossover(population[p1], population[p2])
+ child = mutation(child)
+ child = repair(child)
+ ranking_replacement(population, child)
+ best_k = best_solution([best_solution, child])
+ return population[best_k]
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
(options, args) = parser.parse_args()
if not args:
parser.print_help()
return
problem = Problem(open(args[0]))
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
800255aa1183295156edb0ddd0e266b85a27aba4
|
Import names from numpy
|
diff --git a/ga.py b/ga.py
index 75bd077..1640fc9 100644
--- a/ga.py
+++ b/ga.py
@@ -1,105 +1,105 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
from csp import CrewSchedulingProblem, namedtuple
from random import choice
-import numpy
+from numpy import dot, zeros, array, matrix, random, sum, abs
from operator import attrgetter
range = xrange
class Problem:
# fields: A, c
def __init__(self, problem_file):
csp = CrewSchedulingProblem(problem_file)
columns, costs = [], []
for rotation in csp.generate_rotations():
column = numpy.zeros(len(csp.tasks), dtype='int8')
for task in rotation.tasks:
column[task] = 1
columns.append(column)
costs.append(rotation.cost)
self.A = numpy.matrix(columns).transpose()
self.costs = numpy.array(costs)
self.nr_tasks, self.nr_rotations = self.A.shape
Solution = namedtuple('Solution', 'columns covering fitness unfitness')
def make_solution(problem, columns):
covering = dot(problem.A, columns)
fitness = dot(problem.costs, columns)
unfitness = sum(abs(covering - 1))
return Solution(columns, covering, fitness, unfitness)
def construct_solution(problem):
# TODO: smarter solution construction
columns = random.randint(2, size=problem.nr_rotations).astype('int8')
return make_solution(problem, columns)
def binary_tournament(population):
candidates = [choice(population), choice(population)]
return min(candidates, key=attrgetter('fitness'))
def most_compatible(population, P1):
#P2 = ...
return P2
def matching_selection(population):
P1 = binary_tournament(population)
if P1.unfitness == 0:
P2 = binary_tournament(population)
else:
P2 = most_compatible(population, P1)
return (P1, P2)
def uniform_crossover(P1, P2):
mask = numpy.random.randint(2, size=P1.size)
child = mask * P1.columns + (1 - mask) * P2.columns
return Solution(child)
def mutation(solution, M_s, M_a, epsilon):
return solution
def repair(solution):
return solution
def ranking_replacement(population, solution):
return
def best_solution(solutions):
return solutions[0]
def ga(population_size, nr_iterations):
population = [construct_solution() for k in range(population_size)]
best = best_solution(population)
for t in range(nr_iterations):
P1, P2 = matching_selection(population)
C = uniform_crossover(P1, P2)
C = mutation(C, M_s, M_a, epsilon)
C = repair(C)
ranking_replacement(population, C)
best = best_solution([best_solution, C])
return best
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
(options, args) = parser.parse_args()
if not args:
parser.print_help()
return
problem = Problem(open(args[0]))
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
db907f61f18d8b509ba06736dc0c866d1d52555a
|
Dumb solution construction, for the moment
|
diff --git a/ga.py b/ga.py
index e418681..75bd077 100644
--- a/ga.py
+++ b/ga.py
@@ -1,105 +1,105 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
from csp import CrewSchedulingProblem, namedtuple
from random import choice
import numpy
from operator import attrgetter
range = xrange
class Problem:
# fields: A, c
def __init__(self, problem_file):
csp = CrewSchedulingProblem(problem_file)
columns, costs = [], []
for rotation in csp.generate_rotations():
column = numpy.zeros(len(csp.tasks), dtype='int8')
for task in rotation.tasks:
column[task] = 1
columns.append(column)
costs.append(rotation.cost)
self.A = numpy.matrix(columns).transpose()
self.costs = numpy.array(costs)
self.nr_tasks, self.nr_rotations = self.A.shape
Solution = namedtuple('Solution', 'columns covering fitness unfitness')
def make_solution(problem, columns):
covering = dot(problem.A, columns)
fitness = dot(problem.costs, columns)
unfitness = sum(abs(covering - 1))
return Solution(columns, covering, fitness, unfitness)
-def construct_solution():
- # s = ...
- return Solution(s)
-
+def construct_solution(problem):
+ # TODO: smarter solution construction
+ columns = random.randint(2, size=problem.nr_rotations).astype('int8')
+ return make_solution(problem, columns)
def binary_tournament(population):
candidates = [choice(population), choice(population)]
return min(candidates, key=attrgetter('fitness'))
def most_compatible(population, P1):
#P2 = ...
return P2
def matching_selection(population):
P1 = binary_tournament(population)
if P1.unfitness == 0:
P2 = binary_tournament(population)
else:
P2 = most_compatible(population, P1)
return (P1, P2)
def uniform_crossover(P1, P2):
mask = numpy.random.randint(2, size=P1.size)
child = mask * P1.columns + (1 - mask) * P2.columns
return Solution(child)
def mutation(solution, M_s, M_a, epsilon):
return solution
def repair(solution):
return solution
def ranking_replacement(population, solution):
return
def best_solution(solutions):
return solutions[0]
def ga(population_size, nr_iterations):
population = [construct_solution() for k in range(population_size)]
best = best_solution(population)
for t in range(nr_iterations):
P1, P2 = matching_selection(population)
C = uniform_crossover(P1, P2)
C = mutation(C, M_s, M_a, epsilon)
C = repair(C)
ranking_replacement(population, C)
best = best_solution([best_solution, C])
return best
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
(options, args) = parser.parse_args()
if not args:
parser.print_help()
return
problem = Problem(open(args[0]))
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
7b2a3022879ec884942bd4980118f731891339a9
|
Solution as namedtuple, and constructor function
|
diff --git a/ga.py b/ga.py
index a192a14..e418681 100644
--- a/ga.py
+++ b/ga.py
@@ -1,119 +1,105 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
from csp import CrewSchedulingProblem, namedtuple
from random import choice
import numpy
from operator import attrgetter
range = xrange
class Problem:
# fields: A, c
def __init__(self, problem_file):
csp = CrewSchedulingProblem(problem_file)
columns, costs = [], []
for rotation in csp.generate_rotations():
column = numpy.zeros(len(csp.tasks), dtype='int8')
for task in rotation.tasks:
column[task] = 1
columns.append(column)
costs.append(rotation.cost)
self.A = numpy.matrix(columns).transpose()
self.costs = numpy.array(costs)
self.nr_tasks, self.nr_rotations = self.A.shape
-class Solution:
- __slots__ = ['columns', 'fitness', 'unfitness']
- def __init__(self, columns, problem):
- self.columns = numpy.array(columns).astype('int8')
- self.fitness = fitness(problem, self.columns)
- self.unfitness = unfitness(problem, self.columns)
- def __eq__(self, other):
- return (self.columns == other.columns).all()
- def __neq__(self, other):
- return not (self == other)
- def __repr__(self):
- return 'Solution(%s, f=%d, u=%d)' % (
- str.join('', map(str, columns)), self.fitness, self.unfitness)
-
-def fitness(problem, solution):
- return numpy.dot(problem.costs, solution)
-
-def unfitness(problem, solution):
- w = numpy.dot(problem.A, solution)
- return numpy.sum(numpy.abs(w - 1))
+Solution = namedtuple('Solution', 'columns covering fitness unfitness')
+def make_solution(problem, columns):
+ covering = dot(problem.A, columns)
+ fitness = dot(problem.costs, columns)
+ unfitness = sum(abs(covering - 1))
+ return Solution(columns, covering, fitness, unfitness)
def construct_solution():
# s = ...
return Solution(s)
def binary_tournament(population):
candidates = [choice(population), choice(population)]
return min(candidates, key=attrgetter('fitness'))
def most_compatible(population, P1):
#P2 = ...
return P2
def matching_selection(population):
P1 = binary_tournament(population)
if P1.unfitness == 0:
P2 = binary_tournament(population)
else:
P2 = most_compatible(population, P1)
return (P1, P2)
def uniform_crossover(P1, P2):
mask = numpy.random.randint(2, size=P1.size)
child = mask * P1.columns + (1 - mask) * P2.columns
return Solution(child)
def mutation(solution, M_s, M_a, epsilon):
return solution
def repair(solution):
return solution
def ranking_replacement(population, solution):
return
def best_solution(solutions):
return solutions[0]
def ga(population_size, nr_iterations):
population = [construct_solution() for k in range(population_size)]
best = best_solution(population)
for t in range(nr_iterations):
P1, P2 = matching_selection(population)
C = uniform_crossover(P1, P2)
C = mutation(C, M_s, M_a, epsilon)
C = repair(C)
ranking_replacement(population, C)
best = best_solution([best_solution, C])
return best
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
(options, args) = parser.parse_args()
if not args:
parser.print_help()
return
problem = Problem(open(args[0]))
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
37696c0318ebc275cac4b8bef58be6f366e200c0
|
Add problem size information to Problem
|
diff --git a/ga.py b/ga.py
index e808df2..a192a14 100644
--- a/ga.py
+++ b/ga.py
@@ -1,118 +1,119 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
from csp import CrewSchedulingProblem, namedtuple
from random import choice
import numpy
from operator import attrgetter
range = xrange
class Problem:
# fields: A, c
def __init__(self, problem_file):
csp = CrewSchedulingProblem(problem_file)
columns, costs = [], []
for rotation in csp.generate_rotations():
column = numpy.zeros(len(csp.tasks), dtype='int8')
for task in rotation.tasks:
column[task] = 1
columns.append(column)
costs.append(rotation.cost)
self.A = numpy.matrix(columns).transpose()
self.costs = numpy.array(costs)
+ self.nr_tasks, self.nr_rotations = self.A.shape
class Solution:
__slots__ = ['columns', 'fitness', 'unfitness']
def __init__(self, columns, problem):
self.columns = numpy.array(columns).astype('int8')
self.fitness = fitness(problem, self.columns)
self.unfitness = unfitness(problem, self.columns)
def __eq__(self, other):
return (self.columns == other.columns).all()
def __neq__(self, other):
return not (self == other)
def __repr__(self):
return 'Solution(%s, f=%d, u=%d)' % (
str.join('', map(str, columns)), self.fitness, self.unfitness)
def fitness(problem, solution):
return numpy.dot(problem.costs, solution)
def unfitness(problem, solution):
w = numpy.dot(problem.A, solution)
return numpy.sum(numpy.abs(w - 1))
def construct_solution():
# s = ...
return Solution(s)
def binary_tournament(population):
candidates = [choice(population), choice(population)]
return min(candidates, key=attrgetter('fitness'))
def most_compatible(population, P1):
#P2 = ...
return P2
def matching_selection(population):
P1 = binary_tournament(population)
if P1.unfitness == 0:
P2 = binary_tournament(population)
else:
P2 = most_compatible(population, P1)
return (P1, P2)
def uniform_crossover(P1, P2):
mask = numpy.random.randint(2, size=P1.size)
child = mask * P1.columns + (1 - mask) * P2.columns
return Solution(child)
def mutation(solution, M_s, M_a, epsilon):
return solution
def repair(solution):
return solution
def ranking_replacement(population, solution):
return
def best_solution(solutions):
return solutions[0]
def ga(population_size, nr_iterations):
population = [construct_solution() for k in range(population_size)]
best = best_solution(population)
for t in range(nr_iterations):
P1, P2 = matching_selection(population)
C = uniform_crossover(P1, P2)
C = mutation(C, M_s, M_a, epsilon)
C = repair(C)
ranking_replacement(population, C)
best = best_solution([best_solution, C])
return best
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
(options, args) = parser.parse_args()
if not args:
parser.print_help()
return
problem = Problem(open(args[0]))
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
46d1ee2bff78964b36c74c6472c1061feb99636e
|
Exit when no command line arg is given
|
diff --git a/ga.py b/ga.py
index a56f4d9..e808df2 100644
--- a/ga.py
+++ b/ga.py
@@ -1,115 +1,118 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
from csp import CrewSchedulingProblem, namedtuple
from random import choice
import numpy
from operator import attrgetter
range = xrange
class Problem:
# fields: A, c
def __init__(self, problem_file):
csp = CrewSchedulingProblem(problem_file)
columns, costs = [], []
for rotation in csp.generate_rotations():
column = numpy.zeros(len(csp.tasks), dtype='int8')
for task in rotation.tasks:
column[task] = 1
columns.append(column)
costs.append(rotation.cost)
self.A = numpy.matrix(columns).transpose()
self.costs = numpy.array(costs)
class Solution:
__slots__ = ['columns', 'fitness', 'unfitness']
def __init__(self, columns, problem):
self.columns = numpy.array(columns).astype('int8')
self.fitness = fitness(problem, self.columns)
self.unfitness = unfitness(problem, self.columns)
def __eq__(self, other):
return (self.columns == other.columns).all()
def __neq__(self, other):
return not (self == other)
def __repr__(self):
return 'Solution(%s, f=%d, u=%d)' % (
str.join('', map(str, columns)), self.fitness, self.unfitness)
def fitness(problem, solution):
return numpy.dot(problem.costs, solution)
def unfitness(problem, solution):
w = numpy.dot(problem.A, solution)
return numpy.sum(numpy.abs(w - 1))
def construct_solution():
# s = ...
return Solution(s)
def binary_tournament(population):
candidates = [choice(population), choice(population)]
return min(candidates, key=attrgetter('fitness'))
def most_compatible(population, P1):
#P2 = ...
return P2
def matching_selection(population):
P1 = binary_tournament(population)
if P1.unfitness == 0:
P2 = binary_tournament(population)
else:
P2 = most_compatible(population, P1)
return (P1, P2)
def uniform_crossover(P1, P2):
mask = numpy.random.randint(2, size=P1.size)
child = mask * P1.columns + (1 - mask) * P2.columns
return Solution(child)
def mutation(solution, M_s, M_a, epsilon):
return solution
def repair(solution):
return solution
def ranking_replacement(population, solution):
return
def best_solution(solutions):
return solutions[0]
def ga(population_size, nr_iterations):
population = [construct_solution() for k in range(population_size)]
best = best_solution(population)
for t in range(nr_iterations):
P1, P2 = matching_selection(population)
C = uniform_crossover(P1, P2)
C = mutation(C, M_s, M_a, epsilon)
C = repair(C)
ranking_replacement(population, C)
best = best_solution([best_solution, C])
return best
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
(options, args) = parser.parse_args()
+ if not args:
+ parser.print_help()
+ return
problem = Problem(open(args[0]))
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
6e25088dc1052cb8f6f89c6ad07b34923daa6c43
|
Problem.c -> Problem.rotation_costs
|
diff --git a/gamatrix.py b/gamatrix.py
index 0e56cbe..eb6b7c6 100644
--- a/gamatrix.py
+++ b/gamatrix.py
@@ -1,87 +1,86 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
from csp import CrewSchedulingProblem, namedtuple, frozenset
from random import choice
from operator import attrgetter
from numpy import *
range = xrange
class Problem:
# fields: A, c, alpha, beta
def __init__(self, problem_file):
csp = CrewSchedulingProblem(problem_file)
columns, costs = [], []
for rotation in csp.generate_rotations():
column = zeros(len(csp.tasks), dtype='uint8')
for task in rotation.tasks:
column[task] = 1
columns.append(column)
costs.append(rotation.cost)
A = array(columns).transpose()
- c = array(costs)
m, n = A.shape
alpha = [set() for row in range(m)]
beta = [set() for col in range(n)]
for row, col in transpose(A.nonzero()):
alpha[row].add(col)
beta [col].add(row)
self.A = A
- self.c = c
+ self.rotation_costs = array(costs)
self.nr_rows, self.nr_cols = m, n
self.alpha = map(frozenset, alpha)
self.beta = map(frozenset, beta)
def __repr__(self):
return '<CSP problem, %dx%d>' % (self.nr_rows, self.nr_cols)
def initial_solution(problem, population_size=1):
solution = zeros((problem.nr_cols, population_size), dtype='uint8')
I = frozenset(range(problem.nr_rows))
for k in range(population_size):
S, U = set(), set(I)
while U:
i = choice(list(U))
J = [j for j in problem.alpha[i] if not (problem.beta[j] & (I - U))]
if J:
j = choice(J)
solution[j, k] = 1
U -= problem.beta[j]
else:
U.remove(i)
return solution
def ga(problem, nr_iterations=100, population_size=100):
population = [initial_solution(problem, population_size)
for k in range(population_size)]
best = best_solution(population)
for t in range(nr_iterations):
P1, P2 = matching_selection(population)
C = uniform_crossover(P1, P2)
C = mutation(C, M_s, M_a, epsilon)
C = repair(C)
ranking_replacement(population, C)
best = best_solution([best_solution, C])
return best
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
(options, args) = parser.parse_args()
problem = Problem(open(args[0]))
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
381f88df8275a2dafe81f7fd874ba7288113bcb0
|
Use unsigned matrices
|
diff --git a/gamatrix.py b/gamatrix.py
index 307a020..0e56cbe 100644
--- a/gamatrix.py
+++ b/gamatrix.py
@@ -1,87 +1,87 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
from csp import CrewSchedulingProblem, namedtuple, frozenset
from random import choice
from operator import attrgetter
from numpy import *
range = xrange
class Problem:
# fields: A, c, alpha, beta
def __init__(self, problem_file):
csp = CrewSchedulingProblem(problem_file)
columns, costs = [], []
for rotation in csp.generate_rotations():
- column = zeros(len(csp.tasks), dtype='int8')
+ column = zeros(len(csp.tasks), dtype='uint8')
for task in rotation.tasks:
column[task] = 1
columns.append(column)
costs.append(rotation.cost)
A = array(columns).transpose()
c = array(costs)
m, n = A.shape
alpha = [set() for row in range(m)]
beta = [set() for col in range(n)]
for row, col in transpose(A.nonzero()):
alpha[row].add(col)
beta [col].add(row)
self.A = A
self.c = c
self.nr_rows, self.nr_cols = m, n
self.alpha = map(frozenset, alpha)
self.beta = map(frozenset, beta)
def __repr__(self):
return '<CSP problem, %dx%d>' % (self.nr_rows, self.nr_cols)
def initial_solution(problem, population_size=1):
- solution = zeros((problem.nr_cols, population_size), dtype='int8')
+ solution = zeros((problem.nr_cols, population_size), dtype='uint8')
I = frozenset(range(problem.nr_rows))
for k in range(population_size):
S, U = set(), set(I)
while U:
i = choice(list(U))
J = [j for j in problem.alpha[i] if not (problem.beta[j] & (I - U))]
if J:
j = choice(J)
solution[j, k] = 1
U -= problem.beta[j]
else:
U.remove(i)
return solution
def ga(problem, nr_iterations=100, population_size=100):
population = [initial_solution(problem, population_size)
for k in range(population_size)]
best = best_solution(population)
for t in range(nr_iterations):
P1, P2 = matching_selection(population)
C = uniform_crossover(P1, P2)
C = mutation(C, M_s, M_a, epsilon)
C = repair(C)
ranking_replacement(population, C)
best = best_solution([best_solution, C])
return best
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
(options, args) = parser.parse_args()
problem = Problem(open(args[0]))
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
1d8041fcf59eba9cc7723ef8aca8b2f1e7df3169
|
Genetic algorithm outline
|
diff --git a/gamatrix.py b/gamatrix.py
index 2d041ee..307a020 100644
--- a/gamatrix.py
+++ b/gamatrix.py
@@ -1,73 +1,87 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
from csp import CrewSchedulingProblem, namedtuple, frozenset
from random import choice
from operator import attrgetter
from numpy import *
range = xrange
class Problem:
# fields: A, c, alpha, beta
def __init__(self, problem_file):
csp = CrewSchedulingProblem(problem_file)
columns, costs = [], []
for rotation in csp.generate_rotations():
column = zeros(len(csp.tasks), dtype='int8')
for task in rotation.tasks:
column[task] = 1
columns.append(column)
costs.append(rotation.cost)
A = array(columns).transpose()
c = array(costs)
m, n = A.shape
alpha = [set() for row in range(m)]
beta = [set() for col in range(n)]
for row, col in transpose(A.nonzero()):
alpha[row].add(col)
beta [col].add(row)
self.A = A
self.c = c
self.nr_rows, self.nr_cols = m, n
self.alpha = map(frozenset, alpha)
self.beta = map(frozenset, beta)
def __repr__(self):
return '<CSP problem, %dx%d>' % (self.nr_rows, self.nr_cols)
def initial_solution(problem, population_size=1):
solution = zeros((problem.nr_cols, population_size), dtype='int8')
I = frozenset(range(problem.nr_rows))
for k in range(population_size):
S, U = set(), set(I)
while U:
i = choice(list(U))
J = [j for j in problem.alpha[i] if not (problem.beta[j] & (I - U))]
if J:
j = choice(J)
solution[j, k] = 1
U -= problem.beta[j]
else:
U.remove(i)
return solution
+def ga(problem, nr_iterations=100, population_size=100):
+ population = [initial_solution(problem, population_size)
+ for k in range(population_size)]
+ best = best_solution(population)
+ for t in range(nr_iterations):
+ P1, P2 = matching_selection(population)
+ C = uniform_crossover(P1, P2)
+ C = mutation(C, M_s, M_a, epsilon)
+ C = repair(C)
+ ranking_replacement(population, C)
+ best = best_solution([best_solution, C])
+ return best
+
+
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
(options, args) = parser.parse_args()
problem = Problem(open(args[0]))
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
6b2f8b55ba06ad0ed0260c4573c8e78aa7176bb8
|
Initial solution as function rather than method
|
diff --git a/gamatrix.py b/gamatrix.py
index a77481c..2d041ee 100644
--- a/gamatrix.py
+++ b/gamatrix.py
@@ -1,79 +1,73 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
from csp import CrewSchedulingProblem, namedtuple, frozenset
from random import choice
from operator import attrgetter
from numpy import *
range = xrange
class Problem:
# fields: A, c, alpha, beta
def __init__(self, problem_file):
csp = CrewSchedulingProblem(problem_file)
columns, costs = [], []
for rotation in csp.generate_rotations():
column = zeros(len(csp.tasks), dtype='int8')
for task in rotation.tasks:
column[task] = 1
columns.append(column)
costs.append(rotation.cost)
A = array(columns).transpose()
c = array(costs)
m, n = A.shape
alpha = [set() for row in range(m)]
beta = [set() for col in range(n)]
for row, col in transpose(A.nonzero()):
alpha[row].add(col)
beta [col].add(row)
self.A = A
self.c = c
self.nr_rows, self.nr_cols = m, n
self.alpha = map(frozenset, alpha)
self.beta = map(frozenset, beta)
def __repr__(self):
return '<CSP problem, %dx%d>' % (self.nr_rows, self.nr_cols)
- def initial_solution(self, population_size=1):
- solution = zeros((self.nr_cols, population_size), dtype='int8')
- I = frozenset(range(self.nr_rows))
- for k in range(population_size):
- S, U = set(), set(I)
- while U:
- i = choice(list(U))
- J = [j for j in self.alpha[i] if not (self.beta[j] & (I - U))]
- if J:
- j = choice(J)
- solution[j, k] = 1
- U -= self.beta[j]
- else:
- U.remove(i)
- return solution
+def initial_solution(problem, population_size=1):
+ solution = zeros((problem.nr_cols, population_size), dtype='int8')
+ I = frozenset(range(problem.nr_rows))
+ for k in range(population_size):
+ S, U = set(), set(I)
+ while U:
+ i = choice(list(U))
+ J = [j for j in problem.alpha[i] if not (problem.beta[j] & (I - U))]
+ if J:
+ j = choice(J)
+ solution[j, k] = 1
+ U -= problem.beta[j]
+ else:
+ U.remove(i)
+ return solution
-
-
-
-
-
-
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
(options, args) = parser.parse_args()
problem = Problem(open(args[0]))
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
c702d7a22a1c1dc712e3419cddcf532c9fb2c141
|
Problem __repr__
|
diff --git a/gamatrix.py b/gamatrix.py
index de2d3c6..a77481c 100644
--- a/gamatrix.py
+++ b/gamatrix.py
@@ -1,76 +1,79 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
from csp import CrewSchedulingProblem, namedtuple, frozenset
from random import choice
from operator import attrgetter
from numpy import *
range = xrange
class Problem:
# fields: A, c, alpha, beta
def __init__(self, problem_file):
csp = CrewSchedulingProblem(problem_file)
columns, costs = [], []
for rotation in csp.generate_rotations():
column = zeros(len(csp.tasks), dtype='int8')
for task in rotation.tasks:
column[task] = 1
columns.append(column)
costs.append(rotation.cost)
A = array(columns).transpose()
c = array(costs)
m, n = A.shape
alpha = [set() for row in range(m)]
beta = [set() for col in range(n)]
for row, col in transpose(A.nonzero()):
alpha[row].add(col)
beta [col].add(row)
self.A = A
self.c = c
self.nr_rows, self.nr_cols = m, n
self.alpha = map(frozenset, alpha)
self.beta = map(frozenset, beta)
+ def __repr__(self):
+ return '<CSP problem, %dx%d>' % (self.nr_rows, self.nr_cols)
+
def initial_solution(self, population_size=1):
solution = zeros((self.nr_cols, population_size), dtype='int8')
I = frozenset(range(self.nr_rows))
for k in range(population_size):
S, U = set(), set(I)
while U:
i = choice(list(U))
J = [j for j in self.alpha[i] if not (self.beta[j] & (I - U))]
if J:
j = choice(J)
solution[j, k] = 1
U -= self.beta[j]
else:
U.remove(i)
return solution
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
(options, args) = parser.parse_args()
problem = Problem(open(args[0]))
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
a4e25a43567f1ca9d5338a2b6531a753c01101b4
|
Method for constructing initial population
|
diff --git a/gamatrix.py b/gamatrix.py
index 2602382..de2d3c6 100644
--- a/gamatrix.py
+++ b/gamatrix.py
@@ -1,61 +1,76 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
from csp import CrewSchedulingProblem, namedtuple, frozenset
from random import choice
from operator import attrgetter
from numpy import *
range = xrange
class Problem:
# fields: A, c, alpha, beta
def __init__(self, problem_file):
csp = CrewSchedulingProblem(problem_file)
columns, costs = [], []
for rotation in csp.generate_rotations():
column = zeros(len(csp.tasks), dtype='int8')
for task in rotation.tasks:
column[task] = 1
columns.append(column)
costs.append(rotation.cost)
A = array(columns).transpose()
c = array(costs)
m, n = A.shape
alpha = [set() for row in range(m)]
beta = [set() for col in range(n)]
for row, col in transpose(A.nonzero()):
alpha[row].add(col)
beta [col].add(row)
self.A = A
self.c = c
self.nr_rows, self.nr_cols = m, n
self.alpha = map(frozenset, alpha)
self.beta = map(frozenset, beta)
+ def initial_solution(self, population_size=1):
+ solution = zeros((self.nr_cols, population_size), dtype='int8')
+ I = frozenset(range(self.nr_rows))
+ for k in range(population_size):
+ S, U = set(), set(I)
+ while U:
+ i = choice(list(U))
+ J = [j for j in self.alpha[i] if not (self.beta[j] & (I - U))]
+ if J:
+ j = choice(J)
+ solution[j, k] = 1
+ U -= self.beta[j]
+ else:
+ U.remove(i)
+ return solution
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
(options, args) = parser.parse_args()
problem = Problem(open(args[0]))
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
01d3375f9aa55a313a3b0cc589d3cd40d53b5055
|
Freeze alpha and beta, add nr_rows & nr_cols
|
diff --git a/gamatrix.py b/gamatrix.py
index 8b5aedb..2602382 100644
--- a/gamatrix.py
+++ b/gamatrix.py
@@ -1,60 +1,61 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
-from csp import CrewSchedulingProblem, namedtuple
+from csp import CrewSchedulingProblem, namedtuple, frozenset
from random import choice
from operator import attrgetter
from numpy import *
range = xrange
class Problem:
# fields: A, c, alpha, beta
def __init__(self, problem_file):
csp = CrewSchedulingProblem(problem_file)
columns, costs = [], []
for rotation in csp.generate_rotations():
column = zeros(len(csp.tasks), dtype='int8')
for task in rotation.tasks:
column[task] = 1
columns.append(column)
costs.append(rotation.cost)
A = array(columns).transpose()
c = array(costs)
m, n = A.shape
alpha = [set() for row in range(m)]
beta = [set() for col in range(n)]
for row, col in transpose(A.nonzero()):
alpha[row].add(col)
beta [col].add(row)
self.A = A
self.c = c
- self.alpha = alpha
- self.beta = beta
+ self.nr_rows, self.nr_cols = m, n
+ self.alpha = map(frozenset, alpha)
+ self.beta = map(frozenset, beta)
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
(options, args) = parser.parse_args()
problem = Problem(open(args[0]))
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
1a9824b920e08430f51342fa0e2c544358feb062
|
Describe problem with matrices
|
diff --git a/gamatrix.py b/gamatrix.py
new file mode 100644
index 0000000..8b5aedb
--- /dev/null
+++ b/gamatrix.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python
+
+# Genetic algorithm taken from:
+# P.C.Chu, J.E.Beasley.
+# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
+# Journal of Heuristics, 11: 323--357 (1998)
+
+from csp import CrewSchedulingProblem, namedtuple
+from random import choice
+from operator import attrgetter
+from numpy import *
+range = xrange
+
+class Problem:
+ # fields: A, c, alpha, beta
+ def __init__(self, problem_file):
+ csp = CrewSchedulingProblem(problem_file)
+ columns, costs = [], []
+ for rotation in csp.generate_rotations():
+ column = zeros(len(csp.tasks), dtype='int8')
+ for task in rotation.tasks:
+ column[task] = 1
+ columns.append(column)
+ costs.append(rotation.cost)
+
+ A = array(columns).transpose()
+ c = array(costs)
+ m, n = A.shape
+
+ alpha = [set() for row in range(m)]
+ beta = [set() for col in range(n)]
+ for row, col in transpose(A.nonzero()):
+ alpha[row].add(col)
+ beta [col].add(row)
+
+ self.A = A
+ self.c = c
+ self.alpha = alpha
+ self.beta = beta
+
+
+
+
+
+
+
+
+
+
+
+def main():
+ from optparse import OptionParser
+ parser = OptionParser(usage="usage: %prog [options] [input_file]")
+ (options, args) = parser.parse_args()
+ problem = Problem(open(args[0]))
+
+if __name__ == '__main__':
+ main()
+
+
|
rbonvall/grasp-crew-scheduling
|
fe758da7a374dade150dd2e94b00eafaddb89edd
|
Fitness and unfitness implementation
|
diff --git a/ga.py b/ga.py
index 3d8590c..a56f4d9 100644
--- a/ga.py
+++ b/ga.py
@@ -1,112 +1,115 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
from csp import CrewSchedulingProblem, namedtuple
from random import choice
import numpy
from operator import attrgetter
range = xrange
class Problem:
# fields: A, c
def __init__(self, problem_file):
csp = CrewSchedulingProblem(problem_file)
columns, costs = [], []
for rotation in csp.generate_rotations():
column = numpy.zeros(len(csp.tasks), dtype='int8')
for task in rotation.tasks:
column[task] = 1
columns.append(column)
costs.append(rotation.cost)
self.A = numpy.matrix(columns).transpose()
self.costs = numpy.array(costs)
class Solution:
__slots__ = ['columns', 'fitness', 'unfitness']
- def __init__(self, columns):
+ def __init__(self, columns, problem):
self.columns = numpy.array(columns).astype('int8')
- self.fitness = fitness(self.columns)
- self.unfitness = unfitness(self.columns)
+ self.fitness = fitness(problem, self.columns)
+ self.unfitness = unfitness(problem, self.columns)
def __eq__(self, other):
return (self.columns == other.columns).all()
def __neq__(self, other):
return not (self == other)
def __repr__(self):
return 'Solution(%s, f=%d, u=%d)' % (
str.join('', map(str, columns)), self.fitness, self.unfitness)
-def fitness(solution):
- pass
-def unfitness(solution):
- pass
+def fitness(problem, solution):
+ return numpy.dot(problem.costs, solution)
+
+def unfitness(problem, solution):
+ w = numpy.dot(problem.A, solution)
+ return numpy.sum(numpy.abs(w - 1))
+
def construct_solution():
# s = ...
return Solution(s)
def binary_tournament(population):
candidates = [choice(population), choice(population)]
return min(candidates, key=attrgetter('fitness'))
def most_compatible(population, P1):
#P2 = ...
return P2
def matching_selection(population):
P1 = binary_tournament(population)
if P1.unfitness == 0:
P2 = binary_tournament(population)
else:
P2 = most_compatible(population, P1)
return (P1, P2)
def uniform_crossover(P1, P2):
mask = numpy.random.randint(2, size=P1.size)
child = mask * P1.columns + (1 - mask) * P2.columns
return Solution(child)
def mutation(solution, M_s, M_a, epsilon):
return solution
def repair(solution):
return solution
def ranking_replacement(population, solution):
return
def best_solution(solutions):
return solutions[0]
def ga(population_size, nr_iterations):
population = [construct_solution() for k in range(population_size)]
best = best_solution(population)
for t in range(nr_iterations):
P1, P2 = matching_selection(population)
C = uniform_crossover(P1, P2)
C = mutation(C, M_s, M_a, epsilon)
C = repair(C)
ranking_replacement(population, C)
best = best_solution([best_solution, C])
return best
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
(options, args) = parser.parse_args()
problem = Problem(open(args[0]))
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
603ad278afdbd2fab01d6469474910d56b807dad
|
Problem class
|
diff --git a/ga.py b/ga.py
index 4b02784..3d8590c 100644
--- a/ga.py
+++ b/ga.py
@@ -1,107 +1,112 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
from csp import CrewSchedulingProblem, namedtuple
from random import choice
import numpy
from operator import attrgetter
range = xrange
+class Problem:
+ # fields: A, c
+ def __init__(self, problem_file):
+ csp = CrewSchedulingProblem(problem_file)
+ columns, costs = [], []
+ for rotation in csp.generate_rotations():
+ column = numpy.zeros(len(csp.tasks), dtype='int8')
+ for task in rotation.tasks:
+ column[task] = 1
+ columns.append(column)
+ costs.append(rotation.cost)
+ self.A = numpy.matrix(columns).transpose()
+ self.costs = numpy.array(costs)
+
class Solution:
__slots__ = ['columns', 'fitness', 'unfitness']
def __init__(self, columns):
self.columns = numpy.array(columns).astype('int8')
self.fitness = fitness(self.columns)
self.unfitness = unfitness(self.columns)
def __eq__(self, other):
return (self.columns == other.columns).all()
def __neq__(self, other):
return not (self == other)
def __repr__(self):
return 'Solution(%s, f=%d, u=%d)' % (
str.join('', map(str, columns)), self.fitness, self.unfitness)
def fitness(solution):
pass
def unfitness(solution):
pass
def construct_solution():
# s = ...
return Solution(s)
def binary_tournament(population):
candidates = [choice(population), choice(population)]
return min(candidates, key=attrgetter('fitness'))
def most_compatible(population, P1):
#P2 = ...
return P2
def matching_selection(population):
P1 = binary_tournament(population)
if P1.unfitness == 0:
P2 = binary_tournament(population)
else:
P2 = most_compatible(population, P1)
return (P1, P2)
def uniform_crossover(P1, P2):
mask = numpy.random.randint(2, size=P1.size)
child = mask * P1.columns + (1 - mask) * P2.columns
return Solution(child)
def mutation(solution, M_s, M_a, epsilon):
return solution
def repair(solution):
return solution
def ranking_replacement(population, solution):
return
def best_solution(solutions):
return solutions[0]
def ga(population_size, nr_iterations):
population = [construct_solution() for k in range(population_size)]
best = best_solution(population)
for t in range(nr_iterations):
P1, P2 = matching_selection(population)
C = uniform_crossover(P1, P2)
C = mutation(C, M_s, M_a, epsilon)
C = repair(C)
ranking_replacement(population, C)
best = best_solution([best_solution, C])
return best
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
(options, args) = parser.parse_args()
- csp = CrewSchedulingProblem(open(args[0]))
- columns, costs = [], []
- for rotation in csp.generate_rotations():
- column = numpy.zeros(len(csp.tasks), dtype='int8')
- for task in rotation.tasks:
- column[task] = 1
- columns.append(column)
- costs.append(rotation.cost)
- A = numpy.matrix(columns).transpose()
- c = numpy.array(costs)
+ problem = Problem(open(args[0]))
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
c7614809f387690716760ae8b38b605671abc92c
|
Create matrix A and cost vector
|
diff --git a/ga.py b/ga.py
index 4fa7e78..4b02784 100644
--- a/ga.py
+++ b/ga.py
@@ -1,95 +1,107 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
from csp import CrewSchedulingProblem, namedtuple
from random import choice
import numpy
from operator import attrgetter
range = xrange
class Solution:
__slots__ = ['columns', 'fitness', 'unfitness']
def __init__(self, columns):
self.columns = numpy.array(columns).astype('int8')
self.fitness = fitness(self.columns)
self.unfitness = unfitness(self.columns)
def __eq__(self, other):
return (self.columns == other.columns).all()
def __neq__(self, other):
return not (self == other)
def __repr__(self):
return 'Solution(%s, f=%d, u=%d)' % (
str.join('', map(str, columns)), self.fitness, self.unfitness)
def fitness(solution):
pass
def unfitness(solution):
pass
def construct_solution():
# s = ...
return Solution(s)
def binary_tournament(population):
candidates = [choice(population), choice(population)]
return min(candidates, key=attrgetter('fitness'))
def most_compatible(population, P1):
#P2 = ...
return P2
def matching_selection(population):
P1 = binary_tournament(population)
if P1.unfitness == 0:
P2 = binary_tournament(population)
else:
P2 = most_compatible(population, P1)
return (P1, P2)
def uniform_crossover(P1, P2):
mask = numpy.random.randint(2, size=P1.size)
child = mask * P1.columns + (1 - mask) * P2.columns
return Solution(child)
def mutation(solution, M_s, M_a, epsilon):
return solution
def repair(solution):
return solution
def ranking_replacement(population, solution):
return
def best_solution(solutions):
return solutions[0]
def ga(population_size, nr_iterations):
population = [construct_solution() for k in range(population_size)]
best = best_solution(population)
for t in range(nr_iterations):
P1, P2 = matching_selection(population)
C = uniform_crossover(P1, P2)
C = mutation(C, M_s, M_a, epsilon)
C = repair(C)
ranking_replacement(population, C)
best = best_solution([best_solution, C])
return best
def main():
+ from optparse import OptionParser
+ parser = OptionParser(usage="usage: %prog [options] [input_file]")
+ (options, args) = parser.parse_args()
+
csp = CrewSchedulingProblem(open(args[0]))
- rotations = list(csp.generate_rotations())
+ columns, costs = [], []
+ for rotation in csp.generate_rotations():
+ column = numpy.zeros(len(csp.tasks), dtype='int8')
+ for task in rotation.tasks:
+ column[task] = 1
+ columns.append(column)
+ costs.append(rotation.cost)
+ A = numpy.matrix(columns).transpose()
+ c = numpy.array(costs)
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
59930e0357d9367bb754cf8a35f445dfe4fe16ca
|
import numpy
|
diff --git a/ga.py b/ga.py
index 9a83182..4fa7e78 100644
--- a/ga.py
+++ b/ga.py
@@ -1,96 +1,95 @@
#!/usr/bin/env python
# Genetic algorithm taken from:
# P.C.Chu, J.E.Beasley.
# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
# Journal of Heuristics, 11: 323--357 (1998)
from csp import CrewSchedulingProblem, namedtuple
from random import choice
-from numpy import array, random, equal
-from numpy import random
+import numpy
from operator import attrgetter
range = xrange
class Solution:
__slots__ = ['columns', 'fitness', 'unfitness']
def __init__(self, columns):
- self.columns = array(columns).astype('int8')
+ self.columns = numpy.array(columns).astype('int8')
self.fitness = fitness(self.columns)
self.unfitness = unfitness(self.columns)
def __eq__(self, other):
return (self.columns == other.columns).all()
def __neq__(self, other):
return not (self == other)
def __repr__(self):
return 'Solution(%s, f=%d, u=%d)' % (
str.join('', map(str, columns)), self.fitness, self.unfitness)
def fitness(solution):
pass
def unfitness(solution):
pass
def construct_solution():
# s = ...
return Solution(s)
def binary_tournament(population):
candidates = [choice(population), choice(population)]
return min(candidates, key=attrgetter('fitness'))
def most_compatible(population, P1):
#P2 = ...
return P2
def matching_selection(population):
P1 = binary_tournament(population)
if P1.unfitness == 0:
P2 = binary_tournament(population)
else:
P2 = most_compatible(population, P1)
return (P1, P2)
def uniform_crossover(P1, P2):
- mask = random.randint(2, size=P1.size)
+ mask = numpy.random.randint(2, size=P1.size)
child = mask * P1.columns + (1 - mask) * P2.columns
return Solution(child)
def mutation(solution, M_s, M_a, epsilon):
return solution
def repair(solution):
return solution
def ranking_replacement(population, solution):
return
def best_solution(solutions):
return solutions[0]
def ga(population_size, nr_iterations):
population = [construct_solution() for k in range(population_size)]
best = best_solution(population)
for t in range(nr_iterations):
P1, P2 = matching_selection(population)
C = uniform_crossover(P1, P2)
C = mutation(C, M_s, M_a, epsilon)
C = repair(C)
ranking_replacement(population, C)
best = best_solution([best_solution, C])
return best
def main():
csp = CrewSchedulingProblem(open(args[0]))
rotations = list(csp.generate_rotations())
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
fde6fa10915e1e73ad8e0de5db6d174c31299858
|
Skeleton of genetic algorithm
|
diff --git a/ga.py b/ga.py
new file mode 100644
index 0000000..9a83182
--- /dev/null
+++ b/ga.py
@@ -0,0 +1,96 @@
+#!/usr/bin/env python
+
+# Genetic algorithm taken from:
+# P.C.Chu, J.E.Beasley.
+# Constraint Handling in Genetic Algorithms: The Set Partitioning Problem.
+# Journal of Heuristics, 11: 323--357 (1998)
+
+from csp import CrewSchedulingProblem, namedtuple
+from random import choice
+from numpy import array, random, equal
+from numpy import random
+from operator import attrgetter
+range = xrange
+
+class Solution:
+ __slots__ = ['columns', 'fitness', 'unfitness']
+ def __init__(self, columns):
+ self.columns = array(columns).astype('int8')
+ self.fitness = fitness(self.columns)
+ self.unfitness = unfitness(self.columns)
+ def __eq__(self, other):
+ return (self.columns == other.columns).all()
+ def __neq__(self, other):
+ return not (self == other)
+ def __repr__(self):
+ return 'Solution(%s, f=%d, u=%d)' % (
+ str.join('', map(str, columns)), self.fitness, self.unfitness)
+
+def fitness(solution):
+ pass
+def unfitness(solution):
+ pass
+
+def construct_solution():
+ # s = ...
+ return Solution(s)
+
+
+def binary_tournament(population):
+ candidates = [choice(population), choice(population)]
+ return min(candidates, key=attrgetter('fitness'))
+
+def most_compatible(population, P1):
+ #P2 = ...
+ return P2
+
+def matching_selection(population):
+ P1 = binary_tournament(population)
+ if P1.unfitness == 0:
+ P2 = binary_tournament(population)
+ else:
+ P2 = most_compatible(population, P1)
+ return (P1, P2)
+
+def uniform_crossover(P1, P2):
+ mask = random.randint(2, size=P1.size)
+ child = mask * P1.columns + (1 - mask) * P2.columns
+ return Solution(child)
+
+def mutation(solution, M_s, M_a, epsilon):
+ return solution
+
+def repair(solution):
+ return solution
+
+def ranking_replacement(population, solution):
+ return
+
+def best_solution(solutions):
+ return solutions[0]
+
+
+
+def ga(population_size, nr_iterations):
+ population = [construct_solution() for k in range(population_size)]
+ best = best_solution(population)
+ for t in range(nr_iterations):
+ P1, P2 = matching_selection(population)
+ C = uniform_crossover(P1, P2)
+ C = mutation(C, M_s, M_a, epsilon)
+ C = repair(C)
+ ranking_replacement(population, C)
+ best = best_solution([best_solution, C])
+ return best
+
+
+
+
+
+def main():
+ csp = CrewSchedulingProblem(open(args[0]))
+ rotations = list(csp.generate_rotations())
+
+if __name__ == '__main__':
+ main()
+
|
rbonvall/grasp-crew-scheduling
|
598c1aea8c361617b0cd0f2415b65603330d89aa
|
Set debugging output from command line
|
diff --git a/grasp.py b/grasp.py
index 35cfeea..8e0028c 100755
--- a/grasp.py
+++ b/grasp.py
@@ -1,99 +1,106 @@
#!/usr/bin/env python
from csp import CrewSchedulingProblem, namedtuple
from random import choice, random
from functools import partial
from operator import attrgetter
from sys import stdout
range = xrange
Candidate = namedtuple('Candidate', 'rotation, greedy_cost')
def DEBUG_RCL(candidates, rcl, selected_candidate, stream=stdout):
min_cost = candidates[0].greedy_cost
max_cost = candidates[-1].greedy_cost
def c_repr(c):
r = c.rotation
s = '%s:%d:%d' % (str(r.tasks), r.cost, c.greedy_cost)
bold = 1 if c == selected_candidate else 0
color = 31 if c.greedy_cost == max_cost else None
if c in rcl:
color = 32 if c.greedy_cost == min_cost else 36
if color:
return '\033[%d;49;%dm%s\033[0m' % (bold, color, s)
return s
data = (len(candidates), len(rcl), min_cost, max_cost)
stream.write('#candidate rotations: %d, #rcl: %d, cost range: [%d, %d]\n' % data)
stream.write(' '.join(c_repr(c) for c in candidates))
stream.write('\n')
def DEBUG_SOLUTION(rotations, stream=stdout):
cost = sum(r.cost for r in rotations)
nr_rotations = len(rotations)
stream.write('SOLUTION FOUND cost:%d, nr_rotations: %d\n' %
(cost, nr_rotations))
stream.write(' '.join(str(r.tasks) for r in rotations))
stream.write('\n')
def rotation_cost(r, per_task_bonification=0, perturbation_radius=0):
"""Cost of adding a rotation to a solution"""
return (-per_task_bonification * len(r.tasks) +
perturbation_radius * random() +
r.cost)
def construct_solution(rotations, csp, greedy_cost, alpha):
candidates = sorted((Candidate(r, greedy_cost(r)) for r in rotations),
key=attrgetter('greedy_cost'))
solution = []
while sum(len(r.tasks) for r in solution) < len(csp.tasks):
if not candidates:
return None
min_cost = candidates[0].greedy_cost
max_cost = candidates[-1].greedy_cost
threshold = min_cost + alpha * (max_cost - min_cost)
rcl = [c for c in candidates if c.greedy_cost <= threshold]
selected_candidate = choice(rcl)
solution.append(selected_candidate.rotation)
DEBUG_RCL(candidates, rcl, selected_candidate)
# reevaluate candidates
candidates = [c for c in candidates
if not (c.rotation.tasks & selected_candidate.rotation.tasks)]
DEBUG_SOLUTION(solution)
return solution
def local_search(solution):
return solution
def grasp(rotations, csp, alpha, greedy_cost, max_iterations=1):
best_solution = None
for i in range(max_iterations):
solution = construct_solution(rotations, csp, greedy_cost, alpha)
solution = local_search(solution)
best_solution = solution
break
return best_solution
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
parser.add_option('-a', '--alpha', type='float', default=0.3, metavar='NUM', help='Alpha parameter for RCL construction')
parser.add_option('-b', '--ptb', type='float', default=300, metavar='NUM', help='Per task bonification in greedy function')
parser.add_option('-p', '--pertr', type='float', default=0, metavar='NUM', help='Cost perturbation radius in greedy function')
+ parser.add_option('--debug-greedy', action='store_true', help='Print debugging data for construction stage')
+ parser.add_option('--debug-search', action='store_true', help='Print debugging data for search stage')
(options, args) = parser.parse_args()
if not args:
args = ['orlib/csp50.txt']
+ if not options.debug_greedy:
+ global DEBUG_SOLUTION, DEBUG_RCL
+ DEBUG_SOLUTION = lambda *args: None
+ DEBUG_RCL = lambda *args: None
+
csp = CrewSchedulingProblem(open(args[0]))
rotations = list(csp.generate_rotations())
greedy_cost = partial(rotation_cost, per_task_bonification=options.ptb, perturbation_radius=options.pertr)
solution = grasp(rotations, csp, options.alpha, greedy_cost)
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
4d8174f5eaed24e2cc7e949d12dfd6e626ee337e
|
Transparent background for debugging output
|
diff --git a/grasp.py b/grasp.py
index 76b0846..35cfeea 100755
--- a/grasp.py
+++ b/grasp.py
@@ -1,99 +1,99 @@
#!/usr/bin/env python
from csp import CrewSchedulingProblem, namedtuple
from random import choice, random
from functools import partial
from operator import attrgetter
from sys import stdout
range = xrange
Candidate = namedtuple('Candidate', 'rotation, greedy_cost')
def DEBUG_RCL(candidates, rcl, selected_candidate, stream=stdout):
min_cost = candidates[0].greedy_cost
max_cost = candidates[-1].greedy_cost
def c_repr(c):
r = c.rotation
s = '%s:%d:%d' % (str(r.tasks), r.cost, c.greedy_cost)
bold = 1 if c == selected_candidate else 0
color = 31 if c.greedy_cost == max_cost else None
if c in rcl:
color = 32 if c.greedy_cost == min_cost else 36
if color:
- return '\033[%d;40;%dm%s\033[0m' % (bold, color, s)
+ return '\033[%d;49;%dm%s\033[0m' % (bold, color, s)
return s
data = (len(candidates), len(rcl), min_cost, max_cost)
stream.write('#candidate rotations: %d, #rcl: %d, cost range: [%d, %d]\n' % data)
stream.write(' '.join(c_repr(c) for c in candidates))
stream.write('\n')
def DEBUG_SOLUTION(rotations, stream=stdout):
cost = sum(r.cost for r in rotations)
nr_rotations = len(rotations)
stream.write('SOLUTION FOUND cost:%d, nr_rotations: %d\n' %
(cost, nr_rotations))
stream.write(' '.join(str(r.tasks) for r in rotations))
stream.write('\n')
def rotation_cost(r, per_task_bonification=0, perturbation_radius=0):
"""Cost of adding a rotation to a solution"""
return (-per_task_bonification * len(r.tasks) +
perturbation_radius * random() +
r.cost)
def construct_solution(rotations, csp, greedy_cost, alpha):
candidates = sorted((Candidate(r, greedy_cost(r)) for r in rotations),
key=attrgetter('greedy_cost'))
solution = []
while sum(len(r.tasks) for r in solution) < len(csp.tasks):
if not candidates:
return None
min_cost = candidates[0].greedy_cost
max_cost = candidates[-1].greedy_cost
threshold = min_cost + alpha * (max_cost - min_cost)
rcl = [c for c in candidates if c.greedy_cost <= threshold]
selected_candidate = choice(rcl)
solution.append(selected_candidate.rotation)
DEBUG_RCL(candidates, rcl, selected_candidate)
# reevaluate candidates
candidates = [c for c in candidates
if not (c.rotation.tasks & selected_candidate.rotation.tasks)]
DEBUG_SOLUTION(solution)
return solution
def local_search(solution):
return solution
def grasp(rotations, csp, alpha, greedy_cost, max_iterations=1):
best_solution = None
for i in range(max_iterations):
solution = construct_solution(rotations, csp, greedy_cost, alpha)
solution = local_search(solution)
best_solution = solution
break
return best_solution
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
parser.add_option('-a', '--alpha', type='float', default=0.3, metavar='NUM', help='Alpha parameter for RCL construction')
parser.add_option('-b', '--ptb', type='float', default=300, metavar='NUM', help='Per task bonification in greedy function')
parser.add_option('-p', '--pertr', type='float', default=0, metavar='NUM', help='Cost perturbation radius in greedy function')
(options, args) = parser.parse_args()
if not args:
args = ['orlib/csp50.txt']
csp = CrewSchedulingProblem(open(args[0]))
rotations = list(csp.generate_rotations())
greedy_cost = partial(rotation_cost, per_task_bonification=options.ptb, perturbation_radius=options.pertr)
solution = grasp(rotations, csp, options.alpha, greedy_cost)
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
caa6aa78c63629c903229ded151e985b4beda1bf
|
Remove unused DEBUG function
|
diff --git a/grasp.py b/grasp.py
index 1eec7df..76b0846 100755
--- a/grasp.py
+++ b/grasp.py
@@ -1,101 +1,99 @@
#!/usr/bin/env python
from csp import CrewSchedulingProblem, namedtuple
from random import choice, random
from functools import partial
from operator import attrgetter
from sys import stdout
range = xrange
Candidate = namedtuple('Candidate', 'rotation, greedy_cost')
-def DEBUG(s): print s
-
def DEBUG_RCL(candidates, rcl, selected_candidate, stream=stdout):
min_cost = candidates[0].greedy_cost
max_cost = candidates[-1].greedy_cost
def c_repr(c):
r = c.rotation
s = '%s:%d:%d' % (str(r.tasks), r.cost, c.greedy_cost)
bold = 1 if c == selected_candidate else 0
color = 31 if c.greedy_cost == max_cost else None
if c in rcl:
color = 32 if c.greedy_cost == min_cost else 36
if color:
return '\033[%d;40;%dm%s\033[0m' % (bold, color, s)
return s
data = (len(candidates), len(rcl), min_cost, max_cost)
stream.write('#candidate rotations: %d, #rcl: %d, cost range: [%d, %d]\n' % data)
stream.write(' '.join(c_repr(c) for c in candidates))
stream.write('\n')
def DEBUG_SOLUTION(rotations, stream=stdout):
cost = sum(r.cost for r in rotations)
nr_rotations = len(rotations)
stream.write('SOLUTION FOUND cost:%d, nr_rotations: %d\n' %
(cost, nr_rotations))
stream.write(' '.join(str(r.tasks) for r in rotations))
stream.write('\n')
def rotation_cost(r, per_task_bonification=0, perturbation_radius=0):
"""Cost of adding a rotation to a solution"""
return (-per_task_bonification * len(r.tasks) +
perturbation_radius * random() +
r.cost)
def construct_solution(rotations, csp, greedy_cost, alpha):
candidates = sorted((Candidate(r, greedy_cost(r)) for r in rotations),
key=attrgetter('greedy_cost'))
solution = []
while sum(len(r.tasks) for r in solution) < len(csp.tasks):
if not candidates:
return None
min_cost = candidates[0].greedy_cost
max_cost = candidates[-1].greedy_cost
threshold = min_cost + alpha * (max_cost - min_cost)
rcl = [c for c in candidates if c.greedy_cost <= threshold]
selected_candidate = choice(rcl)
solution.append(selected_candidate.rotation)
DEBUG_RCL(candidates, rcl, selected_candidate)
# reevaluate candidates
candidates = [c for c in candidates
if not (c.rotation.tasks & selected_candidate.rotation.tasks)]
DEBUG_SOLUTION(solution)
return solution
def local_search(solution):
return solution
def grasp(rotations, csp, alpha, greedy_cost, max_iterations=1):
best_solution = None
for i in range(max_iterations):
solution = construct_solution(rotations, csp, greedy_cost, alpha)
solution = local_search(solution)
best_solution = solution
break
return best_solution
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
parser.add_option('-a', '--alpha', type='float', default=0.3, metavar='NUM', help='Alpha parameter for RCL construction')
parser.add_option('-b', '--ptb', type='float', default=300, metavar='NUM', help='Per task bonification in greedy function')
parser.add_option('-p', '--pertr', type='float', default=0, metavar='NUM', help='Cost perturbation radius in greedy function')
(options, args) = parser.parse_args()
if not args:
args = ['orlib/csp50.txt']
csp = CrewSchedulingProblem(open(args[0]))
rotations = list(csp.generate_rotations())
greedy_cost = partial(rotation_cost, per_task_bonification=options.ptb, perturbation_radius=options.pertr)
solution = grasp(rotations, csp, options.alpha, greedy_cost)
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
feb97375f5450a7985a2b5867f08dce56262a62a
|
Moved end condition of construction stage
|
diff --git a/grasp.py b/grasp.py
index b53d1ce..1eec7df 100755
--- a/grasp.py
+++ b/grasp.py
@@ -1,103 +1,101 @@
#!/usr/bin/env python
from csp import CrewSchedulingProblem, namedtuple
from random import choice, random
from functools import partial
from operator import attrgetter
from sys import stdout
range = xrange
Candidate = namedtuple('Candidate', 'rotation, greedy_cost')
def DEBUG(s): print s
def DEBUG_RCL(candidates, rcl, selected_candidate, stream=stdout):
min_cost = candidates[0].greedy_cost
max_cost = candidates[-1].greedy_cost
def c_repr(c):
r = c.rotation
s = '%s:%d:%d' % (str(r.tasks), r.cost, c.greedy_cost)
bold = 1 if c == selected_candidate else 0
color = 31 if c.greedy_cost == max_cost else None
if c in rcl:
color = 32 if c.greedy_cost == min_cost else 36
if color:
return '\033[%d;40;%dm%s\033[0m' % (bold, color, s)
return s
data = (len(candidates), len(rcl), min_cost, max_cost)
stream.write('#candidate rotations: %d, #rcl: %d, cost range: [%d, %d]\n' % data)
stream.write(' '.join(c_repr(c) for c in candidates))
stream.write('\n')
def DEBUG_SOLUTION(rotations, stream=stdout):
cost = sum(r.cost for r in rotations)
nr_rotations = len(rotations)
stream.write('SOLUTION FOUND cost:%d, nr_rotations: %d\n' %
(cost, nr_rotations))
stream.write(' '.join(str(r.tasks) for r in rotations))
stream.write('\n')
def rotation_cost(r, per_task_bonification=0, perturbation_radius=0):
"""Cost of adding a rotation to a solution"""
return (-per_task_bonification * len(r.tasks) +
perturbation_radius * random() +
r.cost)
def construct_solution(rotations, csp, greedy_cost, alpha):
candidates = sorted((Candidate(r, greedy_cost(r)) for r in rotations),
key=attrgetter('greedy_cost'))
solution = []
- while True:
+ while sum(len(r.tasks) for r in solution) < len(csp.tasks):
+ if not candidates:
+ return None
+
min_cost = candidates[0].greedy_cost
max_cost = candidates[-1].greedy_cost
threshold = min_cost + alpha * (max_cost - min_cost)
rcl = [c for c in candidates if c.greedy_cost <= threshold]
selected_candidate = choice(rcl)
solution.append(selected_candidate.rotation)
DEBUG_RCL(candidates, rcl, selected_candidate)
# reevaluate candidates
candidates = [c for c in candidates
if not (c.rotation.tasks & selected_candidate.rotation.tasks)]
- if sum(len(r.tasks) for r in solution) == len(csp.tasks):
- DEBUG_SOLUTION(solution)
- break
- elif not candidates:
- DEBUG('NOT A FEASIBLE SOLUTION')
- return None
+ DEBUG_SOLUTION(solution)
return solution
def local_search(solution):
return solution
def grasp(rotations, csp, alpha, greedy_cost, max_iterations=1):
best_solution = None
for i in range(max_iterations):
solution = construct_solution(rotations, csp, greedy_cost, alpha)
solution = local_search(solution)
best_solution = solution
break
return best_solution
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
parser.add_option('-a', '--alpha', type='float', default=0.3, metavar='NUM', help='Alpha parameter for RCL construction')
parser.add_option('-b', '--ptb', type='float', default=300, metavar='NUM', help='Per task bonification in greedy function')
parser.add_option('-p', '--pertr', type='float', default=0, metavar='NUM', help='Cost perturbation radius in greedy function')
(options, args) = parser.parse_args()
if not args:
args = ['orlib/csp50.txt']
csp = CrewSchedulingProblem(open(args[0]))
rotations = list(csp.generate_rotations())
greedy_cost = partial(rotation_cost, per_task_bonification=options.ptb, perturbation_radius=options.pertr)
solution = grasp(rotations, csp, options.alpha, greedy_cost)
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
3762fae0e5a1e24f4514144883a4be44030167a6
|
Refactor to compute all greedy costs at beginning
|
diff --git a/grasp.py b/grasp.py
index 8614d4a..b53d1ce 100755
--- a/grasp.py
+++ b/grasp.py
@@ -1,97 +1,103 @@
#!/usr/bin/env python
-from csp import CrewSchedulingProblem
+from csp import CrewSchedulingProblem, namedtuple
from random import choice, random
from functools import partial
+from operator import attrgetter
from sys import stdout
range = xrange
+Candidate = namedtuple('Candidate', 'rotation, greedy_cost')
+
def DEBUG(s): print s
-def DEBUG_RCL(rotations, rcl, selected_rotation,
- min_cost, max_cost, greedy_cost, stream=stdout):
- data = (len(rotations), len(rcl), min_cost, max_cost)
- def r_repr(r):
- s = '%s:%d:%d' % (str(r.tasks), r.cost, greedy_cost(r))
- bold = 1 if r == selected_rotation else 0
- color = 31 if greedy_cost(r) == max_cost else None
- if r in rcl:
- color = 32 if greedy_cost(r) == min_cost else 36
+def DEBUG_RCL(candidates, rcl, selected_candidate, stream=stdout):
+ min_cost = candidates[0].greedy_cost
+ max_cost = candidates[-1].greedy_cost
+ def c_repr(c):
+ r = c.rotation
+ s = '%s:%d:%d' % (str(r.tasks), r.cost, c.greedy_cost)
+ bold = 1 if c == selected_candidate else 0
+ color = 31 if c.greedy_cost == max_cost else None
+ if c in rcl:
+ color = 32 if c.greedy_cost == min_cost else 36
if color:
return '\033[%d;40;%dm%s\033[0m' % (bold, color, s)
return s
- stream.write('#rotations: %d, #rcl: %d, cost range: [%d, %d]\n' % data)
- stream.write(' '.join(r_repr(r) for r in rotations))
+ data = (len(candidates), len(rcl), min_cost, max_cost)
+ stream.write('#candidate rotations: %d, #rcl: %d, cost range: [%d, %d]\n' % data)
+ stream.write(' '.join(c_repr(c) for c in candidates))
stream.write('\n')
def DEBUG_SOLUTION(rotations, stream=stdout):
cost = sum(r.cost for r in rotations)
nr_rotations = len(rotations)
stream.write('SOLUTION FOUND cost:%d, nr_rotations: %d\n' %
(cost, nr_rotations))
stream.write(' '.join(str(r.tasks) for r in rotations))
stream.write('\n')
def rotation_cost(r, per_task_bonification=0, perturbation_radius=0):
"""Cost of adding a rotation to a solution"""
return (-per_task_bonification * len(r.tasks) +
perturbation_radius * random() +
r.cost)
def construct_solution(rotations, csp, greedy_cost, alpha):
- rotations = sorted(rotations, key=greedy_cost)
+ candidates = sorted((Candidate(r, greedy_cost(r)) for r in rotations),
+ key=attrgetter('greedy_cost'))
solution = []
while True:
- min_cost = greedy_cost(rotations[0])
- max_cost = greedy_cost(rotations[-1])
+ min_cost = candidates[0].greedy_cost
+ max_cost = candidates[-1].greedy_cost
threshold = min_cost + alpha * (max_cost - min_cost)
- rcl = [r for r in rotations if greedy_cost(r) <= threshold]
- selected_rotation = choice(rcl)
- solution.append(selected_rotation)
+ rcl = [c for c in candidates if c.greedy_cost <= threshold]
+ selected_candidate = choice(rcl)
+ solution.append(selected_candidate.rotation)
- DEBUG_RCL(rotations, rcl, selected_rotation, min_cost, max_cost, greedy_cost)
+ DEBUG_RCL(candidates, rcl, selected_candidate)
# reevaluate candidates
- rotations = [r for r in rotations
- if not (r.tasks & selected_rotation.tasks)]
+ candidates = [c for c in candidates
+ if not (c.rotation.tasks & selected_candidate.rotation.tasks)]
if sum(len(r.tasks) for r in solution) == len(csp.tasks):
DEBUG_SOLUTION(solution)
break
- elif not rotations:
+ elif not candidates:
DEBUG('NOT A FEASIBLE SOLUTION')
return None
return solution
def local_search(solution):
return solution
def grasp(rotations, csp, alpha, greedy_cost, max_iterations=1):
best_solution = None
for i in range(max_iterations):
solution = construct_solution(rotations, csp, greedy_cost, alpha)
solution = local_search(solution)
best_solution = solution
break
return best_solution
def main():
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] [input_file]")
parser.add_option('-a', '--alpha', type='float', default=0.3, metavar='NUM', help='Alpha parameter for RCL construction')
parser.add_option('-b', '--ptb', type='float', default=300, metavar='NUM', help='Per task bonification in greedy function')
parser.add_option('-p', '--pertr', type='float', default=0, metavar='NUM', help='Cost perturbation radius in greedy function')
(options, args) = parser.parse_args()
if not args:
args = ['orlib/csp50.txt']
csp = CrewSchedulingProblem(open(args[0]))
rotations = list(csp.generate_rotations())
greedy_cost = partial(rotation_cost, per_task_bonification=options.ptb, perturbation_radius=options.pertr)
solution = grasp(rotations, csp, options.alpha, greedy_cost)
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
e67cb14289d98a3519c843d21d09b681428212b3
|
Command line arguments for parameter setting
|
diff --git a/grasp.py b/grasp.py
index 4e97e94..8614d4a 100755
--- a/grasp.py
+++ b/grasp.py
@@ -1,94 +1,97 @@
#!/usr/bin/env python
from csp import CrewSchedulingProblem
from random import choice, random
from functools import partial
from sys import stdout
range = xrange
def DEBUG(s): print s
def DEBUG_RCL(rotations, rcl, selected_rotation,
min_cost, max_cost, greedy_cost, stream=stdout):
data = (len(rotations), len(rcl), min_cost, max_cost)
def r_repr(r):
s = '%s:%d:%d' % (str(r.tasks), r.cost, greedy_cost(r))
bold = 1 if r == selected_rotation else 0
color = 31 if greedy_cost(r) == max_cost else None
if r in rcl:
color = 32 if greedy_cost(r) == min_cost else 36
if color:
return '\033[%d;40;%dm%s\033[0m' % (bold, color, s)
return s
stream.write('#rotations: %d, #rcl: %d, cost range: [%d, %d]\n' % data)
stream.write(' '.join(r_repr(r) for r in rotations))
stream.write('\n')
def DEBUG_SOLUTION(rotations, stream=stdout):
cost = sum(r.cost for r in rotations)
nr_rotations = len(rotations)
stream.write('SOLUTION FOUND cost:%d, nr_rotations: %d\n' %
(cost, nr_rotations))
stream.write(' '.join(str(r.tasks) for r in rotations))
stream.write('\n')
def rotation_cost(r, per_task_bonification=0, perturbation_radius=0):
"""Cost of adding a rotation to a solution"""
return (-per_task_bonification * len(r.tasks) +
perturbation_radius * random() +
r.cost)
def construct_solution(rotations, csp, greedy_cost, alpha):
rotations = sorted(rotations, key=greedy_cost)
solution = []
while True:
min_cost = greedy_cost(rotations[0])
max_cost = greedy_cost(rotations[-1])
threshold = min_cost + alpha * (max_cost - min_cost)
rcl = [r for r in rotations if greedy_cost(r) <= threshold]
selected_rotation = choice(rcl)
solution.append(selected_rotation)
DEBUG_RCL(rotations, rcl, selected_rotation, min_cost, max_cost, greedy_cost)
# reevaluate candidates
rotations = [r for r in rotations
if not (r.tasks & selected_rotation.tasks)]
if sum(len(r.tasks) for r in solution) == len(csp.tasks):
DEBUG_SOLUTION(solution)
break
elif not rotations:
DEBUG('NOT A FEASIBLE SOLUTION')
return None
return solution
def local_search(solution):
return solution
def grasp(rotations, csp, alpha, greedy_cost, max_iterations=1):
best_solution = None
for i in range(max_iterations):
solution = construct_solution(rotations, csp, greedy_cost, alpha)
solution = local_search(solution)
best_solution = solution
break
return best_solution
def main():
- import sys
- try:
- filename = sys.argv[1]
- except IndexError:
- filename = 'orlib/csp50.txt'
- csp = CrewSchedulingProblem(open(filename))
+ from optparse import OptionParser
+ parser = OptionParser(usage="usage: %prog [options] [input_file]")
+ parser.add_option('-a', '--alpha', type='float', default=0.3, metavar='NUM', help='Alpha parameter for RCL construction')
+ parser.add_option('-b', '--ptb', type='float', default=300, metavar='NUM', help='Per task bonification in greedy function')
+ parser.add_option('-p', '--pertr', type='float', default=0, metavar='NUM', help='Cost perturbation radius in greedy function')
+ (options, args) = parser.parse_args()
+ if not args:
+ args = ['orlib/csp50.txt']
+
+ csp = CrewSchedulingProblem(open(args[0]))
rotations = list(csp.generate_rotations())
- alpha = 0.3
- greedy_cost = partial(rotation_cost, per_task_bonification=300, perturbation_radius=0)
- solution = grasp(rotations, csp, alpha, greedy_cost)
+ greedy_cost = partial(rotation_cost, per_task_bonification=options.ptb, perturbation_radius=options.pertr)
+ solution = grasp(rotations, csp, options.alpha, greedy_cost)
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
3d3da284370057aaea8cb36c4608e9c777c50fdf
|
rm commented fixed-size rcl construction
|
diff --git a/grasp.py b/grasp.py
index d22b837..4e97e94 100755
--- a/grasp.py
+++ b/grasp.py
@@ -1,95 +1,94 @@
#!/usr/bin/env python
from csp import CrewSchedulingProblem
from random import choice, random
from functools import partial
from sys import stdout
range = xrange
def DEBUG(s): print s
def DEBUG_RCL(rotations, rcl, selected_rotation,
min_cost, max_cost, greedy_cost, stream=stdout):
data = (len(rotations), len(rcl), min_cost, max_cost)
def r_repr(r):
s = '%s:%d:%d' % (str(r.tasks), r.cost, greedy_cost(r))
bold = 1 if r == selected_rotation else 0
color = 31 if greedy_cost(r) == max_cost else None
if r in rcl:
color = 32 if greedy_cost(r) == min_cost else 36
if color:
return '\033[%d;40;%dm%s\033[0m' % (bold, color, s)
return s
stream.write('#rotations: %d, #rcl: %d, cost range: [%d, %d]\n' % data)
stream.write(' '.join(r_repr(r) for r in rotations))
stream.write('\n')
def DEBUG_SOLUTION(rotations, stream=stdout):
cost = sum(r.cost for r in rotations)
nr_rotations = len(rotations)
stream.write('SOLUTION FOUND cost:%d, nr_rotations: %d\n' %
(cost, nr_rotations))
stream.write(' '.join(str(r.tasks) for r in rotations))
stream.write('\n')
def rotation_cost(r, per_task_bonification=0, perturbation_radius=0):
"""Cost of adding a rotation to a solution"""
return (-per_task_bonification * len(r.tasks) +
perturbation_radius * random() +
r.cost)
def construct_solution(rotations, csp, greedy_cost, alpha):
rotations = sorted(rotations, key=greedy_cost)
solution = []
while True:
min_cost = greedy_cost(rotations[0])
max_cost = greedy_cost(rotations[-1])
threshold = min_cost + alpha * (max_cost - min_cost)
- #rcl = sorted(rotations, key=greedy_cost)[:10]
rcl = [r for r in rotations if greedy_cost(r) <= threshold]
selected_rotation = choice(rcl)
solution.append(selected_rotation)
DEBUG_RCL(rotations, rcl, selected_rotation, min_cost, max_cost, greedy_cost)
# reevaluate candidates
rotations = [r for r in rotations
if not (r.tasks & selected_rotation.tasks)]
if sum(len(r.tasks) for r in solution) == len(csp.tasks):
DEBUG_SOLUTION(solution)
break
elif not rotations:
DEBUG('NOT A FEASIBLE SOLUTION')
return None
return solution
def local_search(solution):
return solution
def grasp(rotations, csp, alpha, greedy_cost, max_iterations=1):
best_solution = None
for i in range(max_iterations):
solution = construct_solution(rotations, csp, greedy_cost, alpha)
solution = local_search(solution)
best_solution = solution
break
return best_solution
def main():
import sys
try:
filename = sys.argv[1]
except IndexError:
filename = 'orlib/csp50.txt'
csp = CrewSchedulingProblem(open(filename))
rotations = list(csp.generate_rotations())
alpha = 0.3
greedy_cost = partial(rotation_cost, per_task_bonification=300, perturbation_radius=0)
solution = grasp(rotations, csp, alpha, greedy_cost)
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
3658e9e38b1d8f12a782c6125325a2429256385c
|
alpha and greedy_cost set outside grasp
|
diff --git a/grasp.py b/grasp.py
index 2347fe4..d22b837 100755
--- a/grasp.py
+++ b/grasp.py
@@ -1,95 +1,95 @@
#!/usr/bin/env python
from csp import CrewSchedulingProblem
from random import choice, random
from functools import partial
from sys import stdout
range = xrange
def DEBUG(s): print s
def DEBUG_RCL(rotations, rcl, selected_rotation,
min_cost, max_cost, greedy_cost, stream=stdout):
data = (len(rotations), len(rcl), min_cost, max_cost)
def r_repr(r):
s = '%s:%d:%d' % (str(r.tasks), r.cost, greedy_cost(r))
bold = 1 if r == selected_rotation else 0
color = 31 if greedy_cost(r) == max_cost else None
if r in rcl:
color = 32 if greedy_cost(r) == min_cost else 36
if color:
return '\033[%d;40;%dm%s\033[0m' % (bold, color, s)
return s
stream.write('#rotations: %d, #rcl: %d, cost range: [%d, %d]\n' % data)
stream.write(' '.join(r_repr(r) for r in rotations))
stream.write('\n')
def DEBUG_SOLUTION(rotations, stream=stdout):
cost = sum(r.cost for r in rotations)
nr_rotations = len(rotations)
stream.write('SOLUTION FOUND cost:%d, nr_rotations: %d\n' %
(cost, nr_rotations))
stream.write(' '.join(str(r.tasks) for r in rotations))
stream.write('\n')
def rotation_cost(r, per_task_bonification=0, perturbation_radius=0):
"""Cost of adding a rotation to a solution"""
return (-per_task_bonification * len(r.tasks) +
perturbation_radius * random() +
r.cost)
-def construct_solution(rotations, csp, greedy_cost):
+def construct_solution(rotations, csp, greedy_cost, alpha):
rotations = sorted(rotations, key=greedy_cost)
solution = []
- alpha = 0.3
while True:
min_cost = greedy_cost(rotations[0])
max_cost = greedy_cost(rotations[-1])
threshold = min_cost + alpha * (max_cost - min_cost)
#rcl = sorted(rotations, key=greedy_cost)[:10]
rcl = [r for r in rotations if greedy_cost(r) <= threshold]
selected_rotation = choice(rcl)
solution.append(selected_rotation)
DEBUG_RCL(rotations, rcl, selected_rotation, min_cost, max_cost, greedy_cost)
# reevaluate candidates
rotations = [r for r in rotations
if not (r.tasks & selected_rotation.tasks)]
if sum(len(r.tasks) for r in solution) == len(csp.tasks):
DEBUG_SOLUTION(solution)
break
elif not rotations:
DEBUG('NOT A FEASIBLE SOLUTION')
return None
return solution
def local_search(solution):
return solution
-def grasp(rotations, csp, max_iterations=1):
- greedy_cost = partial(rotation_cost,
- per_task_bonification=300, perturbation_radius=0)
+def grasp(rotations, csp, alpha, greedy_cost, max_iterations=1):
best_solution = None
for i in range(max_iterations):
- solution = construct_solution(rotations, csp, greedy_cost)
+ solution = construct_solution(rotations, csp, greedy_cost, alpha)
solution = local_search(solution)
best_solution = solution
break
return best_solution
def main():
import sys
try:
filename = sys.argv[1]
except IndexError:
filename = 'orlib/csp50.txt'
csp = CrewSchedulingProblem(open(filename))
rotations = list(csp.generate_rotations())
- solution = grasp(rotations, csp)
+
+ alpha = 0.3
+ greedy_cost = partial(rotation_cost, per_task_bonification=300, perturbation_radius=0)
+ solution = grasp(rotations, csp, alpha, greedy_cost)
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
7af31739e6190b8fd1f6ed5c0758fb9951331d5d
|
Solution printing refactored
|
diff --git a/grasp.py b/grasp.py
index c0650c7..2347fe4 100755
--- a/grasp.py
+++ b/grasp.py
@@ -1,87 +1,95 @@
#!/usr/bin/env python
from csp import CrewSchedulingProblem
from random import choice, random
from functools import partial
from sys import stdout
range = xrange
def DEBUG(s): print s
+
def DEBUG_RCL(rotations, rcl, selected_rotation,
min_cost, max_cost, greedy_cost, stream=stdout):
data = (len(rotations), len(rcl), min_cost, max_cost)
def r_repr(r):
s = '%s:%d:%d' % (str(r.tasks), r.cost, greedy_cost(r))
bold = 1 if r == selected_rotation else 0
color = 31 if greedy_cost(r) == max_cost else None
if r in rcl:
color = 32 if greedy_cost(r) == min_cost else 36
if color:
return '\033[%d;40;%dm%s\033[0m' % (bold, color, s)
return s
stream.write('#rotations: %d, #rcl: %d, cost range: [%d, %d]\n' % data)
stream.write(' '.join(r_repr(r) for r in rotations))
stream.write('\n')
+def DEBUG_SOLUTION(rotations, stream=stdout):
+ cost = sum(r.cost for r in rotations)
+ nr_rotations = len(rotations)
+ stream.write('SOLUTION FOUND cost:%d, nr_rotations: %d\n' %
+ (cost, nr_rotations))
+ stream.write(' '.join(str(r.tasks) for r in rotations))
+ stream.write('\n')
+
+
def rotation_cost(r, per_task_bonification=0, perturbation_radius=0):
"""Cost of adding a rotation to a solution"""
return (-per_task_bonification * len(r.tasks) +
perturbation_radius * random() +
r.cost)
def construct_solution(rotations, csp, greedy_cost):
rotations = sorted(rotations, key=greedy_cost)
solution = []
- alpha = 0.8
+ alpha = 0.3
while True:
min_cost = greedy_cost(rotations[0])
max_cost = greedy_cost(rotations[-1])
threshold = min_cost + alpha * (max_cost - min_cost)
#rcl = sorted(rotations, key=greedy_cost)[:10]
rcl = [r for r in rotations if greedy_cost(r) <= threshold]
selected_rotation = choice(rcl)
solution.append(selected_rotation)
DEBUG_RCL(rotations, rcl, selected_rotation, min_cost, max_cost, greedy_cost)
# reevaluate candidates
rotations = [r for r in rotations
if not (r.tasks & selected_rotation.tasks)]
- if sum(map(len, [r.tasks for r in solution])) == len(csp.tasks):
- DEBUG('SOLUTION WITH %d ROTATIONS:' % len(solution))
- for r in solution: print r.tasks,
- print
+ if sum(len(r.tasks) for r in solution) == len(csp.tasks):
+ DEBUG_SOLUTION(solution)
break
- if not rotations:
+ elif not rotations:
DEBUG('NOT A FEASIBLE SOLUTION')
- break
+ return None
return solution
def local_search(solution):
return solution
def grasp(rotations, csp, max_iterations=1):
greedy_cost = partial(rotation_cost,
per_task_bonification=300, perturbation_radius=0)
best_solution = None
for i in range(max_iterations):
solution = construct_solution(rotations, csp, greedy_cost)
solution = local_search(solution)
best_solution = solution
break
return best_solution
def main():
import sys
try:
filename = sys.argv[1]
except IndexError:
filename = 'orlib/csp50.txt'
csp = CrewSchedulingProblem(open(filename))
rotations = list(csp.generate_rotations())
solution = grasp(rotations, csp)
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
ca735a4cf9a0f26faef97ad103eee1e07101f66e
|
chmod +x csp.py grasp.py
|
diff --git a/csp.py b/csp.py
old mode 100644
new mode 100755
diff --git a/grasp.py b/grasp.py
old mode 100644
new mode 100755
|
rbonvall/grasp-crew-scheduling
|
b817a684bea17622e5a37117600823f65031ac27
|
Put writes together in DEBUG_RCL
|
diff --git a/grasp.py b/grasp.py
index 776671e..c0650c7 100644
--- a/grasp.py
+++ b/grasp.py
@@ -1,87 +1,87 @@
#!/usr/bin/env python
from csp import CrewSchedulingProblem
from random import choice, random
from functools import partial
from sys import stdout
range = xrange
def DEBUG(s): print s
def DEBUG_RCL(rotations, rcl, selected_rotation,
min_cost, max_cost, greedy_cost, stream=stdout):
data = (len(rotations), len(rcl), min_cost, max_cost)
- stream.write('#rotations: %d, #rcl: %d, cost range: [%d, %d]\n' % data)
def r_repr(r):
s = '%s:%d:%d' % (str(r.tasks), r.cost, greedy_cost(r))
bold = 1 if r == selected_rotation else 0
color = 31 if greedy_cost(r) == max_cost else None
if r in rcl:
color = 32 if greedy_cost(r) == min_cost else 36
if color:
return '\033[%d;40;%dm%s\033[0m' % (bold, color, s)
return s
+ stream.write('#rotations: %d, #rcl: %d, cost range: [%d, %d]\n' % data)
stream.write(' '.join(r_repr(r) for r in rotations))
stream.write('\n')
def rotation_cost(r, per_task_bonification=0, perturbation_radius=0):
"""Cost of adding a rotation to a solution"""
return (-per_task_bonification * len(r.tasks) +
perturbation_radius * random() +
r.cost)
def construct_solution(rotations, csp, greedy_cost):
rotations = sorted(rotations, key=greedy_cost)
solution = []
alpha = 0.8
while True:
min_cost = greedy_cost(rotations[0])
max_cost = greedy_cost(rotations[-1])
threshold = min_cost + alpha * (max_cost - min_cost)
#rcl = sorted(rotations, key=greedy_cost)[:10]
rcl = [r for r in rotations if greedy_cost(r) <= threshold]
selected_rotation = choice(rcl)
solution.append(selected_rotation)
DEBUG_RCL(rotations, rcl, selected_rotation, min_cost, max_cost, greedy_cost)
# reevaluate candidates
rotations = [r for r in rotations
if not (r.tasks & selected_rotation.tasks)]
if sum(map(len, [r.tasks for r in solution])) == len(csp.tasks):
DEBUG('SOLUTION WITH %d ROTATIONS:' % len(solution))
for r in solution: print r.tasks,
print
break
if not rotations:
DEBUG('NOT A FEASIBLE SOLUTION')
break
return solution
def local_search(solution):
return solution
def grasp(rotations, csp, max_iterations=1):
greedy_cost = partial(rotation_cost,
per_task_bonification=300, perturbation_radius=0)
best_solution = None
for i in range(max_iterations):
solution = construct_solution(rotations, csp, greedy_cost)
solution = local_search(solution)
best_solution = solution
break
return best_solution
def main():
import sys
try:
filename = sys.argv[1]
except IndexError:
filename = 'orlib/csp50.txt'
csp = CrewSchedulingProblem(open(filename))
rotations = list(csp.generate_rotations())
solution = grasp(rotations, csp)
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
2c336b05d20a97e2e553fd4b0ec75ea99f3398ab
|
DEBUG_RCL refactored
|
diff --git a/grasp.py b/grasp.py
index 5ba2226..776671e 100644
--- a/grasp.py
+++ b/grasp.py
@@ -1,87 +1,87 @@
#!/usr/bin/env python
from csp import CrewSchedulingProblem
from random import choice, random
from functools import partial
+from sys import stdout
range = xrange
def DEBUG(s): print s
-def DEBUG_RCL(rotations, rcl, selected_rotation, min_cost, max_cost, greedy_cost):
+def DEBUG_RCL(rotations, rcl, selected_rotation,
+ min_cost, max_cost, greedy_cost, stream=stdout):
data = (len(rotations), len(rcl), min_cost, max_cost)
- DEBUG('#rotations: %d, #rcl: %d, min_cost: %d, max_cost: %d' % data)
- rotation_reprs = []
- for r in rotations:
- r_repr = '%s:%d' % (str(r.tasks), greedy_cost(r))
+ stream.write('#rotations: %d, #rcl: %d, cost range: [%d, %d]\n' % data)
+ def r_repr(r):
+ s = '%s:%d:%d' % (str(r.tasks), r.cost, greedy_cost(r))
+ bold = 1 if r == selected_rotation else 0
+ color = 31 if greedy_cost(r) == max_cost else None
if r in rcl:
- c = int(r == selected_rotation)
- if greedy_cost(r) == min_cost:
- r_repr = '\033[%d;40;32m%s\033[0m' % (c, r_repr)
- else:
- r_repr = '\033[%d;40;36m%s\033[0m' % (c, r_repr)
- if greedy_cost(r) == max_cost:
- r_repr = '\033[0;40;31m%s\033[0m' % r_repr
- rotation_reprs.append(r_repr)
- DEBUG(' '.join(rotation_reprs))
+ color = 32 if greedy_cost(r) == min_cost else 36
+ if color:
+ return '\033[%d;40;%dm%s\033[0m' % (bold, color, s)
+ return s
+ stream.write(' '.join(r_repr(r) for r in rotations))
+ stream.write('\n')
def rotation_cost(r, per_task_bonification=0, perturbation_radius=0):
"""Cost of adding a rotation to a solution"""
return (-per_task_bonification * len(r.tasks) +
perturbation_radius * random() +
r.cost)
def construct_solution(rotations, csp, greedy_cost):
rotations = sorted(rotations, key=greedy_cost)
solution = []
alpha = 0.8
while True:
min_cost = greedy_cost(rotations[0])
max_cost = greedy_cost(rotations[-1])
threshold = min_cost + alpha * (max_cost - min_cost)
#rcl = sorted(rotations, key=greedy_cost)[:10]
rcl = [r for r in rotations if greedy_cost(r) <= threshold]
selected_rotation = choice(rcl)
solution.append(selected_rotation)
DEBUG_RCL(rotations, rcl, selected_rotation, min_cost, max_cost, greedy_cost)
# reevaluate candidates
rotations = [r for r in rotations
if not (r.tasks & selected_rotation.tasks)]
if sum(map(len, [r.tasks for r in solution])) == len(csp.tasks):
DEBUG('SOLUTION WITH %d ROTATIONS:' % len(solution))
for r in solution: print r.tasks,
print
break
if not rotations:
DEBUG('NOT A FEASIBLE SOLUTION')
break
return solution
def local_search(solution):
return solution
def grasp(rotations, csp, max_iterations=1):
greedy_cost = partial(rotation_cost,
per_task_bonification=300, perturbation_radius=0)
best_solution = None
for i in range(max_iterations):
solution = construct_solution(rotations, csp, greedy_cost)
solution = local_search(solution)
best_solution = solution
break
return best_solution
def main():
import sys
try:
filename = sys.argv[1]
except IndexError:
filename = 'orlib/csp50.txt'
csp = CrewSchedulingProblem(open(filename))
rotations = list(csp.generate_rotations())
solution = grasp(rotations, csp)
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
b9d59c92a6faf28b7f30a974dade2694b4b5c8ab
|
Sort available rotations by greedy cost
|
diff --git a/grasp.py b/grasp.py
index 49c79ef..5ba2226 100644
--- a/grasp.py
+++ b/grasp.py
@@ -1,87 +1,87 @@
#!/usr/bin/env python
from csp import CrewSchedulingProblem
from random import choice, random
from functools import partial
range = xrange
def DEBUG(s): print s
def DEBUG_RCL(rotations, rcl, selected_rotation, min_cost, max_cost, greedy_cost):
data = (len(rotations), len(rcl), min_cost, max_cost)
DEBUG('#rotations: %d, #rcl: %d, min_cost: %d, max_cost: %d' % data)
rotation_reprs = []
for r in rotations:
r_repr = '%s:%d' % (str(r.tasks), greedy_cost(r))
if r in rcl:
c = int(r == selected_rotation)
if greedy_cost(r) == min_cost:
r_repr = '\033[%d;40;32m%s\033[0m' % (c, r_repr)
else:
r_repr = '\033[%d;40;36m%s\033[0m' % (c, r_repr)
if greedy_cost(r) == max_cost:
r_repr = '\033[0;40;31m%s\033[0m' % r_repr
rotation_reprs.append(r_repr)
DEBUG(' '.join(rotation_reprs))
def rotation_cost(r, per_task_bonification=0, perturbation_radius=0):
"""Cost of adding a rotation to a solution"""
return (-per_task_bonification * len(r.tasks) +
perturbation_radius * random() +
r.cost)
def construct_solution(rotations, csp, greedy_cost):
- rotations = rotations[:]
+ rotations = sorted(rotations, key=greedy_cost)
solution = []
alpha = 0.8
while True:
- min_cost = greedy_cost(min(rotations, key=greedy_cost))
- max_cost = greedy_cost(max(rotations, key=greedy_cost))
+ min_cost = greedy_cost(rotations[0])
+ max_cost = greedy_cost(rotations[-1])
threshold = min_cost + alpha * (max_cost - min_cost)
#rcl = sorted(rotations, key=greedy_cost)[:10]
rcl = [r for r in rotations if greedy_cost(r) <= threshold]
selected_rotation = choice(rcl)
solution.append(selected_rotation)
DEBUG_RCL(rotations, rcl, selected_rotation, min_cost, max_cost, greedy_cost)
# reevaluate candidates
rotations = [r for r in rotations
if not (r.tasks & selected_rotation.tasks)]
if sum(map(len, [r.tasks for r in solution])) == len(csp.tasks):
DEBUG('SOLUTION WITH %d ROTATIONS:' % len(solution))
for r in solution: print r.tasks,
print
break
if not rotations:
DEBUG('NOT A FEASIBLE SOLUTION')
break
return solution
def local_search(solution):
return solution
def grasp(rotations, csp, max_iterations=1):
greedy_cost = partial(rotation_cost,
per_task_bonification=300, perturbation_radius=0)
best_solution = None
for i in range(max_iterations):
solution = construct_solution(rotations, csp, greedy_cost)
solution = local_search(solution)
best_solution = solution
break
return best_solution
def main():
import sys
try:
filename = sys.argv[1]
except IndexError:
filename = 'orlib/csp50.txt'
csp = CrewSchedulingProblem(open(filename))
rotations = list(csp.generate_rotations())
solution = grasp(rotations, csp)
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
8edcf1096058b0befcc5539518ffcb4dfc6ca9a2
|
Bug fixed in rcl selection (s/</<=/)
|
diff --git a/grasp.py b/grasp.py
index 84de028..49c79ef 100644
--- a/grasp.py
+++ b/grasp.py
@@ -1,87 +1,87 @@
#!/usr/bin/env python
from csp import CrewSchedulingProblem
from random import choice, random
from functools import partial
range = xrange
def DEBUG(s): print s
def DEBUG_RCL(rotations, rcl, selected_rotation, min_cost, max_cost, greedy_cost):
data = (len(rotations), len(rcl), min_cost, max_cost)
DEBUG('#rotations: %d, #rcl: %d, min_cost: %d, max_cost: %d' % data)
rotation_reprs = []
for r in rotations:
r_repr = '%s:%d' % (str(r.tasks), greedy_cost(r))
if r in rcl:
c = int(r == selected_rotation)
if greedy_cost(r) == min_cost:
r_repr = '\033[%d;40;32m%s\033[0m' % (c, r_repr)
else:
r_repr = '\033[%d;40;36m%s\033[0m' % (c, r_repr)
if greedy_cost(r) == max_cost:
r_repr = '\033[0;40;31m%s\033[0m' % r_repr
rotation_reprs.append(r_repr)
DEBUG(' '.join(rotation_reprs))
def rotation_cost(r, per_task_bonification=0, perturbation_radius=0):
"""Cost of adding a rotation to a solution"""
return (-per_task_bonification * len(r.tasks) +
perturbation_radius * random() +
r.cost)
def construct_solution(rotations, csp, greedy_cost):
rotations = rotations[:]
solution = []
alpha = 0.8
while True:
min_cost = greedy_cost(min(rotations, key=greedy_cost))
max_cost = greedy_cost(max(rotations, key=greedy_cost))
threshold = min_cost + alpha * (max_cost - min_cost)
#rcl = sorted(rotations, key=greedy_cost)[:10]
- rcl = [r for r in rotations if greedy_cost(r) < threshold]
+ rcl = [r for r in rotations if greedy_cost(r) <= threshold]
selected_rotation = choice(rcl)
solution.append(selected_rotation)
DEBUG_RCL(rotations, rcl, selected_rotation, min_cost, max_cost, greedy_cost)
# reevaluate candidates
rotations = [r for r in rotations
if not (r.tasks & selected_rotation.tasks)]
if sum(map(len, [r.tasks for r in solution])) == len(csp.tasks):
DEBUG('SOLUTION WITH %d ROTATIONS:' % len(solution))
for r in solution: print r.tasks,
print
break
if not rotations:
DEBUG('NOT A FEASIBLE SOLUTION')
break
return solution
def local_search(solution):
return solution
def grasp(rotations, csp, max_iterations=1):
greedy_cost = partial(rotation_cost,
per_task_bonification=300, perturbation_radius=0)
best_solution = None
for i in range(max_iterations):
solution = construct_solution(rotations, csp, greedy_cost)
solution = local_search(solution)
best_solution = solution
break
return best_solution
def main():
import sys
try:
filename = sys.argv[1]
except IndexError:
filename = 'orlib/csp50.txt'
csp = CrewSchedulingProblem(open(filename))
rotations = list(csp.generate_rotations())
solution = grasp(rotations, csp)
if __name__ == '__main__':
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.