Pages

Saturday, 16 July 2011

Cloud Computing

Introduction

A definition for cloud computing is the use of multiple servers on a digital network as if they were one computer. The term is become more frequently used for anything that provides hosted services on the internet. A wide variety of services are already available on the cloud. Examples are Google Docs and Microsoft Sky Drive and on-line Office which provide similar tools to an offline office application. The introduction of cloud computing is becoming more and more common and some application developers are moving towards the cloud distancing themselves from the offline applications.

Advantages

Well advantages are easy to image. I think the most important one is the ability to access you work or application from anywhere given a good internet connection. As internet connections become more easy to get with the improvements of mobile networks, cloud computing can become the way to go. Cloud computing put most of the processing on the servers and thus allow for thinner clients such as newer generation mobile phones and tables to make use of such technologies. Nowadays mobile technology is powerful enough to run decent web browsers and thus make it possible to use cloud services.

Cloud computing brings the ability of platform independence. Although in some cases due to browser conflicts, this is just an illusion cloud services are mostly accessed through web browsers, so as long as your cloud app is compatible with the most common browsers, platform independence becomes less of an illusion. HTML5 should also help lower this gap as its introduction should help reduce 3rd party tools such as flash which may not be available in all device (apple ipads and iphone).

Another advantage of cloud computing is the fact that hardware and software need not to be managed. When you use a cloud service you only pay for what you use and need and upgrades are automatic, and scaling up or down is easier if your cloud is structured in the right way. The user of the cloud does not need to update his software repeatedly as the pp is not local. The app can be upgraded once from the cloud and all users are automatically updated.

Security is another important fact. Although Cloud services give the sense of less security, these systems seem to be quite secure and reliable. Sometimes they are even considered more secure than traditional systems, as they are more available and reachable and eliminate the need to manual print and display the data or sent it (by email) to others. These tasks can be a threat to privacy especially email, whereas access to that data directly through the cloud from anywhere is surely more secure than email.

Another advantage of using good and reliable Cloud provides is the no-need for backups. These providers ensure a high level of fault tolerance and take regular backups that ensure no data is lost. Usually these service providers can provide much better fault tolerance and information recovery than  other companies do.

Disadvantages

Although I think there are much more advantages than disadvantages to use cloud computing, One must also mention the disadvantages. The most obvious disadvantage is the reliance on a network connection. Cloud computing means no network, no nothing, slow network, frustrating slow work.

Another disadvantage to cloud computing is the connection of peripherals. Although the cloud is available from anywhere not all devices may be recognised by the cloud. Integrating devices such as bulk printers or normal USB devices can become much more difficult. If integration is done through a specific software connection, then although the cloud is accessible from anywhere, only those engines with the software installed can use those services.

Cloud computing may render huge benefits in the long term but may not be the cheapest solution to set up, especially for small scale businesses with a lower profit margin. Fortunately, cloud services are becoming cheaper as we speak and as they become more common, they become even cheaper.

A thing to consider in cloud computing is security. Earlier I mentioned that cloud computing is safe both in terms of security and in terms of availability and backup. Although the cloud can result in less data loss because of its frequent backup's, the fact that its servers are interconnected means there is a high risk for data when it comes to attacks and intrusions.

Conclusion

I think that in most cases cloud computing is the way to go. The idea of implementing an application that is available and functional to a wider range of devices is in itself intriguing . Not having to care about back ups and easier updates seem also good ideas to me. But anyway, before implementing a system, you might always want to weigh the pros and cons of your situation realising that the good of the majority might not necessarily mean your good.

Friday, 15 July 2011

Social Networks

Brief History

This week's post is very interesting as social networks are very common amongst net users. From the beginning of the internet and even before social networking was always present in the digital world. Social networking in the PC is the interaction of users using computer networks so the early Bulletin Board Systems can also be considered as Social networking tools. There were various attempts to create social networking sites, and some were very successful in their era. I don't remember any old social networking tools and I don't know how they  worked or their capabilities.

My earliest form of contact to these tools was MIRC with which I used to chat every now and then. I didn't use MIRC much since back then I only had access to a dial-up modem and using the internet was expensive. My real exposure to social networking started when I created a Hi5 account. In Malta Hi5 was very popular and nearly all of my friends had a hi5 account. Hi5 was more conform with the modern idea of Social networking and each user his own profile and virtual friends. Then Facebook popped up and most of my friends migrated to Facebook. I didn't want to switch to FB at first but when nearly all my friends switched I also created a profile. In the same period I tried MySpace, which at the time was very common especially amongst artists. More Recently I created Twitter and Linkedin accounts and Managed to make an account on Google+.

Social Networking

Modern social networking sites offer many interesting features such as photo and video sharing, photo tags, live chat and nowadays video and group video chats. Some of these web sites have a particular theme or purpose. An example is Twitter. This micro blogging site is mostly used to diffuse information. I don't use twitter that often, but when I am waiting for a particular news or information I usually go to twitter as information flows quickly there. When MySpace was more common, it was an idea place to go to look for information about your favourite artists and also listen to their music in case of musicians.

