You are currently browsing the tag archive for the ‘lsl’ tag.

Anyone who has tried creating an opening door in Second Life will no doubt have found that it is surprisingly tricky. In this post, I’ll describe a way of doing it that lets you build a door which opens, can be linked to other objects (such as a building!), and which will still function correctly when the building that it is linked to is rotated — if you have attempted to create doors before, you will no doubt already be aware of the problems that can arise with each of
these.

Creating a reliable opening door requires a mixture of a specially constructed prim, and a script. Let’s start with the prim.

Create a cube block.

Set the Start Cut parameter to 0.125 and the End Cut parameter to 0.625. You will notice that the pivot centre of the door is now at one edge of the visible part, instead of directly in the middle. This is the key (!) to the way that the door will work — we can now rotate the door very simply, and it will rotate around this hinge point.

Resize the result to something suitable for a door, making sure that you keep the pivot centre on the upright edge of the prim.

Basic door prim

Note that when you texture the door, the number of horizontal repeats will need to be set to 2, because only half of the prim is visible. Once you apply a texture you will this will become obvious, as the following pictures should make clear:

Door with unadjusted texture
Door with adjusted texture

Now for the script. To make sure that the door works correctly regardless of the angle to which it might have been rotated, we must use the Local rotation rather than the global rotation. We will use a variable to keep track of whether the door is open or closed — the only thing to be careful about here is that you must make sure the door is in the closed position at any time when the script is reset.

integer isOpen = FALSE;
float rotateBy = 0.8;
openclose() {
 if (isOpen)
 {
  llSetLocalRot(llEuler2Rot(<0,0,-rotateBy*PI_BY_TWO>)*llGetLocalRot());
  isOpen = FALSE;
 }
 else
 {
  llSetLocalRot(llEuler2Rot(<0,0,rotateBy*PI_BY_TWO>)*llGetLocalRot());
  isOpen = TRUE;
 }
}
default
{
    touch_start(integer total_number)
    {
        openclose();
    }
}

Close the build dialog, and touch the door a couple of times — it should open and close sensibly.

It is now possible to link the door to a building, and the door should continue to work properly. The only thing you must be careful about is that door must not be the root prim. If the door is made the root prim, when it rotates it will rotate the rest of the building with it! If the door is a child prim, it will only rotate itself.

For a more sophisticated door script, check out the Deluxe Door on the LSL Wiki site:

Library Door

An alternative is the sliding door. This doesn’t need a special prim — just size a normal cube into the size you want for the door, and use the script that you will find below (but read the rest of this first).

The slideBy amount is the amount by which the door will slide when it opens. Usually you will want this to be something a little smaller than the width of the door. This should leave part of the door visible, assuming, of course, that it is sliding into another prim.

We don’t need to use local co-ordinates for this door — the position is always local. However, you need to check which direction the door will slide in. This will normally be either the X or Y axis, depending on which is the width of the door. Be careful about rotating the door after adding the script, but before linking the door.

For example, here is a rough draft of a door. As you see, it is aligned so that it should slide along the X-axis (the red arrow).

Basic sliding door

If I rotate the door through 90 degrees, it now needs to slide along the Y-axis (the green arrow) and I will need to change the script accordingly.

Rotated sliding door

Once the door has been linked in place, you can rotate the entire object, and the door will still move in the correct direction in relation to the rest of the object.

Here’s the script, set to move along the X-axis.

integer isOpen = FALSE;
vector originalPos;
float slideBy = 1.5;
init()
{
    originalPos = llGetLocalPos();
    vector size = llGetScale();
    // Set up the amount to move by. Use size.y instead of size.x
    // if you want to slide along the y-axis.
    slideBy = size.x - 0.2;
}
openclose()
{
  if (isOpen)
  {
    llSetPos(originalPos);
    isOpen = FALSE;
  }
  else
  {
    llSetPos(<originalPos.x + slideBy, originalPos.y, originalPos.z>);
    // To move alon the y-axis, use this instead:
    // llSetPos();
    isOpen = TRUE;
  }
}
default
{
    state_entry()
    {
        init();
    }
    on_rez(integer param)
    {
        init();
    }
    touch_start(integer total_number)
    {
        openclose();
    }
    changed(integer change)
    {
        // When the links change, reset the script
        // so that we pick up the changes.
        if (change & CHANGED_LINK)
        {
            llResetScript();
        }
    }
}

This is going to be a long one. Get yourself a cup of coffee first.

What is a HUD? If you have to ask that question, you probably won’t get much from this article, but HUD is an acronym of Head-Up Display, and allows creators in Second Life to add a user-interface to gadgets.

They are created from prims just like any other user-created objects in Second Life, but they are only visible to their owner, and always appear ‘flat’ against the screen. If you’ve used any gadgets in Second Life, you will almost certainly have come across them.

