jQuery DataTables with Lift Framework

Let me introduce the two components from the title of this post.

Lift is a very interesting and fun web framework. The main thing distinguishing it from the mass of web frameworks is that it’s not an MVC framework, not a typical one. It abandons the idea of executing one method of some controller per request for something a way more flexible. It’s called “view first” and as it suggests views are parsed in the first place and actions to call are infered from them.

Second (or more precisely first) thing from the title – DataTables is a jQuery plugin that allows to create rich and useful ajax (or not ajax) tables of data.

After some tinkering (and learning about fundamental fmapFunc function) I’ve written a view class for Lift that greatly simplifies usage of DataTables in Lift.

While writing this Lift 2.4 and DataTables 1.9.3 were used.

Usage

The source code is available here: https://gist.github.com/3099013

Here’s how to use this. First complete setup steps:

  1. Create a Lift project if you haven’t already.
  2. Create a file called DataTable.scala in your view package (perhaps code.view or com.yourcompany.product.view)
  3. Paste contents of the gist and save. You may need to change the package name at the top of the file.
  4. Obtain DataTables plugin and place jquery.dataTables.js file in /src/main/webapp/scripts/
  5. Copy other media files to corresponding folders if you’re going to use them.

Now let’s make it work. We will write a simple snippet that will demonstrate a data table. Go ahead and create a new snippet class, say DemoTable.scala and write an implementation like this:

package code.snippet

import code.view._

class DemoTable {
  def table = {
    val cols = "Col1" :: "Col2" :: Nil

    // this function returns data to populate table based on parameters passed in
    val fun = (params: DataTableParams) => {
      val rows = List(("row1_col1", "row1_col2"), ("row2_col1", "row2_col2"))
      val count = 2

      new DataTableObjectSource(count, count, rows.map(r =>
        List(("0", r._1),
          ("1", r._2),
          ("DT_RowId", "rowid_" + r._1))))
    }

    DataTable(
      cols, // columns
      fun, // our data provider
      "my-table", // html table id
      List(("bFilter", "false")), // datatables configuration
      ("class", "table table-striped table-bordered")) // set css class for table
  }
}

Now create a simple template table.html:

<div class="lift:surround?with=default;at=content">
  <div class="lift:DemoTable.table"></div>
</div>

Last thing to do is enable this page in boot, for example:
Menu("Demo table") / "table",

And we’re done. Page localhost:8080/table will show a very simple but operational data table.

Explanation

DataTable() creates a DataTables widget so we want to return it’s result from our rendering function. It takes several parameters:

The most important part is function providing data. It’s a function that takes DataTableParams as parameter and returns either DataTableArraySource or DataTableObjectSource. Those three classes encapsulate parameters and responses used for communication between javascript and server as described here: http://datatables.net/usage/server-side. In this example we used object source so we could pass DT_RowID for each row (not very useful in this example though :) ). Usually in data providing function we would retrieve relevant and sorted data from a database.

Posted on August 13, 2012 at 1:33 am by Lubiluk · Permalink · 7 Comments
In: Uncategorized

Cocoa – Adding mask and overlay to an image

Masking an image in cocoa framework sometimes is not that straightforward as it should be, therefore I’m sharing a code that accomplishes that task in a very simple and neat way.

Simply applying mask to an image using CGImageMaskCreate and assigning result image to UIImageView’s image property often doesn’t work properly – the result has black colour instead of transparent in masked regions. It may work only when your image has alpha channel.

But there is a more convenient way to achieve image mask. I have prepared a small class that extends UIView. It displays an image masked by given mask and in addition applies an overlay to the image. The class can display image with mask or overlay or with both at the same time.

Class is available for download here: DSMaskAndOverlayView.zip

In order to use it place a UIView in your layout using Interface Builder, make it subclass of DSMaskAndOverlayView (you can also layout it from code) and configure it by assigning images (UIImage) to image, mask and overlay properties.

The method used for image masking in the class is very simple. It actually makes use of CGImageMaskCreate to create masked image and draws it in drawRect method. This way we don’t need to worry about alpha channel in our image. Overlay is achieved by simply drawing given overlay image on top of the base or masked base image with use of kCGBlendModeOverlay blend mode.
That’s just a sample, you can easily add your own effects to this class.