I consider myself a moderate social networking user as I like to use these services but not too much. I like the idea of sharing information over the internet, but sometimes I am a bit concerned. On tools such as Facebook, anyone can take you a photo and upload it to his profile and put your tag on it. This might not always be a good thing as your private life starts to disappear. There are however benefits of putting up a public profile. For example with Facebook you may keep in touch with friends that you no longer meet often and may also help you make new friendships. Linkedin is also a very common social network but focusses more on business networking which can expose it's users to potential employers.

Technological View

In terms of technology social networks are very interesting. As time passes competitors start to show up and thus major social networks  keep to improve. All social networks that rise amongst the others are destined to fall someday. Currently Facebook is doing pretty well and it is the world's largest social network. Apart from the profile and stream sharing, Facebook has a good layout and is constantly improving and updating. One thing that failed on the previous network MySpace was the ability of the users to create their own style. Since not all users are IT experts, lots of pages were created with erroneous code which might not be interpreted by all browsers, and some pages not readable by screen readers. Custom good looking professional layout is important to a social network such as FB. An interesting feature of FB is the auto tagging when an album is uploaded. Faces on the photos are recognised and tagged temporarily until confirmation from user. Recently Facebook is also rolling video chat to its users and word says that it is doing so in an attempt to counter Google+'s video features. For video chat Facebook uses Skype technology in another Facebook-Skype agreement. These networks already share some chatting features. Facebook Video chat is currently available to a limited number of users. Fortunately mine is available and I already tried it. I must say that it worked good as it should but it is nowhere as interesting as Google Hangouts on Google+.

A newly emerged, but still exclusive social network is Google+. This social network offers interesting features and new concepts. G+ introduced the concept of Circles where contacts are not all considered the same and therefore not given the same level of sharing. With this interesting feature, one could upload and show photos of Saturday nights to his friends without his family(other circle) being able to see them. This improves  the concept of privacy, if any exists on the internet. Another interesting feature is the Google hangout. People are allowed to join in a hangout and video chat, or text chat with a group of friends in a very cool environment. I managed to get invited in to Google+. I liked it a lot and I am very interested to see if these networks will be able to coexist like Facebook and Twitter or if one will crush the other like Facebook crashed MySpace. In my opinion G+ may be a valid competitor with FB, but currently all users seem to be computer experts or work in computer related environments. For Social network to become large it needs more normal casual users.

Another rumour is out saying that Microsoft are coming up with their own social network. Given how their previous attempts failed  (windows live spaces and windows live network) I am interested to see what are they up to.

A little Experiment

Recently I made a little experiment to try Some services offered by social networks and their connection to peripherals.  More exactly, I needed to video chat but had no webcam and I needed a quick fix. Having an android phone really helped, as I downloaded an App to make my phone work as an IP camera. Then I used a special ds filter to turn the IPcam into a sort of webcam. The experiment worked on local applications. For testing I tried Facebook and Google+. This virtual webcam was recognised and worked on skype and facebook video chat, but to my disappointment did not work on G+ hangouts or Google talk. My thinking was that if the cam is recognised locally and by Skype, it should be recognised by everything, well apparently I was wrong. Facebook video chat has a similar experience to video chat on Skype, obviously because they use the same technology. Later I tried Hangouts with a real webcam, and it is quite cool. I did not hang out with many users to test its capabilities, but with a few users it worked well.

Privacy Concerns

As social networks become more and more popular questions about their security and privacy start to arise. In my opinion one must be cautious as what to upload on social networks. Making too much information public on the internet might not be very good. You do not know how that information will be used and by who. Also some pictures might come to haunt you later on in your life or might be seen by people you wouldn't want them to. Some times websites like Facebook make photo sharing easy, but you might end up sharing photos that probably in your real life, you wouldn't. Although the new Social network G+ has features such as circles to limit the view of the posts, once pictures or posts are on-line, you have no control of what the other users might do with them. So I my opinion I would recommend the use trusted social network sites but the user should take special care of what to share, and now with G+ we can also include, with whom to share.

Monday, 4 July 2011

Mobile Phone Technology and Geolocation

Introduction

This is not the first time I am blogging about mobile phones and internet usage on Mobile Phones. There is a vast number of manufacturers providing powerful smart phones that are able to provide internet access. Most modern smart phone provide a comfortable view and use for surfing the web. The only problem is the internet itself. Most web pages do not fit the small screens on mobile phone and therefore they are not easily accessible. Fortunately, major companies are providing mobile versions of their services or mobile applications that allow smoother viewing of the sites content. The mobile version of a website is becoming more and more popular nowadays as people are moving towards mobile devices.