For example, here is the popular blogHUD, for making blog postings from within Second Life:

blogHUD

When I started trying to create HUDs myself, I found that there was very little information about how to go about it, and I struggled for a while with even the simplest things. Now that I think I know what I am doing(!), I thought I would post a blog passing on my hard-won information!

In this post, I’ll show the basic steps of creating a HUD, and point out some of the pitfalls and ‘gotchas’ that you are likely to encounter along the way.

Are you sitting comfortably? Then I’ll begin…

The first thing to do, of course, is to decide what our HUD will contain. Because of the limitations of SL, it is not easy to include any kind of output in the HUD (with some ingenuity it can be done, but that is beyond the scope of this blog), so our HUD will basically be restricted to having some buttons to push.

For the sake of an example, we are going to create a HUD which allows the user to scan the area for other avatars, and to ‘poke’ (via chat) one of those avatars. Not very exciting, I know, but it is only an example!

We will need two buttons: Scan and Poke. We will also need some sort of ‘window’ for them to sit on. We could have them just floating on the screen, but that would look rather odd.

The first step is to create a sort of ‘rough draft’ of our HUD. I’ll explain why in a minute.

Let’s start with the window.

(Oh, one quick point – I am going to assume that you are fully familiar with creating/scaling/texturing prims. If you aren’t, you really shouldn’t be trying to create HUDs yet!).

Create a simple cube. Set the X scale to 0.01, so that you end up with a thin, flat board. Move it to somewhere close so that you can see it easily. If you want, you can blank the texture, though that isn’t important – we’ll deal with the texture later.

Next, let’s add a couple of buttons. Create two more cubes, setting the X scale to 0.1 again, and setting the Y and Z scale to something that approximates a sort of rectangular button shape. Place them flat against the ‘window’ board. Don’t worry about positioning them exactly yet, but you might want to colour them so that you can see them more clearly.

Link the buttons and the window (I’d suggest making the window the root prim, by selecting it last before linking, though it isn’t important for the simple HUD that we are going to make). One warning – don’t rotate this object, otherwise when you come to attach it, it might not be facing you!

Ok, now we have a primitive-looking window and buttons. Time to turn them into an actual HUD. Right-click the linked object, click ‘More’ on the pie menu, then click Attach HUD, and select Center.

If by chance you find that it is at the wrong angle (probably sideways!), you can rotate it even though it is attached. You might find it easier to adjust the numbers manually in the build dialog, rather than trying to use the Rotate tool.

Attached HUD

Yuk. You now have a grotesque HUD, probably occupying far too much of the screen, and obscuring your view. Don’t worry, there are things we can do about it. In fact, if you are at all familiar with building stuff, I’m sure that you are already ahead of me. Hold fire, though, because there are a few things you need to know before going on.

Firstly, yes, you can edit the HUD when it is attached. This is very convenient, because an unattached HUD is very small and fiddly to work with. However, there are some limitations on what you can actually edit once the HUD is attached. This is why it is useful to do a ‘rough draft’ while the HUD is unattached and you have all the editing facilities available to you.

The most important limitation on editing an attached HUD is that you cannot unlink the prims that make up the HUD, and you cannot link new prims to the HUD. If you find that you need to add a new prim, you will have to detach the HUD (it will vanish into your inventory, and you will need to re-rez it, which is rather annoying), create and link the new prim, then re-attach the HUD.

To work on the individual elements of the HUD, you need to tick the ‘Edit linked parts’ checkbox on the Build dialog. I’ve found that this normally lets you do most things to the individual parts, although rescaling prims sometimes refuses to ‘take’. If you get that happening to you, unfortunately all you can do is drop the HUD and unlink it while you edit the offending prim.

For our simple example, rescale the entire HUD to something more suitable. You can then edit the two buttons to position them more exactly (this is much easier to do now that the HUD is attached).

Of course, it is still obscuring our view. For now, select the ‘window’ prim, blank the texture, colour it grey (or whatever you prefer), and set the transparency to something between 50 and 75.

You could do something similar with the buttons, but we need to get text onto these in some way. Because SL doesn’t yet provide text-on-a-prim, you will have to break out your favourite graphics program, and create some button textures.

Naturally, you can do something similar with the texture for your window prim, and create something fancier than the plain version that we’ve just made.

If you are feeling lazy, here are a couple of example button textures that you can use instead:

“Scan” button texture (.tga)
“Poke” button texture (.tga)

Here is the final result (I’ve done some resizing, and reattached the HUD at the top-left instead of the centre):

Example HUD

One final ‘gotcha’. Go back to when we originally attached the HUD, and we found that it took up large amounts of screen space. How much screen space do you imagine a prim of a given size will take up? The answer is…it depends. Most crucially, it depends on the size of the window (or the screen resolution if running full-screen) that Second Life is using. A HUD will occupy more space in a smaller window, less space in a larger window. You need to think about this when designing your hud (make the mistake of trying to create a ‘full-screen’ HUD, and it will only fit properly at one specific screen-size. Not good).

