Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Thursday, 13 October 2016

Information about LuaJIT

The following are various notes about the design and implementation of LuaJIT.

Design overview

Email to lua-l mailing list.

From: Mike Pall mike.de
Subject: LuaJIT 2.0 intellectual property disclosure and research opportunities
Newsgroups: gmane.comp.lang.lua.general
Date: Monday 2nd November 2009 10:17:04 UTC (over 7 years ago)


It has been brought to my attention that it might be advantageous
for some parts of the research community and the open source
community, that I make a public statement about the intellectual
property (IP) contained in LuaJIT 2.0 and earlier versions:

  I hereby declare any and all of my own inventions contained in
  LuaJIT to be in the public domain and up for free use by anyone
  without payment of any royalties whatsoever.

  [Note that the source code itself is licensed under a permissive
  license and is not placed in the public domain. But this is an
  orthogonal issue.]

I cannot guarantee it to be free of third-party IP however. In
fact nobody can. Writing software has become a minefield and any
moderately complex piece of software is probably (unknowingly to
the author) encumbered by hundreds of dubious patents. This
especially applies to compilers. The curent IP system is broken
and software patents must be abolished. Ceterum censeo.

The usual form of disclosure is to write papers and publish them.
I'm sorry, but I don't have the time for this right now. But I
would consider publishing open source software as a form of
disclosure.

In the interest of anyone doing research on virtual machines,
compilers and interpreters, I've compiled  a list of some of the
new aspects to be found in LuaJIT 2.0. I do not claim all of them
are original (I cannot possibly know all of the literature), but
my research indicates that many of them are quite innovative.

This also presents some research opportunities for 3rd parties.
I have little use for academic merits myself -- I'm more interested
in coding than writing papers. Anyone is welcome to dig out any
aspects, explore them in detail and publish them (giving due credit).

Design aspects of the VM:

- NaN-tagging: 64 bit tagged values are used for stack slots and
  table slots. Unboxed floating-point numbers (doubles) are
  overlayed with tagged object references. The latter can be
  distinguished from numbers via the use of special NaNs as tags.
  It's a remote descendant of pointer-tagging.

  [The idea dates back to 2006, but I haven't disclosed it before
  2008. Special NaNs have been used to overlay pointers before.
  Others have used it for tagging later on. The specific layout is
  of my own devising.]