Although there are various different mobile brands, most mobiles use similar operating system, with some manufacturers adding a touch of their own. The most common OSes are Apple's IOS, Symbian, RIM, Windows Phone and Android. Most of the manufacturers are moving towards Android and Windows Phone. Even Nokia decided to go towards Windows Phone instead of continuing to develop their Symbian interface.

As mobiles become faster and better, so does their internet browser. Most mobile phones already have a browser that supports many HTML 5 features. HTML 5 was identified by many as the way to go for the future of the internet. Most smart phone also make use of Geolocation features that find the exact location of the device using a GPS system. For this pot I experimented with some geolocation API and also I decided to use some Google map APIs as well.

Using the Geolocation Features

Getting a Geolocation is easy. The following code shows you how to get the longitude, latitude and time of location of a device using geolocation.

<script type="text/javascript">
navigator.geolocation.getCurrentPosition(userLocated, locationError);

function userLocated(position){

var lat = position.coords.latitude;
var long = position.coords.longitude;
var timeOfLocation = position.timestamp;
document.write(lat+"<br/>"+long+"<br/>"+timeOfLocation);
}


function locationError(error){
alert(error.code);
}

By calling navigator.geolocation.getCurrentPosition(userLocated, locationError); the function userlacated is called if a location is found, while locationError is called if an error occurs.The function userLocated has position as parameter. From this parameter, the coordinates and other data can be obtained.
This Link should return the geolocation of the device http://mark-galea.webs.com/Geolocation.html.

Using Google Maps together with Geolocation

After a bit of research I decided to use google maps. To display the map with the current location, is easy as the code is provided by google in a way that copy and paste does it all. Then I decided to display the name of the location of the coordinates being displayed. This was slightly harder for me as I took the wrong approach.

While reading the google maps documentation I read that I needed to make an XML http request to get the data and display it. This worked only in internet explorer locally. This is because Chrome does not allow requests from local files. When I uploaded the file to a web server, the code didn't work on any browser. This was due to the limits in the cross-domain requests that do not allow requests from different domains. I was stuck for hours trying to find a solution for the problem, until I realised I was looking at the problem the wrong way. Looking further in the documentation I found that Google created JavaScript API for usage on the client side and what I was doing was only required for some server side processes.

Code for obtaining an address from coordinates and vice versa can be found in the documentation. I didn't notice immediately what I was doing wrong because of my lack of experience in some JavaScript features which I never used before. Also the Google maps documentation I was reading only states that there is another approach for JavaScript client side users, in a small paragraph , which I missed because of my habit to just skim through documents. I must say the tools provided by Google make it very easy to display items on the map. Since I read how to extract addresses using XML requests I will also show some code to get coordinates from addresses using an XML HTTP Request.

A get request to the following address returns an XML file containing a list of possible addresses and coordinates.

http://maps.googleapis.com/maps/api/geocode/xml?address=Valletta,Malta,+CA&sensor=true

<GeocodeResponse>
  <status>OK</status>
  <result>
   <type>locality</type>
   <type>political</type>
   <formatted_address>Valletta, Malta</formatted_address>
   <address_component>
    <long_name>Valletta</long_name>
    <short_name>Valletta</short_name>
    <type>locality</type>
    <type>political</type>
   </address_component>
   <address_component>
    <long_name>Malta</long_name>
    <short_name>MT</short_name>
    <type>country</type>
    <type>political</type>
  </address_component>
  <geometry>
   <location>
    <lat>35.8977900</lat>
    <lng>14.5141060</lng>
   </location>
   <location_type>APPROXIMATE</location_type>
   <viewport> 
   <southwest>
     <lat>35.8887508</lat>
     <lng>14.4980986</lng>
   </southwest>
   <northeast>
     <lat>35.9068282</lat>
     <lng>14.5301134</lng>
   </northeast>
  </viewport>
  <bounds>
   <southwest>
    <lat>35.8924169</lat>   
    <lng>14.5042573</lng>
   </southwest>
  <northeast>
   <lat>35.9036630</lat>
   <lng>14.5207773</lng>
  </northeast>
 </bounds>  
</geometry>
 <partial_match>true</partial_match>
 </result>
</GeocodeResponse>

An XML Similar to the one above is obtained from the request. By reading through the XML data can be taken. The above example shows results for the address Valletta, Malta. There are other approaches other than XML, in fact Google recommends JSON. This approach cannot be used however in javascript as corss-Domain Requests are not allowed and therefore the HTTP Request is ignored.

Google Created Javascript APIs which include methods that return these results without needing to make any request.


function getLocaFromCoord(latlng)
{
var geocoder = new google.maps.Geocoder();
   geocoder.geocode({'latLng': latlng}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results[1]) {
          map.setZoom(11);
          marker = new google.maps.Marker({
              position: latlng,
              map: map
          });
          infowindow.setContent(results[1].formatted_address);
          infowindow.open(map, marker);
        }
      } else {
        alert("Geocoder failed due to: " + status);
      }
    });
}

The function above puts a map marker and displays a particular location, including, its name, given the exact coordinates.