Ok, we now have our HUD designed and built…but it doesn’t actually do anything! Time to rectify that.

Select the buttons individually, and create a new script in each one.

For the Scan button, edit the script, and replace the default with the following, which does a simple scan of the surround area, and outputs the names of any avatars found (the output is done via llOwnerSay, so it is only visible to the user of the HUD):

default
{
    touch_start(integer total_number)
    {
        llOwnerSay("Scanning...");
        // Look for any avatars within 96m.
        llSensor("", NULL_KEY, AGENT, 96.0, PI);
    }
    sensor(integer num_detected)
    {
        integer i;
        while(i < num_detected)
        {
            if (llDetectedKey(i) != llGetOwner())
            {
                llOwnerSay(llDetectedName(i));
            }
            ++i;
        }
    }
}

For the Poke button, replace the default script with this rather more elaborate one. This again does a scan of avatars in the vicinity, and then displays a dialog with their names as the buttons. When you select an avatar from the dialog, the chat message ‘[Your name] pokes [avatar name]’ is displayed.

integer dlgHandle = -1;
integer dlgChannel = -9999;
list avatarList = [];
reset()
{
    llSetTimerEvent(0.0);
    llListenRemove(dlgHandle);
    dlgHandle = -1;
}
default
{
    touch_start(integer total_number)
    {
        llOwnerSay("Scanning...");
        avatarList = [];
        // Look for any avatars within 10m.
        llSensor("", NULL_KEY, AGENT, 96.0, PI);
    }
    sensor(integer num_detected)
    {
        integer i;
        while((i < num_detected) && (i < 9))
        {
            if (llDetectedKey(i) != llGetOwner())
            {
                avatarList += [llDetectedName(i)];
            }
            ++i;
        }
        if (llGetListLength(avatarList) > 0)
        {
          state dialog;
        }
    }
}
state dialog
{
    state_entry()
    {
        // Set up a listener to detect button clicks.
        dlgHandle = llListen(dlgChannel, "", llGetOwner(), "");

        // Start a new timer.
        llSetTimerEvent(30.0);

        // Add a 'Cancel' button.
        avatarList += ["Cancel"];

        // Display the dialog.
        llDialog(llGetOwner(), "Please select an avatar.", avatarList, dlgChannel);
    }
    listen(integer channel, string name, key id, string message)
    {
        // The message parameter holds the caption of the
        // button that was clicked. Search the menu options
        // list for it.
        if ((channel == dlgChannel) && (llListFindList(avatarList, [message]) != -1))
        {
            if (message != "Cancel")
            {
                llSay(0, llKey2Name(llGetOwner()) + " pokes " + message);
            }
            reset();
            state default;
        }
    }
    timer()
    {
        reset();
        state default;
    }
}

Close the Build dialog, and your HUD should be fully active. Click on the buttons to check that they work.

Congratulations, you’ve just built your first HUD!

It’s often useful for an object to maintain a record of avatars or objects. One example might be a shop vendor which keeps a list of who has bought which item from it, or perhaps you want something which will tell you who has visited your shop recently.

There are various ways of doing this, but all of them eventually require you to store the information somewhere, and short of providing a link to an off-world database (a perfectly viable solution, but beyond the scope of this blog), the best option is to use a list.

The LSL implementation of lists is relatively primitive, but quite flexible, especially once you get to grips with the various associated functions, of which there are quite a few.

A list is just what the name implies. It is a simple collection of values, of any data type.

Declaring a list variable, and adding some items, is quite simple:

list animals = [];    // This creates an empty list.
animals += ["cat"];   // This adds one entry.
animals += ["dog"];   // This adds another entry.

Our list is now [“cat”, “dog”]. We can add more than one item at once:

animals += ["rabbit", "mouse"];

The list now holds [“cat”, “dog”, “rabbit”, “mouse”].

If we want to get a particular item out of a list, we use one of the llList2… functions. As our list only holds strings, we use llList2String. This needs to know the list that we are extracting from, and the item number. Be careful – items in a list are numbered from 0! If you have never done any programming before, this might catch you out, but it is very common in programming languages (for reasons that I won’t go into here):

// Copies "dog" to the 'item' variable.
string item = llList2String(animals, 1);

Actually, a list can hold any data type, and any mixture of data types, except (and this is an important exception) other lists.

For example, we could do this:

animals += [10.12, 16, "kangeroo"];

Our list is now [“cat”, “dog”, “rabbit”, “mouse”, 10.12, 16, “kangeroo”]. As you’ll realise, this probably isn’t a clever thing to do, because we now have strings and numbers mixed in our list, in no particular order.