The essential code of the class is listed below:

- (void)drawRect:(CGRect)rect
{
    if (_image == nil) {
        return;
    }
    
    if (_mask != nil) {
        UIImage *masked = [self maskImage:_image withMask:_mask];
        [masked drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) blendMode:kCGBlendModeNormal alpha:1.0];
    } else {
        [_image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) blendMode:kCGBlendModeNormal alpha:1.0];
    }
    
    if (_overlay != nil) {
        [_overlay drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) blendMode:kCGBlendModeOverlay alpha:1.0];
    }
}

Masking function:

- (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage {
        CGImageRef maskRef = maskImage.CGImage; 

	CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
                                        CGImageGetHeight(maskRef),
                                        CGImageGetBitsPerComponent(maskRef),
                                        CGImageGetBitsPerPixel(maskRef),
                                        CGImageGetBytesPerRow(maskRef),
                                        CGImageGetDataProvider(maskRef), NULL, false);
    
	CGImageRef masked = CGImageCreateWithMask([image CGImage], mask);
    
	UIImage *result = [UIImage imageWithCGImage:masked];
    
    CGImageRelease(mask);
	CGImageRelease(masked);
	CGImageRelease(maskRef);
    
    return result;
}

Usage:

...
maskAndOverlayView.image = [UIImage imageNamed:@"my_image.png"];
maskAndOverlayView.mask = [UIImage imageNamed:@"my_mask.png"];
maskAndOverlayView.overlay = [UIImage imageNamed:@"my_overlay.png"];
Posted on August 7, 2011 at 11:02 pm by Lubiluk · Permalink · One Comment
In: Uncategorized · Tagged with: ,

Getting started with PhysX SDK 3.0 on Linux

Nvidia has released PhysX SDK 3.0 with new features/changes and promised native support for 64-bit machines (Official release notes). Amongst, SDK packages there is also one for Linux. Unfortunately Nvidia again doesn’t ship any documentation or samples for Linux users. But that won’t stop us.
Putting all the PhysX parts together is quite cumbersome task, therefore in this entry I will show you how to set up the SDK and compile a simple sample PhysX code.

Getting the SDK

PhysX SDK 3.0 can be downloaded from Nvidia developer suppor center: http://supportcenteronline.com/ics/support/DLRedirect.asp?fileID=111953. You need to have an account there in order to download packages (it’s free).  (By the way, passwords on this site are stored non-hashed…)

Extract the package in your filesystem and prepare your editor or IDE for hacking. I extracted the SDK into /opt/PhysXSDK and I will use that location in the rest of this article.

The SDK consists of include files, static libraries and some c++ source files.

I recommend you to download PhysX SDK for Windows as well, because it contains documentation in .chm files and samples which are missing in Linux package.

Compiling a simple program

Sample PhysX 3.0 program screenshot We need some sample code to play with it’s compilation. Samples provided with the SDK (in Windows packgage) are far more complicated than in previous releases, therefore instead of trying to compile one of them I’ve picked one very simple sample code from the internet. I’ve found a nice simple program on this site: http://mmmovania.blogspot.com/2011/05/simple-bouncing-box-physx3.html?utm_source=BP_recent. The only thing that it does is dropping a cube on the ground, but more important is that, it performs all needed PhysX initializations. I have modified the source file slightly such that it can be compiled under Linux with gcc. You can obtain the modified file here: SampleBox.cc

In order to compile the file we need to set up 4 things: defined symbols, include paths, library paths and link flags.