function getCoordFromAddress(address)
{
 var geocoder = new google.maps.Geocoder();
    if (geocoder) {
      geocoder.geocode({ 'address': address }, function (results, status) {
         if (status == google.maps.GeocoderStatus.OK) {
             getLocaFromCoord(results[0].geometry.location);
         }
         else {
            alert("Geocoding failed: " + status);
         }
      });
   }
}

The Function above searches for a particular address, and gets, its coordinates if found. Then calls the previously explained function to display the coordinates as a place on the map.

Below are some screen shots of a small website that I made. This site, identifies your geolocation and displays it on the map. If the location is wrong, you can type your exact address and your location should be displayed on the map.



The Website is on-line at this link: http://mark-galea.webs.com/MapsAPI.html

The Site is styled to work on most mobile phones, but I only tested it on an Android Desire S and it worked perfectly showing my exact location and displaying its name in the info window.

Conclusion

Working with geolocations and Google maps was quite entertaining for me. Although I got confused at first, Google maps are quite easy to work with and a lot of help is provided on-line, with a lot of code ready made. Geolocation can be uses to make location based services which are much more accurate than those used by ip locations. This is improved especially in mobile devices as these are usually equipped with GPS devices that offer very accurate positioning. Location data however can be used badly in the wrong hands so attention should be taken before allowing any location to be given.

Thursday, 23 June 2011

HTML 5

Introduction

Hi all, this I will not talk about second Life, but I will focus on newer web technologies. This Week's topic is about HTML 5 and CSS 3 and I will talk about, compatibilities and I will also do some sample code. HTML 5 is not a completed language and not all browsers support its features. Some browsers show better capabilities than others in this task.

Browser Wars

The wars between browsers is always on and as time passes browsers improve their HTML 5 compatibilities to offer better support than others. Currently all major browsers offer quite good HTML 5 support with IE9 having the least ratings from the other browsers. The website http://www.findmebyip.com/litmus/ shows a list of browsers together with their compatibilities. As it can be seen Google's Chrome and Apple's Safari seem to do a pretty good job. In fact both Google and Apple give a lot of importance to this technology in their development. Chrome's quick and seamless updates continue to improve the product and to add more and more HTML 5 support.

The website http://html5test.com/ provides a list of your browsers supported and unsupported features together with an overall rating. Well we all  did this test in Web Technologies class and the first thing I noticed is the huge difference in rating between chrome and IE 9. Chrome (12.0.742.100) currently scores 328/450 while IE9 only scores 141/450. I also notice that my browser had problems using WebGL technology, something which my friend's Chrome browsers did not.

I was a bit disappointed at first and did not know what cause the problem. The new browsers promise that a simple install of the browsers will include all features, but this was not exactly true in my case. I immediately though it was a problem with my graphic's card driver, and I was right. I have an ATI HD Raedon Graphic Card, which is not Recent, but not very old neither. I found several articles about ATI chips not supporting WebGL, and from the ATI Website I downloaded a new driver that supports this technology. It seams that ATI issued newer drivers to all chips considered as non legacy. These new drivers add support to WebGL. I tried WebGL on several other PC's with the chrome browsers. All new graphic cards seem to do pretty well but graphic cards considered as Legacy are not supported. Finally I was able to view some WebGL Demos online.

Differences between HTML4/CSS2 and HTML5/CSS3

HTML5 Introduces a lot of new features but some old tags will be no longer supported and newer tags must be used.  HTML5 adds support for the Header and Footer tags that can display information in the web document. Other new tags provide better structure to the document. Other interesting elements are the media elements and the canvas element. These tags are new in HTML 5 and offer better media support that in the past was only available through web extensions such as adobe's flash player.

Media elements illustrated on the website www.w3schools.com include:

TagDescription
<audio>For multimedia content, sounds, music or other audio streams
<video>For video content, such as a movie clip or other video streams
<source>For media resources for media elements, defined inside video or audio elements
<embed>For embedded content, such as a plug-in

These elements allow you to play media directly from the browser. The supported browser codecs may vary although HTML5 provides for a set of standard codecs that should be supported. An even more interesting new element is the canvas element. This element allows programmers to draw things using Scripts. I used to do a similar thing using the Canvas in Java Applets, but working totally in the web browser is another thing. Speaking about Applets, the Applet tag will no longer be supported but applets can still be used by using the object tag and adding the right mime_type in the attribute type.

CSS3 is completely backwards compatible and therefore no old code must be changed. CSS3 provides new styling such as:
  • Selectors
  • Box Model
  • Backgrounds and Borders
  • Text Effects
  • 2D/3D Transformations
  • Animations
  • Multiple Column Layout
  • User Interface

New features about borders are introduced. The feature border-radius produces round corners. It has been around for a while in some browsers although IE only stared supporting it on version 9. To make this feature in CSS2 you would have to use several images to obtain the rounded features and than place them on the corners. Well most border features seem to be supported by all major browsers although some features may be still in a testing phase.