Assuming that we do know the order, we can extract these values using the llList2Float and llList2Integer functions:

float fvalue = llList2Float(animals, 4);
integer ivalue = llList2Integer(animals, 5);

On the other hand, suppose we want to store several items of information for each ‘entry’ in our list. Suppose we want a script that holds avatar names along with some kind of count for each avatar (maybe the number of times they have visited your shop).

What we need is a strided list. This is exactly the same as a normal list, but we impose certain conditions on it, and use a slightly more convoluted way to extract information out of it.

Let me explain. To make things easier, let’s use some standard computer parlance, and call our combination of avatar id and count as a ‘record’. Our constraint on the list is that we always add a complete record at a time, and this record must always contain the same number of items, each item being of a specified type. In our example, a record is a list which contains a string (the avatar name) and an integer (the count).

For example:

list avatarList = []; // Create an empty list.
avatarList += ["Pyter Morgridge", 0];   // Add a record.
avatarList += ["Someone Else", 0]; // Add another record.

Our list now holds [“Pyter Morgridge”, 0, “Someone Else”, 0]. Because we have imposed a structure on it, we can extract a complete record out of the list by using the llList2List function, which extracts a sublist. In this case, we will extract the first record, which starts at position 0 in the list, and ends with position 1.

list pytersrecord = llList2List(avatarList, 0, 1);

We now have [“Pyter Morgridge”, 0] in pytersrecord. The only tricky bit (and it isn’t that tricky) is working out where a particular record starts.

We deal with than by making things a little more generic. Let’s start a new script:

integer FIELD_COUNT = 2;  // Number of items in each record.
list avatarList = []; // Create an empty list.

Now we can create a utility function that will return the position in the list for a particular record number. In our example above, the record for Pyter is record number 0, and the record for Someone Else is record number 1. The list entries for them start at 0 and 2 respectively.

integer getPosition(integer recordNumber)
{
    return recordNumber * FIELD_COUNT;
}

We can use this to create functions that will return a single record, delete a record, and update a record:

list getRecord(integer recordNumber)
{
    integer pos = getPosition(recordNumber);
    if (pos < (llGetLength(avatarList) + FIELD_COUNT - 1))
      return llList2List(avatarList, pos, pos + FIELD_COUNT - 1);
    else
      return [];  // Or possibly raise an error.
}
deleteRecord(integer recordNumber)
{
    integer pos = getPosition(recordNumber);
    if (pos < (llGetLength(avatarList) + FIELD_COUNT - 1))
      avatarList = llDeleteSubList(avatarList, pos, 
                                   pos + FIELD_COUNT - 1);
}
updateRecord(integer recordNumber, list newRecord)
{
    integer pos = getPosition(recordNumber);
    if (pos < (llGetLength(avatarList) + FIELD_COUNT - 1))
      avatarList = llListReplaceList(avatarList, newRecord, pos, 
					      pos + FIELD_COUNT - 1);
}

You’ll find more information about lists and strided lists here:

LSL Wiki – Lists

I’m not sure why, but this struck me as oddly amusing. It is also, however, very clever, and immediately useful for anyone who is new to scripting.

May I present Ann Enigma’s LSL Script Auto-Generator!

In fact, even if you are not new to scripting, but you want to quickly generate a relatively simple script (possibly as the starting point for something more elaborate), this might well be useful.

Don’t miss Ann’s main blog, either, if you have any interest in virtual worlds:

3greeneggs.com

Here is a very simple way to create rippling water for a pond or swimming pool. It uses the water textures which are in the Second Life standard library, so you don’t have to spend money uploading any textures!

To make this work, create two prims. For the sake of this example, I’ll call them Water and Ripples, just to make it easier to identify which one I am talking about.

Make them both the same size, and flatten them as thin as possible — they are going to combine to form the water surface.

Place them so that the Ripples prim is just above the top of the Water prim.

In the Second Life texture library, find the Waterfalls folder. Texture the Water prim with the “Water – ripple layer 1” texture, and the Ripples prim with the “Water – ripple layer 2 texture”.

In the Water prim, create a new script, and replace the script contents with the following:

default
{
    state_entry()
    {
        llSetTextureAnim(ANIM_ON | LOOP | SMOOTH | ROTATE, ALL_SIDES,
                        1, 1, 1, 1, -0.025);
    }
}

This will slowly rotate the texture.

In the Ripples prim, create a new script, and replace the script contents with the following:

default
{
    state_entry()
    {
        llSetTextureAnim(ANIM_ON | LOOP | SMOOTH | ROTATE, ALL_SIDES,
                        1, 1, 1, 1, 0.025);
    }
}

This will slowly rotate the texture, but in the opposite direction to the texture of the Water prim.

The result, to my eyes at least, is a very convincing rippling water effect. You have to look at it very carefully to spot what is actually happening.