Find appropriate (preprocessor and linker) settings of your project in your IDE or enter flags for compiler in command line.

  1. The only one symbol that has to be defined is either _DEBUG (for debug mode) or NDEBUG. Only one of them may be defined at a time.  Apropriate preprocessor flag is:
    -D_DEBUG or -DNDEBUG
  2. Next we need to set up include paths for PhysX header files. Note that it’s not a complete set of PhysX includes. If you will use some other header files that are not included here remember to add apropriate paths for preprocessor. Aslo, it is better to not use depracated functionalities from the last include directory.
    -I/opt/PhysXSDK/SDKs/PhysXAPI \
    -I/opt/PhysXSDK/SDKs/PhysXAPI/extensions \
    -I/opt/PhysXSDK/PhysXFoundationSDK \
    -I/opt/PhysXSDK/pxtask/include \
    -I/opt/PhysXSDK/SDKs/PhysXAPI/deprecated

    The backslash sign is for proper escaping line breaks in makefiles. You don’t need that if you just enter these flags inline.

  3. Now let’s tell the linker where to find PhysX libraries. All of them are in just two directories. If you are on 32-bit machine change directory name from linux64 to linux32.
    -L/opt/PhysXSDK/SDKs/lib/linux64 \
    -L/opt/PhysXSDK/pxtask/lib/linux64
  4. Last thing to do is instruct the linker to link our program against PhysX libraries. To do so enter following flags:
    -lpthread \
    -lrt \
    -lPhysX3 \
    -lSimulationController \
    -lLowLevel \
    -lPhysXProfileSDK \
    -lPhysX3Extensions \
    -lFoundation \
    -lSceneQuery \
    -lPhysX3Common \
    -lPhysX3CharacterKinematic \
    -lPhysX3Vehicle \
    -lPhysX3Cooking \
    -lPhysX3MetaData \
    -lGeomUtils \
    -lPvdRuntime \
    -lRepX3 \
    -lPxTask

    It seems that order of these flags may have some influence on linking success. The above set works.

The file provided for this entry uses OpenGL and Glut libraries, so you need to provide following linker flags as well:

-lgl -lglu -lglut

Also make sure that you have these libraries installed.

Now spawn the compiler and enjoy your PhysX program running in your favourite OS!

For those who use Anjuta IDE or Autotools I attach configured Anjuta project: physx3-demo.tar.gz

Sources:
http://mmmovania.blogspot.com/2011/05/simple-bouncing-box-physx3.html?utm_source=BP_recent
http://forums.developer.nvidia.com/index.php?showtopic=6396
http://forums.developer.nvidia.com/index.php?s=21e9323c0ddf3f7d9d08cd96b9ba98ed&showtopic=6267&st=0

Posted on July 18, 2011 at 8:39 pm by Lubiluk · Permalink · 5 Comments
In: Uncategorized · Tagged with: , ,

HowTo: Setup PhysX SDK on Linux

Note: This article is about PhysX 2.8.1. A guide for PhysX 3.0 is here.

PhysXbyNV_Black_200Nvidia PhysX can be run under Linux, but unfortunately there is not documentation how to do it. Binaries are available (only 32bit) but that’s all what is given to Linux users. I will describe step by step how to setup and begin development with PhysX in Ubuntu with use of Eclipse CDT. Users of other distributions and editors will find here useful informations too.

Article covers installation of PhysX SDK 2.8.1 and compiling sample program on 64bit machine (Ubuntu x86_64). On 32bit systems it will require little less effort so I will mark the parts which can be omitted on that systems with “64bit:” prefix.

Installation

First thing to do is download PhysX package from this site:  http://developer.nvidia.com/object/physx_downloads.html
It looks like Nvidia doesn’t provide packages for linux any more (because of coming sdk 3, they say), but you can still find it on Internet by googling for: PhysX_2.8.1_SDK_CoreLinux_deb.tar.gz or PhysX_2.8.1_SDK_CoreLinux_rpm.tar.gz

When you have package ready, go to download directory, unpack and install all packages.  64bit users will need to do it from command line to force installation.

64bit:

sudo dpkg -i --force-architecture *.deb

Shared libraries are installed in version specific directory “/usr/lib/PhysX/v2.8.1/”, so we need to link them to “/usr/lib”.

sudo ln -s /usr/lib/PhysX/v2.8.1/libNxCharacter.so.1 /usr/lib/libNxCharacter.so.1
sudo ln -s /usr/lib/PhysX/v2.8.1/libNxCooking.so.1 /usr/lib/libNxCooking.so.1
sudo ln -s /usr/lib/PhysX/v2.8.1/libPhysXCore.so.1 /usr/lib/libPhysXCore.so.1