Another interesting feature in CSS3 is the text shadow. Although still not supported in IE9, this feature will make part of the new CSS standards. Without this feature shadow could only be used by suer imposing two text lines.

The most interesting parts of CSS3 are surely the 2D and 3D transformations that allow you to manipulate objects but changing their 2D and 3D positions on the screen. This includes rotating, skewing and scaling objects. Most of the features are still a work in progress but on the W3schools.com you can find several examples of using the already  supported tags.

Together with CSS3 and HTML5 new JavaSript features are also added. these new features include:
  • Web Storage
  • Web SQL Storage
  • Offline application cache
  • Web Workers
  • Web Sockets

Some Hands On

The task for todays week is to use two new fetures of:
  • HTML5
  • CSS3
  • new JS
Well in this exercise  I wanted to try so many things, but I had little time, so I decided to make some code to try various features, without actually caring about the website looks and uses. My idea was to try the new features that I would had used earlier in this course if they where supported. All my code works in Chrome but was not tested in other browsers. since some tools use the webkit, they will probably work only on chrome and safari.

To start with I decided to use the canvas elements, so I made various canvas elements in my HTML Body.


<h1>HTML5 Tryout</h1>
<canvas></canvas>
<canvas></canvas>
<canvas></canvas>
<canvas></canvas>
<canvas></canvas>
<canvas></canvas>

The first thing I wanted to try out is the border radius that produces round corners. In the first weeks exercise, I remember that I could not do it in IE 8 and I had to use several pictures to do it. Now it can be done in a single line of CSS.

border-radius:25px;

Then I decide why not add some shadow to the canvas so I used the box-shadow property 
box-shadow:10px 10px 5px #888888; where
box-shadow:h-shadow v-shadow colour
h and v shadow are the positions of the shadow and can be eithier positive or negative.

Finally I added a border to the canvas and added the colour orange. Then I said, why not use some new CSS transformations. The code below shows my entire CSS.

<style type="text/css"> 
canvas
{
width:100px;
height:75px;
border-radius:25px;
box-shadow:10px 10px 5px #888888;
background-color:orange;
border:1px solid black;
}
canvas:nth-child(odd)
{
-webkit-transform:rotate(0deg);
-webkit-animation-name: myfirst;
-webkit-animation-duration: 2s;
-webkit-animation-timing-function: linear;
-webkit-animation-delay: 0s;
-webkit-animation-iteration-count: infinite;
}

canvas:nth-child(even)
{
-webkit-transform:rotate(30deg);
-webkit-animation-name: mysecond;
-webkit-animation-duration: 2s;
-webkit-animation-timing-function: linear;
-webkit-animation-delay: 0s;
-webkit-animation-iteration-count: infinite;
}


@-webkit-keyframes myfirst 
{
0%   {-webkit-transform:rotate(0deg);}
20%  {-webkit-transform:rotate(10deg);}
40%  {-webkit-transform:rotate(20deg);}
60% {-webkit-transform:rotate(30deg);}
80% {-webkit-transform:rotate(20deg);}
100% {-webkit-transform:rotate(10deg);}
}
@-webkit-keyframes mysecond
{
0%   {-webkit-transform:rotate(30deg);}
20%  {-webkit-transform:rotate(20deg);}
40%  {-webkit-transform:rotate(10deg);}
60% {-webkit-transform:rotate(0deg);}
80% {-webkit-transform:rotate(10deg);}
100% {-webkit-transform:rotate(20deg);}
}

I decide to use the new selectors features of CSS to choose the odd canvases and the event canvases separately.  I created key frames with the rotation transformation at different angles in different percentages of the key frame. When selected, the canvas objects are assigned the appropriate keyframe, the duration of the animation, the timing function and the iteration count. In this example the objects keyframe duration is set to two seconds and iterations are infinite. This way the animation never stops.

Now that we have the canvas all set up, why not draw on it. I decided to draw on all even canvas objects. Drawing in Java Script is not easy and requires some thought. The code below shows some javascript.

var obj= document.querySelectorAll("canvas:nth-child(even)");

for (var i = obj.length >>> 0; i--;) { 
var ctx=obj[i].getContext('2d');
for (var x = 0.5; x < 500; x += 20) {
  ctx.moveTo(x, 0);
  ctx.lineTo(x, 375);
}
for (var y = 0.5; y < 500; y += 20) {
  ctx.moveTo(0,y);
  ctx.lineTo(375, y);
}

ctx.strokeStyle = "red";
ctx.stroke();
}

The function document.querySelectorAll() retrieves a list of objects and puts them into the obj variable. In this case the objects are all canvas elements. Only the even canvas elements are selected. A for loop is used to iterate through each object. for each element, a ctx variable is used to store the 2D context of the canvas. Here you can draw and it will become cisible on the canvas.There are various objects that can be drawn but I decided to draw a grid. To draw a grid you must first learn how to draw a line. This is easy, and only two functions are needed. the function moveTo() is used to select the initial drawing position. This function needs the x and y coordinates. The second function LineTo also takes the x and y coordinates and draws a line from the initial starting position to the given coordinates. Using these functions, the lines are drawn and kept in memory, but are not final and therefore not visible. The strokeStyle property sets the stroke colour and the stroke() function draws the line. To create the grid I used two for loops, one to draw vertical lines and another to draw horizontal ones.