- Low-overhead call frames: The linear, growable stack implicitly
  holds the frame structure. The tags for the base function of
  each call frame hold a linked structure of frames, using no
  extra space. Calls/returns are faster due to lower memory
  traffic. This also allows installing exception handlers at zero
  cost (it's a special bit pattern in the frame link).

Design of the IR (intermediate representation) used by the compiler:

- Linear, pointer-free IR: The typed IR is SSA-based and highly
  orthogonal. An instruction takes up only 64 bits. It has up to
  two operands which are 16 bit references. It's implemented with
  a bidirectionally growable array. No trees, no pointers, no cry.
  Heavily optimized for minimal D-cache impact, too.

- Skip-list chains: The IR is threaded with segregated, per-opcode
  skip-list chains. The links are stored in a multi-purpose 16 bit
  field in the instruction. This facilitates low-overhead lookup
  for CSE, DSE and alias analysis. Back-linking enables short-cut
  searches (average overhead is less than 1 lookup). Incremental
  build-up is trivial. No hashes, no sets, no complex updates.

- IR references: Specially crafted IR references allow fast const
  vs. non-const decisions. The trace recorder uses type-tagged
  references (a form of caching) internally for low-overhead
  type-based dispatch.

- High-level IR: A single, uniform high-level IR is used across
  all stages of the compiler. This reduces overall complexity.
  Careful instruction design avoids any impact on low-level CSE
  opportunities. It also allows cheap and effective high-level
  semantic disambiguation for memory references.

Design of the compiler pipeline:

- Rule-based FOLD engine: The FOLD engine is primarily used for
  constant folding, algebraic simplifications and reassociation.
  Most traditional compilers have an evolutionary grown set of
  implicit rules, spread over thousands of hand-coded tiny
  conditionals.

  The rule-based FOLD engine uses a declarative approach to
  combine the first and second level of lookup. It allows wildcard
  lookup with masked keys, too. A pre-processor generates a
  semi-perfect hash table for constant-time rule lookup. It's able
  to deal with thousands of rules in a uniform manner without
  performance degradation. A declarative approach is also much
  easier to maintain.

- Unified stage dispatch: The FOLD engine is the first stage in
  the compiler pipeline. Wildcard rules are used to dispatch
  specific instructions or instruction types (loads, stores,
  allocations etc.) to later optimization stages (load forwarding,
  DSE etc.). Unmatched instructions are passed on to CSE.

  Unified stage dispatch facilitates modular and pluggable
  optimizations with only local knowledge. It's also faster than
  doing multiple dispatches in every stage.

Trace compiler:

- NLF region-selection: The trace heuristics use a natural-loop
  first (NLF) region-selection mechanism to come up with a
  close-to optimal set of (looping) root traces. Only special
  bytecode instructions trigger new root traces -- regular
  conditionals never do this. Root traces that leave the loop are
  aborted and retried later. This also gives outer loops a chance
  to inline inner loops with a low trip count.

  NLF usually generates a superior set of root traces than the
  MRET/NET (next-executing tail) and LEI (last-executed iteration)
  region-selection mechanisms known from the literature.

- Hashed profile counters: Bytecode instructions to trigger the
  start of a hot trace use low-overhead hashed profiling counters.
  The profile is imprecise because collisions are ignored. The
  hash table is kept very small to reduce D-cache impact (only two
  hot cache lines). Since NLF weeds out most false positives, this
  doesn't deteriorate hot trace detection.

  [Neither using hashed profile counters, nor imprecise profiling,
  nor using profiling to detect hot loops is new. But the specific
  combination may be original.]

- Code sinking via snapshots: The VM must be in a consistent state
  when a trace exits. This means that all updates (stores) to the
  state (stack or objects) must track the original language
  semantics.

  Naive trace compilers achieve this by forcing a full update of
  the state to memory before every exit. This causes many on-trace
  stores and seriously diminishes code quality.

  A better approach is to sink these stores to compensation code,
  which is only executed if the trace exits are actually taken.
  A common solution is to emit actual code for these stores. But
  this causes code cache bloat and the information often needs to
  be stored redundantly, for linking of side traces.

  Code sinking via snapshots allows sinking of arbitrary code
  without the overhead of the other approaches. A snapshot stores
  a consistent view of all updates to the state before an exit. If
  an exit is taken the on-trace machine state (registers and spill
  slots) and the snapshot can be used to restore the VM state.

  State restoration using this data-driven approach is slow of
  course. But repeatedly taken side exits quickly trigger the
  generation of side traces. The snapshot is used to initialize
  the IR of the side trace with the necessary state using
  pseudo-loads. These can be optimized together with the remainder
  of the side trace. The pseudo-loads are unified with the machine
  state of the parent trace by the backend to enable zero-cost
  linking to side traces.

  [Currently snapshots only allow store sinking of scalars. It's
  planned to extend this to allow arbitrary store and allocation
  sinking, which together with store forwarding would be a unique
  way to achieve scalar-replacement of aggregates.]

- Sparse snapshots: Taking a full snapshot of all state updates
  before every exit would need a considerable amount of storage.
  Since all scalar stores are sunk, it's feasible to reduce the
  snapshot density. The basic idea is that it doesn't matter which
  state is restored on a taken exit, as long as it's consistent.

  This is a form of transactional state management. Every snapshot
  is a commit; a taken exit causes a rollback to the last commit.
  The on-trace state may advance beyond the last commit as long as
  this doesn't affect the possibility of a rollback. In practice
  this means that all on-trace updates to the state (non-scalar
  stores that are not sunk) need to force a new snapshot for the
  next exit.

  Otherwise the trace recorder only generates a snapshot after
  control-flow constructs that are present in the source, too.
  Guards that have a low probability of being wrongly predicted do
  not cause snapshots (e.g. function dispatch). This further
  reduces the snapshot density. Sparse snapshots also improve
  on-trace code quality, because they reduce the live range of the
  results of intermediate computations. Scheduling decisions can
  be made over a longer stream of instructions, too.

  [It's planned to switch to compressed snapshots. 2D-compression
  across snapshots may be able to remove even more redundancy.]

Optimizations:

- Hash slot specialization: Hash table lookup for constant keys is
  specialized to the predicted hash slot. This avoids a loop to
  follow the hash chain. Pseudocode:

    HREFK:  if (hash[17].key != key) goto exit
    HLOAD:  x = hash[17].value
    -or-
    HSTORE: hash[17].value = x

  HREFK is shared by multiple HLOADs/HSTOREs and may be hoisted
  independently. The verification of the prediction (HREFK) is
  moved out of the dependency chain by a super-scalar CPU. This
  makes hash lookup as cheap as array lookup with minimal complexity.

  It also avoids all the complications (cache invalidation,
  ordering constraints, shape mismatches) associated with hidden
  classes (V8) or shape inference/property caching (TraceMonkey).

- Code hoisting via unrolling and copy-substitution (LOOP):
  Traditional loop-invariant code motion (LICM) is mostly useless
  for the IR resulting from dynamic languages. The IR has many
  guards and most subsequent instructions are control-dependent on
  them. The first non-hoistable guard would effectively prevent
  hoisting of all subsequent instructions.

  The LOOP pass does synthetic unrolling of the recorded IR,
  combining copy-substitution with redundancy elimination to
  achieve code hoisting. The unrolled and copy-substituted
  instructions are simply fed back into the compiler pipeline,
  which allows reuse of all optimizations for redundancy
  elimination. Loop recurrences are detected on-the-fly and a
  minimized set of PHIs is generated.

- Narrowing of numbers to integers: Predictive narrowing is used
  for induction variables. Demand-driven narrowing is used for
  index expressions using a backpropagation algorithm.

  This avoids the complexity associated with speculative, eager
  narrowing, which also causes excessive control-flow dependencies
  due to the many overflow checks. Selective narrowing is better
  at exploiting the combined bandwidth of the FP and integer units
  of the CPU and avoids clogging up the branch unit.

Register allocation:

- Blended cost-model for R-LSRA: The reverse-linear-scan register
  allocator uses a blended cost model for its spill decisions.
  This takes into account multiple factors (e.g. PHI weight) and
  benefits from the special layout of IR references (constants
  before invariant instructions, before variant instructions).

- Register hints: The register allocation heuristics take into
  account register hints, e.g. for loop recurrences or calling
  conventions. This is very cheap to implement, but improves the
  allocation decisions considerably. It reduces register shuffling
  and prevents unnecessary spills.

- x86-specific improvements: Special heuristics for move vs.
  rename produce close to optimal code for two-operand machine
  code instructions.

  Fusion of memory operands into instructions is required to
  generate high-quality x86 code. Late fusion in the backend
  allows better, local decisions, based on actual register
  pressure, rather than estimates of prior stages.

Ok, that's it! Sorry for the length of this posting, but I hope it
was at least informative to someone out there.

--Mike

Links

Wednesday, 31 August 2016

Ponder: what is reflection?

This is discussion on the current state of Ponder and thoughts on future changes.

What is reflection?

Wikipedia states:
In computer science, reflection is the ability of a computer program to examine, introspect, and modify its own structure and behavior at runtime
and uses are:
... observing and modifying program execution at runtime. A reflection-oriented program component can monitor the execution of an enclosure of code and can modify itself according to a desired goal related to that enclosure. This is typically accomplished by dynamically assigning program code at runtime. 
In object-oriented programming languages such as Java, reflection allows inspection of classes, interfaces, fields and methods at runtime without knowing the names of the interfaces, fields, methods at compile time. It also allows instantiation of new objects and invocation of methods. 
Reflection can be used to adapt a given program to different situations dynamically. Reflection-oriented programming almost always requires additional knowledge, framework, relational mapping, and object relevance in order to take advantage of more generic code execution.
Features we might expect are:

Type Introspection

The ability to introspect a program type. E.g. see what type it is and which members it contains. This might useful for runtime data binding, e.g. loading an XML file and assigning the values to class members based on element name matches.

Some C++ reflection systems offer this data automatically by parsing the symbols in a compiled C++ file. Ponder does not offer this, and there is some discussion of this in a previous post. It is generally thought that you do not want to export all data, and that sometimes the data needs annotating in order to remove ambiguity. For example, function returning references: should the values be copied or kept as references?

Self Modification

Since C++ is statically compiled, self modified code might be limited to setting pointers and callbacks to chosen type. It might be possible by implementing a runtime dynamic C++ compiler is complicated, and also likely something you would't want to distribute with your program. A more popular way would be to customise behaviour with data, or use an embeddable scripting language, perhaps with dynamic features, e.g. Lua.


Tuesday, 24 May 2016

Cheatsheet online

Cheatsheet is now online. Previously it run in a browser on the desktop. Now it is hosted on Github pages.

Sheets currently are:
Moonscript now has syntax highlighting via Highlight.js, which I added.

Thursday, 3 December 2015

Cheatsheets

When I'm working, I like quick references to documents or notes I make. This is often the case with things with fiddly syntax, like BASH. Cheatsheets are a great way to summarise information for quick look up.

I wrote some HTML and Javascript to format Markdown notes into something more readable, with extra browsing functionality. The advantage of using Markdown is that it is quite readable as text, and on Github the preview is nicely formatted. All the formatting is done using jQuery, live, in the HTML page.

The project is on Github (As of writing the notes are still a work in progress!). It is very easy to add new notes by just adding a new markdown file. Updating shared notes between locations is as easy as git pull.

Here are some example BASH notes:

Syntax highlighted code examples.

Extended formatting for defines.

Key shortcuts.

I used Bootstrap to get themes and layout easily. There is syntax highlighted code, via HighlightJS. I also added some extra markup syntax for lists of things, like defines. It really is quite impressive what quality open source Javascript libraries are available these days.


Sunday, 6 March 2011

Allegro 5.0 on Mac Snow Leopard

For more notes on Allegro 5 on Lion and Xcode 4 see this post.

I had been experimenting with Allegro 4.4, but now Allegro 5.0.0 has arrived. Apparently version 5.0 has had its API revamped and more functionality added, so I decided to give it a go. I believe it now expects hardware acceleration and has drivers for OpenGL and DirectX. Its appeal lies in its simplicity, good support, and is very cross platform, supporting Windows, Linux, OSX, iPhone, etc.

Build notes:

Dependencies

Previously I had been building libraries from their source and installing them in /usr/local using the usual UNIX build routine (i.e. download source and make). This is somewhat laborious and can be time consuming if something goes wrong (because not OSX compatible). This time round I decided to use MacPorts to do the lifting for me. This saves a lot of time. Just follow their standard installation instructions.

Then you need to install the libraries that you will need to compile Allegro 5. These are listed on this page, but aren't quite correct. I used:
sudo port install zlib freetype jpeg libogg libvorbis
Some of these need to be compiled in "universal" mode as they are compiled in 64 bit by default (which is the default of the compiler, new on OSX 10.6):
sudo port upgrade --enforce-variants libpng +universal
sudo port upgrade --enforce-variants physfs +universal
This will take a while if you are doing this from scratch (20+ mins). After this you should have a new /opt directory, which contains a load of new libraries. You can type "port installed" to see what you have. Some libraries will have "+universal" next to them.

Now download the Allegro 5 source, or get latest from svn. You can repeat the steps from here onwards when you get new versions of Allegro.

To build Allegro you can either build libraries or a framework, and you can either use makefiles or Xcode project files. I built libraries using Xcode 3, and now frameworks using makefiles. Frameworks are more in fitting with the Mac way of doing things, so probably best to use those.

Xcode 3 - Static library

To build using Xcode: Snow Leopard GCC compiles 64-bit code by default, but Allegro is not a 64-bit library, so we want to compile everything as i386. We first generate the Xcode files and then load them in Xcode 3 and change the settings for 32 bit (i386):
  • cd to/allegro
  • mkdir build
  • cd build
  • cmake -G Xcode ..
This will do a load of scanning for the dependencies it needs and then you'll end up with an Xcode project file: ALLEGRO.xcodeproj. This can be opened using Xcode 3 or 4. Although, at the current point (July 2011) I wouldn't recommend Xcode 4, it's just not ready.

For Xcode 3: open the the project file and (in the root project at the top):
  • Change the Architectures to 32-bit Universal.
  • I chose the RelWithDebInfo configuration. I haven't tried the others.
  • Change the active architecture to i386. This is important as Allegro is 32-bit.
  • Reading this article is useful if you don't know which SDK to use.
Build the ALL_BUILD target. You can run A5teroids and some of the example to check that it all works.

Sorry, I haven't built this using the project for Xcode 4. Use the frameworks below if you can't manage it. That's what I am using.

The install will fail because the script it is trying to run needs root access. So go back to the terminal and run the install command manually:
sudo cmake -DBUILD_TYPE=RelWithDbgInfo -P cmake_install.cmake
Then the Allegro files will be installed in /usr/local and you can include and link then from the usual places.

Frameworks

OSX 10.6 switched from 32 bit to 64 bit. Allegro needs to be compiled as 32 bit (i386). So we do the following in the unpacked allegro directory:
  • mkdir build
  • cd build
  • cmake -DWANT_FRAMEWORKS=1 -DCMAKE_OSX_ARCHITECTURES=i386 ..
  • make
  • make install
And Bob is your Auntie.

Hopefully at some point some kind person will add Allegro 5 to MacPorts to save having to do this.


New Project

The easiest way to set a new project up is to create a command-line application in Xcode. However, if we want to package all the assets, like normal Mac applications, you need to create a Cocoa application ("New Project..." > "Cocoa Application").

In the project settings, add "/usr/local/include" as a user header path. This will include the Allegro file that we just installed above. In targets, right click on your application and choose "Add..." and add existing files "/usr/local/lib/liballegro.dylib" and "/usr/local/lib/liballegro_main.dylib". Now, you should be able to build and run your application. However, two windows will appear! This is because the liballegro_main stub will create a window as well as your default application having one (in the .xib).

To remove the default app window (because we want the Allegro one) look in the "resources" folder and open "MainMenu.xib". This brings up the interface designer. In the list of objects, delete the NSWindow object, this will stop two windows being created when the application starts. We also don't need the auto-generated stub code for the application either, so you delete the "main.m" and "app delegate.m" files. You can also delete items from the menu you don't want by dragging them onto the desktop (and they disappear in a puff of smoke). If you build and run you should have one window now.

There is a tutorial on Allegro 5 on the wiki. The API looks a bit more tidy and better namespaced now.


[6-Mar-11] - Updated for Allegro 5.0.0. Notes were previously for the release candidates.
[25-Mar-11] - Added missing libvorbis to port install.
[26-Apr-11] - Using Xcode 3 for building. Xcode 4 wasn't available when this was written.
[7-Jul-11] - Notes for building with frameworks and Macports 32-bit builds.


Tuesday, 22 February 2011

What motivates us?

Interesting talk on what motivates us. Studies find that cognitive work is not driven by financial reward, but more by a sense of purpose.









Tuesday, 6 April 2010

Using Allegro 4.4 on Mac

Building

I have Macbook with Snow Leopard 10.6.2 installed and Allegro 4.4.1.1. I did have some hiccups with Allegro 4.4.0.1. Not sure if this was my fault or the distro as I'm still newish to the Mac and the Allegro Mac instructions are a bit dated.

I first tried building Allegro as a framework, but this doesn't work as I think it should. If you include a framework using: #include "Allegro/allegro.h", the internal Allegro files don't prefix with the framework name "Allegro". So, you end up adding the framework path, which is pointless, so you may as well just compile Allegro in /usr/local and link it from there.

Get Allegro (I used 4.4.1.1). Unzip. I have cmake 2.8. In the Allegro directory :-
  • mkdir build
  • cd build
  • cmake ..
  • sudo make install
  • make clean
Dependencies:
  • OpenGL - included in OS.
  • libpng, zlib and vorbis - These can be downloaded and installed as standard libs in /usr/local. I don't bother with fink or Macports as I don't want the clutter. I want everything to work "natively". There are some details under the pygame build instructions.
So you should now have a working copy of Allego in /usr/local/include and /usr/local/lib, with some executable utilities in /usr/local/bin.

From the mailing list it appears that you can only compile Allegro as a 32 bit library, there is no 64 bit support so any libraries or frameworks and the dependent libraries will have to be 32 bit. Leopard default is 32 bit. Snow Leopard default is 64 bit.

Creating project in Xcode
  • Create a new command-line C++ tool project.
  • Paste in the GL example.
  • Add /usr/local/include to the header search paths in project settings.
  • Add the following frameworks to "Link with Binary Libraries" :
    • Cocoa.
    • OpenGL.
    • Carbon. (Ideally you shouldn't need this, but there is some reference to ShowMenuBar and HideMenuBar, which doesn't appear when you build Allegro as a framework.)
  • Add the following libraries from /usr/local/lib :
    • liballeg.4.4.dylib
    • liballeggl.a
    • liballeg-main.a  (This is a stub for "main" that glues Cocoa to Allegro.)
  • Build the target and it should compile and link.
  • You are now good to go at writing OpenGL games using Allegro.
[8-Apr-10] Changed because building as framework just doesn't work properly.

Monday, 5 April 2010

Clanlib vs Allegro vs SDL on Mac OSX

I want to write a little game in C++. Previously, on Windows, I've used Clanlib. This is nicely designed and has pretty much all you need for a game. However, I now have a Macbook (OSX 10.6.2) and Clanlib has fallen behind the times Mac-wise as it still uses Carbon. There don't seem to be any plans to port it and I don't have the experience or time to this work. So I had a look round at the alternatives (again!).

Clanlib 2.1
  • Pretty mature, modern library with some nice features (e.g. slots and GUI support).
  • Hardware acceleration through OpenGL or DirectX depending on platform.
  • Windows and Linux are well supported but Mac has fallen behind, no Cocoa support.
  • Version 2.0 was the previous 0.9 version; and 1.0 is the old 0.8 version, renamed. Version 1.0 compiles for the Mac but uses the 32-bit Carbon API. In Xcode 3.2.1 you can no longer create a Carbon project, it must be Cocoa; and if you want to do iPhone, this must definitely be the case.
  • Xcode project files provided for Mac. Version 2 needs work.
  • Licence: BSD.

SDL 1.2 / 1.3
  • SDL is a well thought out low level library, but SDL libraries a bit scattered and some look unmaintained.
  • Very portable and core well supported.
  • OpenGL compatible.
  • Uses Cocoa on Mac.
  • Can be built as a framework. 
  • Basic sprites don't support rotation.
  • Licence for version 1.2:  LGPL.
  • Licence for version 1.3: Dual licence, LGPL and commercial (closed source). On embedded platforms (e.g. iPhone) you have no choice but to buy a commercial licence or you are forced to go open source.

Allegro 4.4
  • This is quite an old game library but seems to be well supported. Some of it is quite archaic, with palette support and support for old DOS compilers.
  • Mac port uses Cocoa.
  • API being reworked in Allegro 5.
  • Can be built as a framework.
  • Uses cmake to generate project files.
  • Polling API.
  • Minimal external dependencies (e.g. includes JPEG decoder).
  • Licence: Giftware.

Allegro 5.1
  • Allegro 5 been a long time in development, but worth the wait. Allegro had a lot of cruft from DOS and pre-graphic cards. The latest version is 5.1.
  • The API is a lot more organised than 4.x. It is simple and elegant.
  • The live version, straight from git (with build instructions) is available. Please note that whilst this contains new features and fixes, it also sometimes contains bugs (which happens during development). If you aren't comfortable with this use the latest stable release.
  • OpenGL and DirectX renderers (hardware accelerated) by default.
  • Event based API (i.e. not polling).
  • Notes on building for Mac OSX.
  • Licence: Giftware.
  • (This was version 4.9 in the original comparison, which was a work-in-progress version of Allegro 5.0.)

Conclusion

I like the extra features that Clanlib and Allegro supply in their default libraries. Clanlib unfortunately uses Carbon on the Mac and Mac version not supported for long time. This is a real shame because Clanlib includes everything you need (including a GUI).

SDL provides extra features in libraries which I find a little scattered and iPhone development requires a commercial licence if you don't want to release your source code.

So as a result I decided on switching to Allegro 4.4, because unsure how mature 4.9 is, and generally Mac lags behind the main development platforms (Linux and Windows). I'll build my own API, hiding some of the the archaic nature of Allegro. I also decided on Allegro because I found the retro games site, which uses AllegroGL. :-)

I've now switched to Allegro 5. It is still a nice simple API, much improved and tidied up, and libraries updated for modern hardware. Works fine for OSX 10.6.  This is the best, simple cross platform (Windows, Linux, OSX) solution I have found.

[24-Jul-10] Updated because SDL 1.3 has now move to dual licence.
[25-Mar-11] Updated for Allegro 5.0. Removed notes on 4.9 as not useful.
[16-Jan-13] Updated notes on Allegro 5.1.

Thursday, 15 October 2009

Field

Field looks like a really interesting piece of software. It is step on from Processing, providing a richer IDE with features like embedded editing widgets. I haven't used it in anger yet, and it is still beta, but it looks promising. There are apparently 6 years of work in there so there must be a lot more than meets the eye!


What I also like is the implementation philosophy that other libraries and technologies should be embraced and integrated, rather than rewrite everything. It appears that Field provides a wrapper around other technologies and allows time coordinated use of them. The screen shot about shows the canvas. Left to right is the timeline and the boxes represent things going on.

It will be interesting to use the editor and experiment with the embedded widgets. I've thought about a similar concept for my Guish project, where you'd have interactive GUI elements mixed with text that you enter, like in a terminal. Pure text terminals see really out of date now, and it's about time there was some suitable graphical enhancements.

Other pieces of work by the Open Ended Group that look interesting are Breath, which explores different graphical representations of music, and Musical Creatures, which explores digital creatures that can interact with their environment.

Thursday, 9 April 2009

Mac usable coloured terminal

When using a terminal window on the Mac (or on any system!) if everything is the same colour it is difficult to tell the difference between file types. E.g. there is no difference in presentation between a file, a directory and a link.

If you are using a bash shell (it tells you in the title bar what type it is), you can configure colouring using your profile. This lives in the file: ~/.profile. Add your changes to the end of the file.

There are some helpful blogs with information on what to add, but I found the bold lettering difficult to read. You achieve something more readable just using 'ls -G'. So add:

alias ls='ls -GF'
alias ll='ls -hl'

The -F option also tells you what the object type is (man ls), and ll adds an extra command to save doing ls -l.

You might also want to change your terminal prompt. The default is the machine you are logged into, which is a little pointless if you know it, and takes up a lot of screen. I find the following quite useful:
export PS1='\t \w> '
\t gives you the time in 24 hour format. It also gives seconds and can be a useful way of timing commands roughly. \w tells you the current directory.

Tuesday, 17 March 2009

First Jython experiment

W00t! Got first Jython program working with GTGE:
# Test of Jython and GTGE.

# Java Foundation Classes (JFC)
from java.awt import *

# GTGE API
from com.golden.gamedev import *


"""
**
* The basic skeleton of Golden T Game Engine (GTGE).
*
* Objective: show how to set up a new game.
*
"""

class Test(Game):

def initResources(self):
# initialize game variables
pass

def update(self,elapsedTime):
# update game variables
pass

def render(self,g):
# render to the screen
pass


def main():
game = GameLoader()
game.setup(Test(), Dimension(640,480), False)
game.start()

main()


I decided on GTGE because it seems like it has been used for a lot of games so far, and so is fairly mature. It has also just been released as open source and seems to fairly well supported. We'll see.

Anyway, have a working Jython program that create a GTGE window. Admittedly the authors of GTGE did all the work and I just converted a Java tutorial into Python. Original Java code:
// JFC
import java.awt.*;

// GTGE
import com.golden.gamedev.*;


/**
* Game in Windowed Mode Environment.
*
* Objective: show how to set up a windowed mode game
*/
public class Tutorial5_1 extends Game {


/***************************************/
/************ GAME SKELETON ************/
/***************************************/

public void initResources() {
}


public void update(long elapsedTime) {
}


public void render(Graphics2D g) {
}


/**************************************/
/********** START-POINT ***************/
/**************************************/

public static void main(String[] args) {
GameLoader game = new GameLoader();
game.setup(new Tutorial5_1(), new Dimension(640,480), false);
game.start();
}

}

Saturday, 14 March 2009

Java games

Been wanting to write a little game for fun. There are lots of ways to do this!

There are good C/C++ cross platform game libraries. One of the best I found is Clanlib. It's well designed and contains everything you'll need. Libraries like SDL provide simple cross platform APIs but extra functionality is via extension libraries which tend to be low quality or not maintained. Clanlib provides more of a coherent framework, and uses OpenGL for all rendering, so there are no platform specific quirks.

Using Python and PyGame means you don't have to recompile per platform. PyGame provide bindings for SDL. High level languages, like Python, are nice for prototyping and knocking experimental games up. You also don't need to worry too much about performance these days since most PCs have more than enough horsepower.

If you want to get your game to the widest audience then probably the best way is to make is playable in a browser. Downloading executables from the web is a lottery. Any program could contain malicious code. Running them in a browser gives people more confidence nothing nasty will happen. Flash is quite popular for this, but I didn't really grow to like it when experimenting with it. Now that canvas has arrived, Flash may be on the way out.

I've never really used Java, I suppose I haven't found a use for it. I use C++ for performance programming and Python for scripted tools etc. An interesting Python variant is Jython, that is, Python written in Java. This allows you to compile Python code into Java. So this seems like a good compromise, and allows you embed your Jython applet in a page to be used.

Using Java and Python also allows me to use Eclipse, which is a great development environment. We'll see how it works out.