PhysX is now installed and we can try run some samples from Nvidia which are placed in “/usr/sbin/PhysX_Samples_2.8.1_FC4/Bin/linux/”. Note that not all samples will work. I don’t know why they didn’t pay attention to make sure everything works. Source code for samples are not available on Linux too. Sample that should work is for example SampleBoxes.

/usr/sbin/PhysX_Samples_2.8.1_FC4/Bin/linux/SampleBoxes

Compile own project

So, now we have working PhysX, let’s try to compile something with use of it. I will describe how to do it with Eclipse CDT. You can get a gcc comand as well in the next paragraph (Although, for explanation of parameters read this section).

Before start, on 64bit machines ensure that you have 32bit gcc extensions installed:

64bit:

sudo apt-get install g++-multilib lib32stdc++6

Create a new C++ Empty Project and go to its properties. Go to “Settings” in “C/C++ Build” section. We will configure g++ flags to compile project properly. In “GCC C++ Compiler” in “Preprocessor” add these “Definied symbols”:

LINUX, NX32, CORELIB, NX_DISABLE_FLUIDS

(Last one is needed to make physics simulation work. I think it’s some kind of bug in PhysX but I’m not sure why it happens. I’ve found solution for it on some Italian or Spanish site so I could not understand what it was about.)

In “Directories”  enter these paths:

/usr/include/PhysX/v2.8.1/SDKs/Physics/include

/usr/include/PhysX/v2.8.1/LowLevel/API/include

/usr/include/PhysX/v2.8.1/SDKs/Cooking/include

/usr/include/PhysX/v2.8.1/SDKs/PhysXLoader/include

/usr/include/PhysX/v2.8.1/LowLevel/hlcommon/include

/usr/include/PhysX/v2.8.1/SDKs/Foundation/include

/usr/include/PhysX/v2.8.1/SDKs/NxCharacter/include

64bit: In “Miscellaneous” add flag to “Other flags”

64bit:

-m32

This flag tells compiler to make 32 bit binary instead of 64.

Now go to “GCC C++ Linker” and in “Libraries” add libs:

dl, pthread, PhysXLoader

GLU, GL, glut

Second line of libraries listed above are for OpenGL and GLUT, you’ll need them if you’re going to compile source code that I will list below.

64bit: In “Library search path” should be:

/usr/lib32

64bit: Same as in compiler section add flag in “Miscellaneous”

64bit:

-m32

Ok, enviroment set up properly, let’s compile something and see how it works. Because there is no sample code from Nvidia to try I’ve prepaired one taken from SDK for Windows and modified it a little for easier compilation under Linux. Here are source files: SampleBoxes.tar

And here is entire CTD project with proper configuration: SampleBoxesCDT.tar

Compile, run, enjoy.

Command line

You may also compile these sources from command line with:

g++ -DNX_DISABLE_FLUIDS -DCORELIB -DNX32 -DLINUX -I/usr/include/PhysX/v2.8.1/SDKs/Physics/include -I"" -I/usr/include/PhysX/v2.8.1/LowLevel/API/include -I/usr/include/PhysX/v2.8.1/SDKs/Cooking/include -I/usr/include/PhysX/v2.8.1/SDKs/PhysXLoader/include -I/usr/include/PhysX/v2.8.1/LowLevel/hlcommon/include -I/usr/include/PhysX/v2.8.1/SDKs/Foundation/include -I/usr/include/PhysX/v2.8.1/SDKs/NxCharacter/include -O3 -Wall -c -fmessage-length=0 -m32 -o"SampleBoxes.o" "./SampleBoxes.cpp"
g++ -L/usr/lib32 -m32 -o"physx_test"  ./SampleBoxes.o   -lPhysXLoader -lGLU -lGL -lglut -ldl -lpthread

Documentation

Last, very useful thing to do is install PhysX SDK Documentation viewer. The documentation files in PhysX packages for Linux are taken from Windows literally, so they are in Microsoft’s “.chm” extension and cover installation and setup under Windows, but still it’s very useful. PhysX API is platform independ. In Ubuntu there is a nice “.chm” file viewer “gnochm”. Documentation main file is “/usr/share/doc/libphysx-2.8.1/PhysXDocumentation.chm”

