Bad Robots on WebGL based on ThreeJS

Today, a version of the Bad Robots game is released on an experimental WebGL renderer based on the library ThreeJS.
This is the first OpenGL (WebGL) game on the Flame Steel Engine.
You can play it at the link:
http://demensdeum.com/games/BadRobotsGL/

The source code for IOSystem based on ThreeJS is available here:
https://github.com/demensdeum/FlameSteelEngineGameToolkitWeb

Porting SDL C++ Game to HTML5 (Emscripten)

[Translation may be some day]

За последний год я написал простейший движок Flame Steel Engine и набор классов для игровой разработки Flame Steel Engine Game Toolkit. В данной статье я опишу как производил портирование движка и SDL игры Bad Robots на HTML 5, с использованием компилятора Emscripten.

Установка Hello World – Emscripten

Для начала нужно установить Emscripten. Простейшим вариантом оказалось использование скрипта emsdk для Linux. На официальном сайте данный тип установки называется как “Portable Emscripten SDK for Linux and OS X“. Внутри архива есть инструкция по установке с использованием скрипта. Я производил установку в директорию ~/emsdk/emsdk_portable.

После установки emscripten нужно проверить корректность работы компилятора, для этого создаем простейший hello_world.cpp и собираем его в hello_world.html с помощью команд:

source ~/emsdk/emsdk_portable/emsdk_env.sh
emcc hello_world.cpp -o hello_world.html

После компиляции в папке появится hello_world.html и вспомогательные файлы, откройте его в лучшем браузере Firefox, проверьте что все работает корректно.

Портирование кода игры

В javascript нежелательно вызывать бесконечный цикл – это приводит к зависанию браузера. На данный момент корректная стратегия – запрашивать один шаг цикла у браузера с помощью вызова window.requestAnimationFrame(callback)

В Emscripten данное обстоятельство решено с помощью вызова:

emscripten_set_main_loop(em_callback_func func, int fps, int simulate_infinite_loop);

Таким образом, нужно изменить код игры для корректного вызова метода emscripten. Для этого я сделал глобальный метод GLOBAL_fsegt_emscripten_gameLoop, в котором вызываю шаг цикла игрового контроллера. Главный игровой контроллер также вынесен в глобальную видимость:

#ifdef __EMSCRIPTEN__

void GLOBAL_fsegt_emscripten_gameLoop() {

GLOBAL_fsegt_emscripten_gameController->gameLoop();

}
#endif

Также для обработки специфических для Emscripten моментов, нужно использовать макрос __EMSCRIPTEN__.

Ресурсы и оптимизация

Emscripten поддерживает ресурсы и сборку с оптимизацией.

Для добавления изображений, музыки и прочего, положите все файлы в одну папку, например data. Далее в скрипт сборки добавьте:

emcc <файлы для сборки> –use-preload-plugins –preload-file data

Флаг –use-preload-plugins включает красивый прелоадер в углу экрана, –preload-file добавляет указанный ресурс в файл <имя проекта>.data
Код постоянно останавливался с ошибками доступа к ресурсам, пока я не включил оба этих флага. Также стоит заметить что для корректного доступа к ресурсам, желательно запускать игру на https (возможно и http) сервере, или отключить защиту локального доступа к файлам в вашем браузере.

Для включения оптимизации добавьте флаги:

-s TOTAL_MEMORY=67108864 -O3 -ffast-math

TOTAL_MEMORY – оперативная память в байтах(?) необходимая для корректной работы игры. Вы можете использовать флаг для динамического выделения памяти, но тогда часть оптимизаций работать не будет.

Производительность

Код javascript из C++ работает гораздо медленнее, даже со включенными оптимизациями. Поэтому если ваша цель это разработка для HTML5, то приготовьтесь к ручной оптимизации алгоритмов игры, паралелльному тестированию, также к написанию javascript кода вручную в особо узких местах. Для написания javascript кода используется макрос EM_ASM. Во время реализации рейкастера на emscripten, мне удалось добиться повышения fps с 2-4 до 30 с помощью прямого использования методов canvas.drawImage, в обход обертки SDL->Canvas, что почти приравнялось к написанию всего на javascript.

Поддержка SDL

На данный момент почти не работает SDL_TTF, поэтому отрисовка шрифта для Game Score в BadRobots очень проста. SDL_Image, SDL_Mixer работают корректно, в mixer я проверил только проигрывание музыки.

Исходный код Flame Steel Engine, Flame Steel Engine Game Toolkit, игры Bad Robots:

https://github.com/demensdeum/BadRobots
https://github.com/demensdeum/FlameSteelEngine
https://github.com/demensdeum/FlameSteelEngineGameToolkit

Статья на эту тему:

https://hacks.mozilla.org/2012/04/porting-me-my-shadow-to-the-web-c-to-javascriptcanvas-via-emscripten/

Bad Robots – HTML 5 Game

The first game on the Flame Steel Engine.

http://demensdeum.com/games/BadRobots/BadRobots.html

Shoot all the robots on the screen!

Authors:

Robot animation – http://opengameart.org/content/xeon-ultimate-smash-friends
Music – Killers Kevin MacLeod (incompetech.com)

Source code:

https://github.com/demensdeum/BadRobots
https://github.com/demensdeum/FlameSteelEngine
https://github.com/demensdeum/FlameSteelEngineGameToolkit

Beautiful and empty

You get up in the morning, your mom cooks you something to eat, your dad gives you money for Snickers and takes you to school. You go to a good, strict school without bullies. You study excellently – you have several tutors in subjects that you are not predisposed to. There is an honor roll in your school, on which you, along with your grades, should be, ideally, at the very top. Your future is cloudless – every day you are given gifts, candy, cool fashionable clothes. Everything seems fine, but you understand how boring such a life really is. There is no sense of struggle, every step is predetermined, scheduled for several years in advance.

That’s how I feel when I play any Blizzard game. I see a lot of people who can’t play old school games, can’t play something really original, not formulaic (Deadly Premonition or Papers Please) but everyone loves Blizzard games.

I started my acquaintance with their games on PC with Starcraft. After the wild and arcade Command & Conquer, the gameplay seemed very measured, calming to me. The limitation on the number of units, digging into micro-nano operations personally put me to sleep. Then there was a beautiful, but empty clicker game – Diablo 2. Good graphics, generated levels, and zero gameplay, an absolutely meditative and empty pastime. However, my friends were firmly entrenched in Starcraft and Diablo. In the early 2000s, the mind-blowing Warcraft 3 was released. I really liked the single-player company then. However, the multiplayer is very similar to Starcraft and therefore very dull. Then there was no less beautiful, empty Starcraft 2. I played f2p Hearthstone for a while – this game is like a slot machine, at first you win, you start believing in yourself, but then developers come to you with an offer to buy several decks for 500 ₽. Your skill doesn’t decide anything, only the amount of money spent on virtual decks decides.

I recently bought Overwatch, a shooter from Blizzard. I liked the heroine Mei, whose art and cosplay are all over social networks, and as a result, the general wave of advertising in geek communities threw me onto the shore of Overwatch players.

My fears were justified – excellent graphics, different heroes with their own voices, abilities. Not a single crash during the game, everything is at the level of Blizzard. And now, I want to say that the game is again so polished even in the gameplay that it is simply not interesting to play. It really lacks interesting – unexpected moments, risky ideas, the company, as always, took only the best from past years and, having polished it, sent it to conquer the market, not skimping on good promotion.

The only Blizzard game that I really liked is Rock’n’Roll Racing. It does have gameplay, but I suspect that the credit for this goes not to the developer, but to the publisher – Interplay, most likely Interplay helped Blizzard make something truly playable out of the game.

Games Vision #2

Variable heading Games Vision.
I write short reviews of games that I have played recently

wsunhd
SIM
aka Sara is Missing (Android, Monsoon Lab) – ты находишь телефон девушки по имени Сара. Внутри телефона есть встроенный помощник IRIS, она хочет найти свою хозяйку и просит тебя ей в этом помочь. Задача понять что творилось в голове Сары из ее переписки, фоточек и видео, найти где она находится. Игра очень оригинальная и достаточно пугающая. Минус в том что нет локализации на русский и другие языки, нет версии для iOS, хотя очевидно что интерфейс игры копирует продукцию Apple (IRIS – SIRI) Также игра очень короткая.
Rating 7/10

unnamed
The End of The World
(Android, Sean Wenham) – игра про расставание – парня бросила девушка, теперь он бродит в поисках вина и спит под мостом, вспоминая моменты когда они были вместе. Умилительные моменты воспоминаний, грустная музыка, переход в белое, в принципе отличная игра для женской аудитории и некоторых пацанов. Мне не понравилась бюджетная графика с претензией на оригинальность (напоминает Another World Эрика Шайи), нулевой геймплей, попытки выбить из игрока слезки, предсказуемость, десять минут прохождения. Любителям ванили рекомендую.
Rating: 5/10

unnamed

Werewolf Tycoon (Android, Joe Williamson) – a game about a werewolf who eats people in a city park. The graphics and gameplay here are cheerful – childish, the colors are light without gloomy tones, no blood and people look like round cupcakes with funny animations. The rounds are short and simple, the only enemies are journalists with cameras. It sounds, looks and plays very fun. Of the minuses – low difficulty, watching ads for canceling Game Over, the mechanism for withdrawing points to social networks does not work.
Rating: 6/10