Finally I wanted to try the output tag and the local storage features offered by javascript.
The following code shows how I used them.

<script type="text/javascript">
  window.localStorage['value'] =document.querySelectorAll("canvas").length;
</script>
<p>There are currently <output id="result"></output> Canvas objects on the screen</p>

<script type="text/javascript">
 document.getElementById('result').textContent = window.localStorage['value'] ;
</script>

The context in which the code was used does not really make any sense, I just wanted to try out the features. In n initial script, I store the value of the number of canvas elements on screen in a local storage called 'value'. Then I display a paragraph of text with an empty output tag inside. Later on in the code I run another script that gets the number stored in the local storage and injects it in the output tag, which is then displayed in the paragraph.

The image below shows a screenshot of the final output of the code.

Below is a link to my website where I uploaded this page.

Conclusion

I found using HTML5 features much easier than expected, although I did not perform any particularly difficult tasks. HTML5 really adds something to the web and is much more powerful than its predecessor. With the new styling and scripting, anything can be done pretty much with HTML 5 eliminating the need of other external tools. I see this as a good thing especially for the users that will only need to download a browser and nothing more. Lets hope HTML 5 is finished earlier than expected so we can start benefit from it's features.

Thursday, 16 June 2011

Further into Second Life

Introduction

This week's post will be about some more advanced objects with second life and about SL's ability to connect people all over the world.

In this post I will talk about:

  • Communicating with other SL users which are abroad
  • Building a Notecard  giver
  • Building a Post Box system
  • Building an object that interacts with a Web Page


Communicating on-line

 In the last lesson a student was in Costa Rica for a holiday and decided to take the opportunity to make a little experiment with us. The student joined the lesson using Skype to make a video chat with the class. It was interesting to see how today's technology allows visual chat from all over the world.

In a second part of the lesson, all students logged to Second Life including the student in Costa Rica. We tried to do a lesson for building objects. All students teleported to a sand box where the lecturer showed us different objects and SL scripts. Later on in the lesson, we travelled to different SL worlds to further explore the game. Seeing how easy people can communicate over from different places using SL shows the communicative power of this game.

Building a Note Card Giver

The note card giver is an object that dispatches note cards to SL Avatars. There are various types of Note Card  givers. Some give note cards to avatars on touch, while others do it when an avatar passes near by. In this case I chose to give a note card to every avatar passing by. The Code Below shows how the Note Card giver works.

string notecard = "Note1";
integer freq = 1;
integer maxList = 100;
list given;


default
{
    state_entry()
    {
        llSensorRepeat("", "",AGENT, 20, PI, freq);
        llSetText("", <1.0, 1.0, 1.0>, 1.0);
    }
 
    sensor(integer num_detected)
    {
        integer i;
        key detected;
     
        for(i=0;i<num_detected;i++)
        {
            detected = llDetectedKey(i);
         
            if( llListFindList(given, [detected]) < 0 )
            {
                given += llDetectedKey(i);
             
                llGiveInventory(detected, notecard);
                if (llGetListLength(given) >= maxList)
                {
                    given = llDeleteSubList(given,0,10);
                }                              
            }
        }              
    }
}


The string variable notecard holds the name of the note card that will be passed to the avatar. The integer frequency holds the number of seconds of intervals between each sensor checking. maxList is an integer that holds the number of avatars that will be stored in a list of already contacted avatars. The object starts by calling the function  llSensorRepeat() on state entry. This function causes a sensor to check for avatars every second.

In llSensorRepeat("", "",AGENT, 20, PI, freq) 

AGENT is a mask that allow the sensor to locate avatars through SL Legacy Names
The number 20 is the number of meters the sensor 
PI is the arc of the sensor. PI means that the sensor works 360 degrees.
freq is the number of seconds of each interval of the sensor.

 When the sensor detects something the function sensor(integer num_detected) is called. The function uses a for loop to go through all detections. When an avatar is detected, his name is checked in a list of previously detected avatars, to avoid giving the note card to the same avatar all over again. If the avatar is new, his name is added to the name list and the avatar is given a notecard. llGiveInventory() passes the notecard to the avatar. Finally the function checks the length of the list using the llGetListLength() function. if the function exceeds the maximum number of names, llDeleteSubList(given,0,10); delete the first 10 names in the list. This note card giver is not ideal in a crowded place as 100 names is not a lot, and you would risk the note card giver to keep trying to send note cards to the same avatar. The note card that will be handed to the avatar must be placed in the contents of the card giver.

For the note card giver object a used a thin square prim with a white texture. The image below shows the card giver passing a note card to an avatar.