Maybe some day we will get drivers from Nvidia that run PhysX on GPU and better support for Linux. In near future there will be release of 3.0 PhysX SDK. It will support 64bit architectures natively.

Posted on June 27, 2009 at 2:16 am by Lubiluk · Permalink · 14 Comments
In: Uncategorized · Tagged with: , , ,

Why Linux?

linux_logoThat’s a very common question. You may notice on this blog that I use Linux to most of my tasks. I would like to cover this subject to view some very nice advantages of this OS. I will not denigrate other (commercial especially) operating systems, that’s not the point. I hope to present Linux as a promising and useful OS.

So… why to use Linux?

First of all – because it’s free (as in freedom).  I can hear you saying “Oh, that’s it?!”, but think about opportunities that gives you free operating system. You are not dependent on any company standing behind your OS, you can do whatever you want with your software and hardware. It’s yours. End users, especially desktop computer users may not notice this as a big deal, but for developers and big software consumers it is really blessing not to be dependent on anybody, especially big companies.

In my opinion the most popular platform that runs various software should be a free platform (opposite to current situation). Thanks to this, progress in software development and computer science would be much faster than it is on closed platforms. That’s because when everybody works on an open platform then everybody cares about it and generally pushes it forward.

Imagine a situation that you want to write your own application. Fine, you can do it for every platform that gives you a compiler, but to run your own program on closed platforms first you have to buy this platform. The more programs you have for this platform the more dependent on company that distributes it you become. That’s of course great situation for this company, not for you. The situation touches not only developers but also consumers that use software dedicated for commercial platforms.

That was economical part of subject, now take a look at technical matters. Closed platforms are unchangeable, the only way to improve it is ask it’s producer for features or fixes and wait to see if your wishes will come true. When you work on free platform like Linux you can do improvements by yourself with no waiting or asking anybody, it’s your platform. You don’t have to pay someone to develop your software. You can even distribute entire operating system with your software if it’s needed.

Ok, that could be said about every free operating system. The thing that makes me pick Linux from other open OSes is it’s popularity and availability. In fact, Linux is the most developed free operating system. Of course there are other good OSes like FreeBSD or OpenSolaris, but these are popular for servers, on desktop there is no good hardware support. Linux works on almost every architecture and supports most of hardwares. It has support (not big but always something) from hardware manufacturers like Intel or Nvidia. It runs on servers, desktop computers, laptops, mobile devices and many other devices. Linux make use of every processor if it’s possible. That’s why it is good candidate to make some kind of standard out of it. Worth to say is that Linux is compatible with other POSIX compliant operating systems so usually it’s very easy to port programs from Linux to other free OSes and vice versa.

Finally, the thing that concerns end users. Sometimes you may hear phrases like “this will be year of Linux on desktops”. Actually Linux has reached the level when it runs really well on popular desktop computers and laptops. It runs well and offers plenty of nice features for everybody, from programming tools through office programs to multimedia players. Beside this Linux distributions have great software package managers like APT in Debian or Ubuntu. After some time of using that tools you never want to go back to Windows style messy installers.  Linux is chasing Windows with useful software and often offers even better features. Everyday more software producers consider writing for this platform. The only thing that is needed to make it the finest operating system is popularity. So start to use it and show your friends how cool it can be :).

I had a dream

Imagine how nice it could be if Linux was not only very popular on desktops so you have all useful programs like Photoshop on it but also was used as a gaming platform.  Open platforms works in this way that companies which are developing for it and using it are also building parts of the OS. So if open platform like Linux would be the most popular platform then it would be developed not only by one company like Microsoft but by all software and hardware producers. I don’t mean that everybody will give software for free. No, developers have to earn on their software but it is their interest to make the OS a bit better every the time.

Posted on June 24, 2009 at 10:39 pm by Lubiluk · Permalink · Leave a comment
In: Uncategorized · Tagged with: 

Hello world!

I think the default wordpress title for this post is just fine.

Here I start this blog. I will write here some of my cogitations, tutorials and whatever will come to my mind to write here. Articles will cover software development and other subjects connected with computer science.

I hope you’ll find this useful. Comments and feedback would be appreciated.

Posted on June 11, 2009 at 1:55 am by Lubiluk · Permalink · Leave a comment
In: Uncategorized