<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Overfloater &#187; hoc</title>
	<atom:link href="http://blog.thejit.org/category/hoc/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.thejit.org</link>
	<description>Data Visualization, JavaScript and Computer Science related stuff</description>
	<lastBuildDate>Sun, 18 Jul 2010 13:38:10 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Using OCaml to visualize Radiohead&#8217;s HoC music video (part 3)</title>
		<link>http://blog.thejit.org/2008/12/06/using-ocaml-to-visualize-radioheads-hoc-music-video-part-3/</link>
		<comments>http://blog.thejit.org/2008/12/06/using-ocaml-to-visualize-radioheads-hoc-music-video-part-3/#comments</comments>
		<pubDate>Sat, 06 Dec 2008 17:11:32 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[hoc]]></category>
		<category><![CDATA[ocaml]]></category>
		<category><![CDATA[visualization]]></category>
		<category><![CDATA[ocaml visualization opengl radiohead]]></category>

		<guid isPermaLink="false">http://blog.thejit.org/?p=156</guid>
		<description><![CDATA[Update 10/2009: The project is currently hosted at GitHub.
Update 01/2009: Created a new hoc3.zip file and some documentation.
A while ago Radiohead published their House of Cards video data in form of CSV files. Each CSV file contains information about the 3D position of the points for each frame.
I wrote a couple of previous posts that [...]]]></description>
			<content:encoded><![CDATA[<p><em>Update 10/2009:</em> The project is currently hosted at <a href="http://github.com/philogb/hoc">GitHub</a>.<br />
<em>Update 01/2009:</em> Created a new hoc3.zip file and some <a href="/wp-content/hoc/doc/index.html">documentation</a>.</p>
<p>A while ago Radiohead <a href="http://code.google.com/creative/radiohead/#data-visualization" target="_blank">published</a> their <em>House of Cards</em> video data in form of CSV files. Each CSV file contains information about the 3D position of the points for each frame.</p>
<p>I wrote a couple of previous posts that covered  <a href="http://blog.thejit.org/2008/11/27/using-ocaml-to-visualize-radioheads-hoc-music-video-part-1/">how to render and save that data with OpenGL and OCaml</a> and also <a href="http://blog.thejit.org/2008/12/02/using-ocaml-to-visualize-radioheads-hoc-music-video-part-2/">how to customize camera movement in OpenGL</a>.</p>
<p>This post shows how to customize particle animations for Radiohead&#8217;s House of Cards video.<br />
A proof of concept for camera movement + particle animation is shown in this youtube video:</p>
<p><object width="500" height="344" data="http://www.youtube.com/v/ZRqKIljnvd4&amp;hl=en&amp;fs=1&amp;rel=0&amp;color1=0x3a3a3a&amp;color2=0x999999" type="application/x-shockwave-flash"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://www.youtube.com/v/ZRqKIljnvd4&amp;hl=en&amp;fs=1&amp;rel=0&amp;color1=0x3a3a3a&amp;color2=0x999999" /><param name="allowfullscreen" value="true" /></object></p>
<p>If you want to generate the video, you have to download Radiohead&#8217;s HoC music video data <a href="http://code.google.com/creative/radiohead/#data-visualization" target="_blank">here</a>. Also, you can download the source code for this project <a href="/wp-content/hoc3.zip" target="_blank">here</a>.</p>
<p>This small project is organized in a way that is easy to add new features, camera animations and particle transformations in order to easily code new videos with different effects using the HoC data.</p>
<p>Radiohead&#8217;s HoC data is a set of CSV files. Those files are rendered in OpenGL with OCaml and then saved in <em>bmp</em> or <em>jpeg</em> files to be merged into a video using <em>ffmpeg</em>. If you want to know more about this you should probably read <a href="http://blog.thejit.org/2008/11/27/using-ocaml-to-visualize-radioheads-hoc-music-video-part-1/">part 1</a> of this &#8220;trilogy&#8221;.</p>
<p>The <em>Camera Model</em> class allows you to make custom camera movements that can be handled and defined in a <em>Timeline</em> object in the <em>main.ml</em> file. If you like to know more about this, you can read <a href="http://blog.thejit.org/2008/12/02/using-ocaml-to-visualize-radioheads-hoc-music-video-part-2/">part 2</a> of this &#8220;trilogy&#8221;.</p>
<p>This last post shows how to customize particle interpolation and movement by using the <em>Particle Model</em> class, the <em>ParticleTrans</em> module and the <em>Timeline</em> object.</p>
<h4>Particle Model</h4>
<p>The <em>particle_model</em> class handles particle animations.<br />
Somewhat like the camera class, <em>particle_model</em> stores the initial frame and the last frame along with some extra information about the timing of the animation.<br />
The <em>particle_model</em> then performs an interpolation from the initial_frame to the last_frame, rendering the state of the transformation in the <em>draw</em> function.</p>
<p>A possible interface for the particle model could be something like this:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">class particle_model :
  object
    (* starting frame *)
    val mutable start_frame : VertexType.depth_vertex list
    (* ending frame *)
    val mutable last_frame : VertexType.depth_vertex list
    (* currently loaded frame *)
    val mutable loaded_frame : VertexType.depth_vertex list
    (* if setted to true, it will load a new frame for each
    step of the animation *)
    val mutable refresh_frames : bool
    (* same as the camera_model -check that post *)
    val mutable time : float
    val mutable total_frames : float
    val mutable transition : Transition.trans * Transition.ease
    (* extend start_frame or last_frame in order to
    have same number of points *)
    method balance : unit
    (* equivalent to the camera methods *)
    method step : unit
    method draw : float -&gt; unit
    (* set the type of the animation you want
    to perform *)
    method set_animation :
      float -&gt;
      bool * bool *
      (ParticleTrans.transformation * float *
       (Transition.trans * Transition.ease)) -&gt;
      unit
  end</pre>
<p>Particle animations have a special type, that ressembles the camera model transition type.<br />
This type is defined as follows:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">type animation_op =
    ParticleTrans.transformation * float *
    (Transition.trans * Transition.ease)</pre>
<p>Just to make a comparison, the camera model transition type is:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">
type camera_op_list = (camera_op list) * float * (trans * ease)</pre>
<p>This type can be divided into three main parts:</p>
<ul>
<li> The <em>float</em> value is the total number of frames the animation will use.</li>
<li> The (trans * ease) value allows you to customize different type of transitions, from <em>Linear, None</em> to <em>Quad, EaseInOut</em>. More information about this is in the <em>camera_model</em> post.</li>
<li> <em>ParticleTrans.transformation</em> is a function that applies a transformation to a frame. You can define custom functions in that module and then apply them to the visualization.<br />
I only defined a couple of functions, but you can define any other animation you like. You just have to define a function that receives a frame as input and returns a frame as output.<br />
The interface for ParticleTrans is:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">type transformation =
	| Idle
	| Project of float * float * float
	| Random

val idle : 'a -&gt; 'a

val project :
  transformation -&gt;
  VertexType.depth_vertex list -&gt;
	VertexType.depth_vertex list

val random : VertexType.depth_vertex list -&gt;
	VertexType.depth_vertex list

val get_trans :
  transformation -&gt;
  VertexType.depth_vertex list -&gt;
	VertexType.depth_vertex list</pre>
</li>
</ul>
<h4>Putting it all together</h4>
<p>The timeline object (described in the <a href="http://blog.thejit.org/2008/12/02/using-ocaml-to-visualize-radioheads-hoc-music-video-part-2/">previous post</a>) holds information about the camera and particle transformations beeing applied at each stage of the animation.<br />
This class-less object is defined in the main.ml file and looks like this:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">let timeline =
  object (self)
    val mutable frame = 0.
    val camera_timeline = [
    (* operations defined in the
    camera model post *)
    ]

    val particle_timeline = [
      (* frame number,  (invert, refresh frames, instruction) *)
      (1., (true, true, (Random, 120., (Elastic, EaseOut))));
      (420., (false, false, (Random, 50., (Quad, EaseOut))));
      (471., (false, true, (Idle, 80., (Quad, EaseIn))))
      ]

    method get_frame = frame

    method tick =
      frame &lt;- frame +. 1.;
      self#update_camera;
      self#update_animation

    method update_camera =
      try
        let camera_anim = List.assoc frame camera_timeline in
          cam#set_animations camera_anim;
        with
          | Not_found -&gt; ()

    method update_animation =
      try
        let anim = List.assoc frame particle_timeline in
          part#set_animation frame anim;
      with
          | Not_found -&gt; ()
end</pre>
<p>The <em>particle_timeline</em> and <em>camera_timeline</em> variables hold the transformations to be performed at different stages of the animation.</p>
<h4>Download and Use</h4>
<p>You can download the project <a href="/wp-content/hoc3.zip" target="_blank">here</a>.<br />
You can compile the project by typing:</p>
<pre class="ocaml-pre">ocamlc -g str.cma -I +camlimages ci_core.cma ci_jpeg.cma ci_bmp.cma
-I +lablGL lablglut.cma lablgl.cma interpolate.ml transition.ml camera.ml
 loader.ml particleTrans.ml particle.ml main.ml -o main</pre>
<p>Any comment about the Video or the OpenGL/OCaml implementation is very welcome!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.thejit.org/2008/12/06/using-ocaml-to-visualize-radioheads-hoc-music-video-part-3/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Using OCaml to visualize Radiohead&#8217;s HoC music video (part 2)</title>
		<link>http://blog.thejit.org/2008/12/02/using-ocaml-to-visualize-radioheads-hoc-music-video-part-2/</link>
		<comments>http://blog.thejit.org/2008/12/02/using-ocaml-to-visualize-radioheads-hoc-music-video-part-2/#comments</comments>
		<pubDate>Tue, 02 Dec 2008 00:44:48 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[hoc]]></category>
		<category><![CDATA[ocaml]]></category>
		<category><![CDATA[visualization]]></category>
		<category><![CDATA[opengl]]></category>

		<guid isPermaLink="false">http://blog.thejit.org/?p=109</guid>
		<description><![CDATA[This post is about performing advanced camera movement in OpenGL.
We&#8217;ll use the same Radiohead&#8217;s HoC dataset we used in the previous post.
Once again, the quality of the youtube video is pretty lame. You can right click here and save link as&#8230; to download a high quality version of the video (~100MB).
I strongly recommend you to [...]]]></description>
			<content:encoded><![CDATA[<p>This post is about performing advanced camera movement in OpenGL.<br />
We&#8217;ll use the same Radiohead&#8217;s HoC dataset we used in the <a href="http://blog.thejit.org/2008/11/27/using-ocaml-to-visualize-radioheads-hoc-music-video-part-1/">previous post</a>.</p>
<p>Once again, the quality of the youtube video is pretty lame. You can right click <a href="/wp-content/static/img/hoc2.mpg">here</a> and <em>save link as&#8230;</em> to download a high quality version of the video (~100MB).<br />
I <b>strongly recommend</b> you to see the high quality video <img src='http://blog.thejit.org/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><object width="500" height="344"><param name="movie" value="http://www.youtube.com/v/UEJqrmEWV-Q&#038;hl=en&#038;fs=1&#038;rel=0&#038;color1=0x3a3a3a&#038;color2=0x999999"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/UEJqrmEWV-Q&#038;hl=en&#038;fs=1&#038;rel=0&#038;color1=0x3a3a3a&#038;color2=0x999999" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="500" height="344"></embed></object></p>
<h4>Camera Instructions</h4>
<p>Camera movement is made of Translations and/or Rotations.<br />
We want to provide our camera model with instructions of the type:</p>
<ul>
<li><b>[ Translate <em>from</em> <em>to</em> ]</b></li>
<li><b>[ Rotate <em>from</em> <em>to</em> <em>rotation_axis</em> ]</b></li>
<li><b>[ Translate ...; Rotate ... ]</b></li>
</ul>
<p>As the last example shows, multiple transformations can be done at the same time (translations and rotations).</p>
<p>The definition for a transformation type is:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">
type camera_op =
  | Translate of Gl.point3 * Gl.point3
  | Rotate of float * float * Gl.vect3
</pre>
<p>A camera instruction is a list of these operations (<em>camera_op</em>) and a number specifying the number of frames this transformation should take (i.e the duration of the transformation).</p>
<p>So, for example, this instruction:<br />
<b>( [ Translate( (100., 100., 100.), (0., 0., 0.) ) ], 300. )</b><br />
translates the camera from (100, 100, 100) to (0, 0, 0) in 300 frames, that is in 10 seconds (at 30 frames per second).</p>
<p>Translation is done by simple interpolation. The interpolation formula for translating from <b>A</b> to <b>B</b> is something like this:<br />
<b>A + (B &#8211; A) * delta</b> with <b>delta</b> in (0, 1).</p>
<h4>Transitions</h4>
<p>It would be nice if camera movement, besides being linear, could also perform other advanced transitions, like the ones used in <a href="http://docs111.mootools.net/Effects/Fx-Transitions.js#Fx.Transitions.linear">Fx.Transitions</a> by Mootools.<br />
Some of these transitions are: Quadratic, EaseIn, EaseOut, EaseInOut, Back, Sine, etc&#8230;</p>
<p>These effects are achieved by applying functions to the <b>delta</b> value, changing the way it increases or descreases its value.<br />
A possible interface for a Transition module is:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">
type trans = Linear | Quart
type ease = None | EaseOut | EaseIn | EaseInOut

val linear : 'a -> 'a
val quart : float -> float

val ease_in : ('a -> 'b) -> 'a -> 'b
val ease_out : (float -> float) -> float -> float
val ease_in_out : (float -> float) -> float -> float

val get_transition : trans -> float -> float
val get_ease : ease -> (float -> float) -> float -> float

val get_animation : trans -> ease -> float -> float
</pre>
<p>By using <b>Transition.get_animation Quad EaseInOut delta</b> we can change the timing of our animation from this:<br />
<img src="/wp-content/static/img/Linear.png" style="margin-left:30px;" /></p>
<p>into this:<br />
<img src="/wp-content/static/img/Quad.png" style="margin-left:30px;" /></p>
<p>Our camera instructions are then defined as:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">

type camera_op_list = (camera_op list) * float * (trans * ease)
</pre>
<p>For example:<br />
<b>( [ Translate( (100., 100., 100.), (0., 0., 0.) ) ], 300. (Quad, EaseOut))</b></p>
<h4>The Camera Model</h4>
<p>A possible interface for the camera model is:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">
class camera_model :
  object
    val mutable animations : camera_op list
    val mutable time : float
    val mutable total_frames : float
    val mutable transition : Transition.trans * Transition.ease

    method get_time : float
    method step : unit
    method draw : unit
    method translate : Gl.point3 -> Gl.point3 -> float -> unit
    method rotate : float -> float -> Gl.vect3 -> float -> unit
    method set_animations :
      camera_op list * float * (trans * ease) -> unit
  end
</pre>
<p>The camera_model instance variables contain the destructured <em>camera_op_list</em> type elements: <em>animations</em>, <em>total_frames</em> and <em>transition</em>.<br />
We also provide individual methods for handling translations and rotations. These methods simply compute a delta value, apply the interpolation and then call <em>GlMat.translate3</em> or <em>GlMat.rotate3</em>.</p>
<p>The 40 line implementation looks like this:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">
class camera_model =
 object (self)
  val mutable total_frames = 0.
  val mutable time = 0.
  val mutable transition = (Linear, None)
  val mutable animations = []

  method get_time = time

  method set_animations ans =
    let (x, y, z) = ans in
      animations <- x;
      total_frames <- y;
      transition <- z;
      time <- 0.

  method step =
    if time < total_frames then
      time <- time +. 1.

  method translate start last delta =
    let (trans, ease) = transition in
    let delta_val = Transition.get_animation trans ease delta in
    let (x, y, z) = start in
    let (x', y', z') = last in
    let DVertex(a, b, c, d) = Interpolate.cartesian
                                (DVertex(x, y, z, 0.))
                                (DVertex(x', y', z', 0.))
                                delta_val
    in
      GlMat.translate3 (a, b, c)

  method rotate start last vec delta =
    let (trans, ease) = transition in
    let delta_val = Transition.get_animation trans ease delta in
    let ang = Interpolate.cartesian_float start last delta_val in
    GlMat.rotate3 ang vec 

    method draw =
      let delta = time /. total_frames in
        List.iter (fun anim ->
          match anim with
            | Translate(start, last) ->
               self#translate start last delta
            | Rotate(start, last, vec) ->
               self#rotate start last vec delta ) animations
end
</pre>
<h4>Timeline</h4>
<p>Now that we have our camera model, we need a &#8220;timeline&#8221; object that can pass intructions to the camera at different stages of the animation.<br />
We define a class-less object <em>timeline</em> that holds a list of camera transformations to be executed at a specific frame of the animation:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">
let timeline =
  object (self)
    val mutable frame = 0.
    (* Starting frame number, camera_instructions *)
    val camera_timeline = [
      (1.,   (* camera_instructions *));
      (310., (* camera_instructions *));
      (631., (* camera_instructions *) ]

    method get_frame = frame

    method tick =
      frame <- frame +. 1.;
      self#update_camera;

    method update_camera =
      try
        let camera_anim = List.assoc frame camera_timeline in
          cam#set_animations camera_anim;
        with
          | Not_found -> ()
end
</pre>
<h4>Download and Use</h4>
<p>This is all I&#8217;ve done to handle camera movement.<br />
I&#8217;m not an advanced OpenGL/OCaml developer, so any comment/suggestion about my understanding of OCaml/OpenGL is very welcome.<br />
You can download the source <a href="/wp-content/hoc2.zip" target="_blank">here</a>.<br />
You can compile the source with:</p>
<pre name="ocaml" class="ocaml-pre">
ocamlc -g str.cma -I +camlimages ci_core.cma ci_jpeg.cma ci_bmp.cma
-I +lablGL lablglut.cma lablgl.cma interpolate.ml transition.ml
camera.ml loader.ml main.ml -o main
</pre>
<p>Last part of this &#8220;trilogy&#8221; will be about particle transformations in OpenGL.<br />
Hope you enjoyed it!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.thejit.org/2008/12/02/using-ocaml-to-visualize-radioheads-hoc-music-video-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using OCaml to visualize Radiohead&#8217;s HoC music video (part 1)</title>
		<link>http://blog.thejit.org/2008/11/27/using-ocaml-to-visualize-radioheads-hoc-music-video-part-1/</link>
		<comments>http://blog.thejit.org/2008/11/27/using-ocaml-to-visualize-radioheads-hoc-music-video-part-1/#comments</comments>
		<pubDate>Thu, 27 Nov 2008 15:22:57 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[hoc]]></category>
		<category><![CDATA[ocaml]]></category>
		<category><![CDATA[visualization]]></category>
		<category><![CDATA[opengl]]></category>

		<guid isPermaLink="false">http://blog.thejit.org/?p=49</guid>
		<description><![CDATA[So I was looking for some excuse to learn OCaml + OpenGL, and I run into Radiohead&#8217;s House of Cards video dataset hosted at google code.
The dataset is made of many CSV files, one for each frame of the HoC video.
The data is also shipped with an application that uses Processing to create an image [...]]]></description>
			<content:encoded><![CDATA[<p>So I was looking for some excuse to learn OCaml + OpenGL, and I run into Radiohead&#8217;s House of Cards video dataset hosted at <a href="http://code.google.com/p/radiohead/downloads/list" target="_blank">google code</a>.<br />
The dataset is made of many CSV files, one for each frame of the HoC video.<br />
The data is also shipped with an application that uses <a href="http://processing.org/" target="_blank">Processing</a> to create an image for each frame of the video.</p>
<p>I decided to do the same program in OCaml + OpenGL: for each CSV file, the program loads it, renders it in OpenGL, and then saves that rendered data into a jpg (or bmp) image.</p>
<p>You can merge the generated image frames with the sample mp3 provided at google code, by using <b>ffmpeg</b>: </p>
<pre name="ocaml" class="ocaml-pre">
ffmpeg -f image2 -r 30 -i ./img%d.jpg -sameq -i 1.mp3 ./out.mpeg -pass 2
</pre>
<p>Anyway, the result is quite interesting, and it gives us a good ground to build better visualizations:</p>
<p>(This youtube video quality is pretty lame, I&#8217;d recommend you to right click <a href="/wp-content/static/img/hoc.mpeg">here</a> and <em>save link as&#8230;</em>).<br />
<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/4M4578jg8rI&#038;hl=en&#038;fs=1&#038;rel=0&#038;color1=0x3a3a3a&#038;color2=0x999999"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/4M4578jg8rI&#038;hl=en&#038;fs=1&#038;rel=0&#038;color1=0x3a3a3a&#038;color2=0x999999" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object></p>
<div style="clear:both"></div>
<p>This post is going to be about the making of this simple application.<br />
Further posts on this &#8220;project&#8221; will cover advanced camera movement and particle transformations.</p>
<h4>The Code</h4>
<p>This app was made in one single file, but it contains two important parts:</p>
<p>A <em>data</em> object containing information about the location of the CSV and generated image files, along with some methods to load CSV files and save OpenGL rendered pictures into image files (bmp and jpeg formats).<br />
This object uses <a href="http://pauillac.inria.fr/camlimages/" target="_blank">camlimages</a> for saving images in different formats, and the OpenGL/GLUT bindings provided by <a href="http://wwwfun.kurims.kyoto-u.ac.jp/soft/lsl/lablgl.html" target="_blank">lablGL</a>.</p>
<pre name="code" class="ocaml:nogutter">
(* Loads csv frames and saves the rendered OpenGL image *)
let data =
  object (self)
    val path_to_file = "path_to_folder_containing_csv_files"
    val path_to_image_file = "path_to_folder_that_will_contain_imgs"
    val mutable current_frame = 1
    val total_frames = 2101
    val time_interval = 33

    method get_time_interval =   time_interval

    method load_file filename =
      let channel = open_in (path_to_file ^ filename) in
      let ans = ref [] in
        try
          while true do
            let line = input_line channel in
            let sp = split (regexp ",")
                        (sub line 0 (pred (length line))) in
            match List.map float_of_string sp with
              | [ x; y; z; d ] ->
                ans := DVertex (x, y, z, d) :: !ans
              | _ -> raise (Invalid_argument "not a depth vertex")
          done;
          !ans
        with End_of_file | Invalid_argument _ ->
                 close_in_noerr channel; !ans

    method save_image =
        let img_rgb = new OImages.rgb24 600 400 in
        let pixels = GlPix.read
          ~x:0 ~y:0
          ~width:600 ~height:400
          ~format:`rgb ~kind:`ubyte
        in
        let praw = GlPix.to_raw pixels in
        let raw = Raw.gets ~pos:0 ~len:(Raw.byte_size praw) praw in
        let w = GlPix.width pixels in
        let h = GlPix.height pixels in
        for i = 0 to pred (w * h) do
          let color_rgb = { r = raw.(i * 3 + 2);
                                  g = raw.(i * 3 + 1);
                                  b = raw.(i * 3 + 0) }
          in
            img_rgb#set (i mod w) (i / w) color_rgb;
        done;
        img_rgb#save (path_to_image_file ^ "img" ^ (string_of_int current_frame) ^ ".jpg")
                              None []

    method next_frame =
      current_frame <- (current_frame + 1) mod total_frames;
      if current_frame = 0 then
        current_frame <- total_frames;
      self#load_file ((string_of_int current_frame) ^ ".csv")
end
</pre>
<p>This object is included in the <em>main.ml</em> file, which is the main entry point for the OpenGL application.<br />
This file defines functions for initializing and binding events to the main openGL app. You'll find this code familiar if you know some OpenGL.</p>
<pre name="code" class="ocaml:nogutter">
open Str
open String
open Color
open VertexType

(* Initializes openGL scene components*)
let init width height =
    GlDraw.shade_model `smooth;
    GlClear.color (0.0, 0.0, 0.0);
    GlClear.depth 1.0;
    GlClear.clear [`color; `depth];
    Gl.enable `depth_test;
    GlFunc.depth_func `lequal;
    GlMisc.hint `perspective_correction `nicest

(*  Draws the image*)
let draw () =
  GlClear.clear [`color; `depth];
  GlMat.load_identity ();
  GlMat.translate3 (-150.0, -150.0, -400.0);
  GlDraw.begins `points;
  List.iter (fun (DVertex (x, y, z, d)) ->
    let color = d /. 255. in
      GlDraw.color (color, color, color);
      GlDraw.vertex ~x:x ~y:y ~z:z ()) data#next_frame;
  GlDraw.ends ();
  Glut.swapBuffers ();
  data#save_image

(* Handle window resize *)
let reshape_cb ~w ~h =
  let
    ratio = (float_of_int w) /. (float_of_int h)
  in
    GlDraw.viewport 0 0 w h;
    GlMat.mode `projection;
    GlMat.load_identity ();
    GluMat.perspective 45.0 ratio (0.1, 1300.0);
    GlMat.mode `modelview;
    GlMat.load_identity ()

(* Handle keyboard events *)
let keyboard_cb ~key ~x ~y =
  match key with
    | 27 (* ESC *) -> exit 0
    | _ -> ()

(* A timer function setted to draw a new frame each time_interval ms *)
let rec timer value =
  Glut.postRedisplay ();
  Glut.timerFunc ~ms:data#get_time_interval
                 ~cb:(fun ~value:x -> (timer x))
                 ~value:value

(*  Main program function*)
let main () =
  let
    width = 640 and
    height = 480
  in
    ignore (Glut.init Sys.argv);
    Glut.initDisplayMode ~alpha:true ~depth:true ~double_buffer:true ();
    Glut.initWindowSize width height;
    ignore (Glut.createWindow "Radiohead HoC");
    Glut.displayFunc draw;
    Glut.keyboardFunc keyboard_cb;
    Glut.reshapeFunc reshape_cb;
    Glut.timerFunc ~ms:data#get_time_interval
                   ~cb:(fun ~value:x -> (timer x))
                   ~value:1;
    init width height;
    Glut.mainLoop ()

let _ = main ()
</pre>
<p>You can download the source <a href="/wp-content/hoc1.zip" target="_blank">here</a>.<br />
You can compile the files with the bytecode compiler:</p>
<pre name="ocaml" class="ocaml-pre">
ocamlc -g str.cma -I +camlimages ci_core.cma ci_bmp.cma ci_jpeg.cma
-I +lablGL lablglut.cma lablgl.cma main.ml -o main
</pre>
<p>.<br />
Just remember that you have to install OCaml + lablGL + camlimages to be able to use this.</p>
<p>Any comment about the code will be well appreciated, since I'm an OCaml beginner <img src='http://blog.thejit.org/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  .</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.thejit.org/2008/11/27/using-ocaml-to-visualize-radioheads-hoc-music-video-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
<enclosure url="http://blog.thejit.org/wp-content/static/img/hoc.mpeg" length="49025024" type="video/mpeg" />
		</item>
	</channel>
</rss>