Building a Post Box System

The post box system is a system designed to pass messages to its owner. In this case I decided to let avatars drag notecards into the postbox such that they can be received by my avatar. The post box object is made up of a cuboid base, a semi circular face. The post box can be seen in the image below.


The code below shows the script of the post box system.


default
{
    state_entry() {
        llAllowInventoryDrop(TRUE);
    }
    touch_start(integer total_number) {
        llSay(0,"Create a notecard and drop it into the mailbox");
    }
 
    changed(integer mask) {
        if (mask & (CHANGED_INVENTORY | CHANGED_ALLOWED_DROP)){

            integer i;
            for (i=0; i<llGetInventoryNumber(INVENTORY_ALL); i++) {
                string name = llGetInventoryName(INVENTORY_ALL, i);
                integer type = llGetInventoryType(name);
                if (type != INVENTORY_SCRIPT) {
                    integer perms = llGetInventoryPermMask(name, MASK_OWNER);
                    if ((perms & PERM_TRANSFER) == PERM_TRANSFER &&
                        (perms & PERM_COPY) == 0) {
         
                        // keep track so you don't thank someone for a
                        // notecard that someone else gave you!
                        llSay(0, "Thanks for the "+name);
                         llGiveInventory(llGetOwner(), name);
            llRemoveInventory(name);
                    } else {
                        llSay(0, "Sorry, "+name+" isn't nocopy, trans");
                        llRemoveInventory(name);
                    }
                }
            }
        }
    }

On state entry, the object calls  llAllowInventoryDrop(TRUE); to allow objects to be dragged in the post box system. On touch the avatars are instructed to create a note card and drop it into the post box using the llSay Method. Dragging something in an object calls the changed event. This event takes in a mask that when compared to other masks, the change can be identifies.

"if (mask & (CHANGED_INVENTORY | CHANGED_ALLOWED_DROP))" checks for changes in the inventory and the changed allowed drop state. The function then loops for items in the inventory of the object. If the object is not a script the inventory mask of the ovner of the object with respect to the item is obtained. If the object dragged is not a copy, it is given to the owner of the post box and then removed from the post box. If the item is a copy it is not copied to the owners inventory, but it is removed immediately.

Building an object that interacts with a Web Page

For interacting with a web page I created a flat square prim that returns the number of SL sign-ups. This value is obtained from a web page. The code below shows the script of the object.

string SL_STATS_URL = "http://secondlife.com/httprequest/homepage.php";
key gRequestid;

default
{
    touch_end(integer p) {
        gRequestid = llHTTPRequest(SL_STATS_URL, [HTTP_METHOD, "GET"], "");
    }
    http_response(key requestID, integer status, list metadata, string body) {
        if (requestID == gRequestid) {
            list lines = llParseString2List(body, ["\n"], []);
            integer i = llListFindList(lines, ["signups"]);
            llSay(0, "There are currently "+llList2String(lines, i+1)+
                     " signups");
        }
    }
}

On touch the function llHTTPRequest() sends an http request and returns a request ID that identifies the request. On the event http_response, if the request id of the response is that requested, the lines of the returned request are inserted in a list. Lines are obtained using the function  llParseString2List() that parses a sting into a list of strings given the split parameters, in this case, a space of a carriage return. Note that the web page http://secondlife.com/httprequest/homepage.php returns several values regarding SL statistics.  llListFindList() searches through a list to compare a particular string and returns the index of that list position if found. In this case we are looking for the string Sigups. Finally the object uses llSay to output the number of signups. This number is the next in the list so llList2String(lines, i+1) is used to recover it, where i is the position os the string "sigups" in the list.

Conclusion

Advanced scripting in SL can become quite complicated as the various pre-existing methods and events must be explored before creating an object. This involves a great deal of time, which in my opinion is too much to spend on a game. Fortunately most objects can be found pre-existing on the net, and with little modification, they can be manipulated to satisfy the users needs. 

Wednesday, 8 June 2011

Creating Basic Objects in SL

Introduction

In last week's post I talked about creating objects in SL and tried to create some complicated ones. I did not however try to create objects requested for my degree, instead I took the opportunity to take a look into second life and programming in SL. Well from this week on I will try to create several objects starting with the very basic objects such as a chair. This post will cover:
  • Building a chair on which the avatar can sit properly
  • Building an object that responds to commands
  • Building an object that can send emails

Building a chair

Building a chair in SL is not very hard but aligning objects is. To create the chair I decided to create a cubic prim to create a chair leg. Then I extended the prim to a thin and long cuboid form to resemble a chair leg. I made four copies of the prim and tried to align them. Aligning in SL is difficult and requires some patience. There are external tools that can be used to create and align objects in SL but I chose to stick to the standard SL viewer tools.

The picture below shows a chair leg.


This picture shows four chair legs being aligned.

Creating the bottom of the chair is easier. Only one flat prim is required and is placed on the aligned legs. The back of the chair is made up of another flat prim placed vertically on the chair base. All object are then linked together. Finally I chained the chair colour to brown.

The picture below shows the last version of the chair.


The chair has also some scripts to allow the avatar to sit properly on it. To create the script I used the select face feature that allow the user to select a face on a group of linked prims. On this face I created the script below.

default
{
    state_entry()
    {
   llSitTarget(<0.0, 0.0, 0.1>, ZERO_ROTATION);
    }
}


The llSitTarget() function requires a vector where the avatar will sit and the rotation of the avatar. With the given parameters the avatar sits correctly i the middle of the chair. The picture below shows the avatar sitting on a chair.


Building an object that reacts to commands

In last weeks post I created a car that moves forward and backward when the avatar touches it. This week I decided to make something easier but something that works as it should. For this purpose I decided to create a light bulb that when touched lights on and off.

The bulb is made of a cylinder to recreate the bulb base and a sphere to form the bulb top. Both prims are linked together. The prims have a plain texture different from that of the chair. The sphere part has a 36% transparency to make the bulb look more real. Both objects have scripts to light the top part of the bulb.

The script for the sphere part:

default
{
    state_entry()
    {
        llListen(989,"Cylinder",NULL_KEY,"On");
        llSetColor(<0.5,0.5,0.5>, ALL_SIDES);
    }

  listen( integer channel, string name, key id, string message )
    {
         state On;
    }
    touch_start(integer total_number)
    {
       state On;
    }
}

state On 
{
     state_entry()
    {
        llListen(989,"Cylinder",NULL_KEY,"On");
        llSetColor(<1.0,1.0,0.0>, ALL_SIDES);
    }
    
  listen( integer channel, string name, key id, string message )
{
    state default;
}

    touch_start(integer total_number)
    {
       state default;
    }
}

The Prim has two states, the default state and the on state. Both states have similar code. On state entry in the default state, the script starts listening on channel 989 for an object called Cylinder to say the message On. In case this occurs the listen method is invoked. This method sets the prim's state to On. The function  llSetColor(<0.5,0.5,0.5>, ALL_SIDES); sets the prims colour. It takes two parameter, the first is a vector that represent the colour in RGB form, and the second parameter is the side number or all sides. The vector used for colour does not take the RGB colours are the normal integers we are normally used to, but uses a sum to render the integer to floats less than 1.0. To change an RGB colour to this type, you need to divide it by 255. The vector <0.5,0.5,0.5> is the LSL colour equivalent to (128,128,128) in the normal RGB format where the 0.5 is rounded from 0.502. The state has another event called touch start that changes the state to On.

The State On is similar to the default state, but instead changes the colour to yellow rather than grey. this state also listens for messages thrown by the Cylinder Object. When the listen event is invoked, the default state is triggered and the bulb is switch off and set back to its greyish colour. Touching the bulb in the On state also switches it off (by setting the default state).

The code for the Cylindrical part is simple. Up on touch the object throws the llSay method to send the message On. The message is sent on the channel 989, which is the same channel the cylindrical object is listening on. This way a message is sent between the two prims and the bulb is switched on and off.

default
{
    state_entry()
    {
    }

    touch_start(integer total_number)
    {
       llSay(989,"On");
    }
}

The default bulb state. The bulb is off.


The On bulb state. The bulb is On.

Building an object that can send emails


For this exercise I decided to create a flat prim that listens to what avatars say. Depending on what they say a mail can be sent. The code below shows the script for the prim.

default
{
    state_entry()
    {
        llListen(0,"",NULL_KEY,"");
    }

     listen( integer channel, string name, key id, string message )
    {
    string messagetype = llGetSubString(message,0,4);
    string messagestring = llGetSubString(message,5,-1);
    
    if (messagetype == "mail:")
    {    
    llEmail( "mail@hotmail.com", "Message From SL", messagestring);
    }
    }
}

This prim has only one state. On state entry the prim starts listening for what avatars say. When an avatar says something the message starts listening. When the message starts with "mail:", the rest of the message is sent by email. In the listen event, the function  llGetSubString(message,0,4) gets the first four characters of the messages the avatars say. This string is put in the variable messagetype. The rest of the string is put in the variable called messagestring. If the message type is equal to "mail:" the message string is sent by mail. E-mails can be sent using the llEmail() function. This function takes mail address, subject and message as parameters.

Conclusion

Scripting in LSL is not easy, especially when dealing with rotation and vectors. Fortunately a lot of examples can be found on the Second Life Wiki. A lot of material is available online and examples can be found for practically everything.  I find LSL to be most interesting part of SL. This week I focused more on the listen function as it is very interesting how objects can interact with other objects and with avatars.

In general Building object in SL takes time. Aligning and resizing objects is not easy as it should be. Building the object visuals takes a lot of time but with the help of external tools, these procedures can be made easier. With the addition of scripts SL become a powerful social tool where an avatar interacts with a new world.