LSL Protocol/rfedip

From Second Life Wiki
< LSL Protocol
Revision as of 22:22, 28 December 2013 by Ratany Resident (talk | contribs) (added second example device)
Jump to navigation Jump to search

Ratany fine Engineerings Device Interface Protocol (rfedip)

About

The Ratany fine Engineering Device Interface Protocol (short: rfedip) is an extensible protocol for the detection of compliant devices and for the handling of the communication between such devices.

The protocol defines how devices can be detected and rules for how the devices can communicate. It does not define the very content of such communications, with the exception of a few so-called control messages.


The protocol has been created because there doesn´t seem to be any sort of standard to detect devices. Devices can be leashing posts, furniture, collars, cuffs and chastity belts as well as any other gadget the design of which involves interoperability or some sort of communication with other devices.

Using sensors to scan for devices has turned out to be an insufficient alternative. The sensor range is inevitably limited, and particular prims --- which may be the actual points of an object to tie a leash to --- of objects cannot be detected with a sensor.

Using existing protocols like the lockmeister protocol also turned out not to be feasible. A device using the lockmeister protocol only becomes active from an agent sitting on the device or touching the device, and the device does itself not listen for queries to identify itself.

At the time of this writing, open collar items seem to employ some sort of protocol and maybe even some sort of API. However, these are not documented, and development appears to be in progress such that significant changes might be implemented.

Other protocols may exist that are vendor-specific. Insofar their designs have not been disclosed, they are unsuited to achieve compatibility and interoperability of devices made by different creators. A device that lacks compatibility with other devices may have no more than a very limited use for the user of the device, especially when the functionality of the device genuinely requires that the device works with others.

The Ratany fine Engineering Device Interface Protocol is intended to encourage and to help with the creation of devices that are compatible with others.


The availability of a useful protocol does not mean that creators of devices will be inclined to use it. Please consider this article as a draft with the intention to create a useful protocol which hopefully might be used by many creators --- and as a request for comments. Please feel free to use the discussion page of this article to add your suggestions and ideas, or to contact the author directly.


Requirements brought upon a protocol

The protocol should be:

  • available
  • extensible
  • independent of the medium which is used to transmit protocol messages
  • reliable
  • easy to implement/use
  • compatible with previous versions of the protocol when new versions are created


Specification

In General

The rfedip protcol uses strings of characters that can be transfered as messages of a type which can be sent by functions like llMessageLinked(), llRegionSayTo(), llRegionSay(), llShout(), llSay(), llWhisper() as well as in the body of an email or via the use of the HTTP protocol.

An rfedip message is a string which is divided into fields by the use of a special character as separator. The fields of a message are defined as follows, and they appear in the message in the order they are listed here:


  • sender-UUID: The UUID of the sending device.
  • recipient-UUID: The UUID of the device the message is directed to.
  • protocol version: A string that specifies the version of the protocol.
  • payload: The payload of the protocol. The payload is generally assumed to consist of a token. The token may be followed by a parameter. Multiple tokens and parameters may be sent in a single message. However, a single message should not contain multiple tokens. Multiple messages should be used to avoid the creation of messages that contain multiple tokens.


All devices compliant with the rfedip protocol must have available documentation about all the tokens and, if applicable, the parameters used with the tokens the device supports. The documentation must include the tokens and parameters the device understands, as well as the tokens and parameters it might use itself to communicate with other rfedip-compliant devices.

This is to ensure that creators and users of rfedip-compliant devices can refer to the documentation of devices created by others and make the devices they are creating compatible with devices created by others, if they so choose.

A device for which such documentation is not freely available cannot be considered as compliant or compatible with the rfedip protocol.


Definitions

The rfedip protocol itself defines:

  • a string specifying the protocol version: "RFEDIP-1.0"
  • that future versions of the protocol must maintain compatibility with previous versions of the protocol
  • a suggestion as to what may be considered as "sufficient version": "RFEDIP" (What is considered as "sufficient version" for a particular device is up to the creator of that device.)
  • the special character that must be used to seperate a string of characters into fields in order to form a protocol message: "|"
  • a default communications channel, when applicable: -20131224
  • supporting email and http as transport media for protocol messages is optional; supporting the default communications channel is mandatory
  • a token that designates a request for a device to identify itself: "identify"
  • a token that designates a protocol message a device identifies itself with: "identity"
  • a token that designates a protocol message signalling that a communication (sequence) has ended, mandatorily followed by the channel in question: "msg_end!"
  • a token that designates a protocol message requesting that a particular channel, if applicable, be used for further communication, mandatorily followed by the channel which is to be used as a parameter: "openchan"
  • that a particular channel which was opened can be closed when the device that requested opening this channel sends the protocol message that signals that a communication (sequence) has ended
  • that a particular channel which was opened on request of a device can unconditionally be closed one hour after the last communication has occurred on that channel
  • that identification requests must always be answered (consequently, the default channel must never be closed, even not when a device signals the end of a communication (sequence) for the default channel)
  • that messages involving tokens as defined here must be sent on the default channel for they are considered control messages (i. e. messages like identification requests, responses to those, opening channels, signalling the end of a communication (sequence))


Example Implementation

First Example: A device providing chaining points

For an example implementation, a simple rfedip-compliant device will be created here that allows another device to query the UUIDs of so-called chain points of an object.

Since the author is using cpp as preprocessor for LSL scripts (and other tools), the actual source code for the device will be provided first. The LSL script that is the result of the compilation process will be given below. Even without full syntax highlighting, the source is IMO much easier to read than the actual script.

You do not need to use cpp or other tools to make use of the rfedip-protocol. How you actually implement the protocol is completely up to you, this is merely an example.

To create the device, a generic template is used. It´s called a generic template because it doesn´t contain more than what is needed to answer identification requests and to check whether a received message appears to be a valid rfedip-protocol message. For anything beyond that, a function (named rfedip_handle()) is called. (This has the advantage that the function can be defined in a script for a particular device which simply includes the template, and many different devices can be made which all use the same template.)

You can think of this template as a script that handles some control messages of the protocol which are not device-specific.


<lsl>

// Ratnay fine Engineering Device Interface Protocol // // generic example template //


  1. include <lslstddef.h>
  2. include <rfedip.h>


default { event state_entry() { // permanently listen on the protocol channel // llListen(RFEDIP_CHANNEL, "", NULL_KEY, ""); }

event listen(int channel, string name, key other_device, string _MESSAGE) { IfMessage(RFEDIP_protIDENTIFY_QUERY) { // Indistinctively answer queries that want to // detect this device: The answer goes to the // sender (i. e. other_device) and looks like: // // "<sender-uuid>|<recipient-uuid>|RFEDIP_sVERSION|RFEDIP_protIDENTIFY" // // For the device that receives the answer to // the request to identify, the <sender-uuid> // is the UUID of this device. // // With // // RFEDIP_RESPOND(<recipient-uuid>, <sender-uuid>, <protocol-payload>); // // an answer is sent to the device from which // this device has received the request to // identify itself: //

  1. define this_device llGetLinkKey(llGetLinkNumber()) // the UUID of this device

RFEDIP_RESPOND(other_device, this_device, RFEDIP_CHANNEL, RFEDIP_protIDENTIFY); return; }

// From here on, received messages are expected to // look like: // // "<sender-uuid>|<recipient-uuid>|RFEDIP_sVERSION|<token>[|parameter|parameter...]" // // <sender-uuid> is the UUID of the device sending the // message (i. e. other_device); <recipient-uuid> is // the UUID of the recipient, i. e. of this device // // Please do not confuse incoming messages with // outgoing messages! // // Parameters can be tokens. However, this is not // recommended. Send multiple messages rather than // multiple tokens in one message. // // The received message is put into a list for further // processing: // list payload = ProtocolData(RFEDIP_sSEP);

// Attempt to verify whether the message looks valid: // if(Len(payload) < RFEDIP_iMINMSGLEN) return;

// Attempt to make sure that the message is for this // device: // // + ignore messages that appear not to be sent by the // device they claim to be sent from by verifying // the sender given in the message with the actual // sender: //

  1. define InvalidSender (RFEDIP_ToSENDER(payload) != other_device)

// // + ignore messages that appear not be destined for // this device by verifying the recipient given in // the message with what this device actually is: //

  1. define NotDestined (RFEDIP_ToRCPT(payload) != this_device)

// // + ignore messages that request a different version // of the protocol by verifying the protocol version // given in the message --- in this example, a check // for what is considered a "sufficient version" is // applied: //

  1. define BadVersion !Instr(RFEDIP_ToPROTVERSION(payload), RFEDIP_sSUFFICIENT_VERSION)

// when(InvalidSender || NotDestined || BadVersion) return;

  1. undef this_device
  2. undef InvalidSender
  3. undef NotDestined
  4. undef BadVersion

// From here on, the capabilities of the device can be // implemented. // // Since this is a template, just call a handling // function so the template can simply be included // into a script that implements such capabilities. // rfedip_handle(payload); } } </lsl>


As you can see, above template uses (#includes) the two files "lslstddef.h" and "rfedip.h". Providing "lslstddef.h", and how to use cpp as a preprocessor, is far outside the scope of this article. Only "rfedip.h" is required here:


<lsl>


// defines for Ratany fine Engineerings Device Interface Protocol

  1. ifndef _RFEDIP
  2. define _RFEDIP
  1. define RFEDIP_sVERSION "RFEDIP-1.0" // protocol version
  2. ifndef RFEDIP_sSUFFICIENT_VERSION
  3. define RFEDIP_sSUFFICIENT_VERSION "RFEDIP" // default to any version as sufficient version
  4. endif
  5. define RFEDIP_sSEP "|" // separator used in protocol messages
  1. define RFEDIP_CHANNEL -20131224 // default channel used for protocol messages
  1. define RFEDIP_protIDENTIFY_QUERY "identify" // identification query, must be responded to with RFEDIP_protIDENTIFY
  2. define RFEDIP_protIDENTIFY "identity" // answer to identification queries
  3. define RFEDIP_protEND "msg_end!" // indicate end of data transfer; if a particular channel was opened, this channel can be closed
  4. define RFEDIP_protOPEN "openchan" // open a particular channel for further communication, mandatorily has a channel number as parameter
  1. define RFEDIP_ToSENDER(_l) llList2Key(_l, 0) // return UUID of sender from list _l
  2. define RFEDIP_ToRCPT(_l) llList2Key(_l, 1) // return UUID of recipient from list _l
  3. define RFEDIP_ToPROTVERSION(_l) llList2String(_l, 2) // return string containing the version of the protocol from list _l
  4. define RFEDIP_ToFirstTOKEN(_l) llList2String(_l, 3) // return the first token from list _l
  5. define RFEDIP_ToFirstPARAM(_l) llList2String(_l, 4) // return the first parameter
  6. define RFEDIP_ToRESPONSE(_sndr, _rcpt, ...) llDumpList2String([_sndr, _rcpt, RFEDIP_sVERSION, __VA_ARGS__], RFEDIP_sSEP) // convert a protocol payload into a protocol message
  7. define REFDIP_OPEN(_rcpt, _sndr, _nchan) llRegionSayTo(_rcpt, RFEDIP_CHANNEL, RFEDIP_ToRESPONSE(_sndr, _rcpt, RFEDIP_protOPEN, _nchan)) // open a particular channel for communication
  8. define RFEDIP_END(_rcpt, _sndr, _nchan) llRegionSayTo(_rcpt, RFEDIP_CHANNEL, RFEDIP_ToRESPONSE(_sndr, _rcpt, RFEDIP_protEND, _nchan)) // indicate end of communication on channel _c
  9. define RFEDIP_IDQUERY llRegionSay(RFEDIP_CHANNEL, RFEDIP_protIDENTIFY_QUERY) // ask all rfedip compliant devices to identify themselves
  10. define RFEDIP_RESPOND(_rcpt, _sndr, _chan, ...) llRegionSayTo(_rcpt, _chan, RFEDIP_ToRESPONSE(_sndr, _rcpt, __VA_ARGS__))
  1. define RFEDIP_iMINMSGLEN 4 // used to figure out whether a message is a RfE-dip message or not


  1. endif // _RFEDIP

</lsl>


To create the actual device for this example, the script that provides the function which handles the device-specific protocol messages is also needed. It simply defines the function to report the chain points on request:


<lsl>

// RfE-dip compatible generic chaining device // // "Generic" means that all prims of the object (i. e. device) this // script is in which are named sCHAINPOINT (i. e. "hook", see below) // will be reported via the Ratany fine Engineering device interface // protocol when a compatible device queries them. In case there are // no prims with that name and the script is in the root prim, the // root prim will be reported.


// some standard definitions //

  1. include <lslstddef.h>

// use the getlinknumbersbyname() function from a library that // provides functions to deal with names and descriptions of prims in // order to figure out link numbers //

  1. define _USE_getlinknumbersbyname
  2. include <getlinknumbers.lsl>

// some standard definitions for rfedip: //

  1. include <rfedip.h>

// some definitions needed by devices that communicate with this // device //

  1. include <rfedip-generic-chainpoints.h>


// the prims of the device that are points to attach chains to are // named "hook", unless otherwise defined

  1. ifndef sCHAINPOINT
  2. define sCHAINPOINT "hook"
  3. endif

// When a request for chaining points has been received, respond with // the UUID of each chaining point of this device. Once all the // available points are reported, the the RFEDIP_protEND token is sent // to indicate that the data transfer is complete. // // Report one chaining point per message to simplify parsing for the // receiver and to avoid problems with maximum message length. // // rfedip_handle() is called from the RfE-dip-template. In this case, // no more than a few lines are needed which can easily be inlined. // (Inlining can save memory compared to actually using a function and // may run faster.) //

  1. define rfedip_handle(_data) \

when(RFEDIP_ToFirstTOKEN(_data) == protTETHER) \ { \ list hooks = getlinknumbersbyname(sCHAINPOINT); \ key sender = RFEDIP_ToSENDER(_data); \ key this = llGetLinkKey(llGetLinkNumber()); \ if(!Len(hooks) && (llGetLinkNumber() < 2)) hooks = (list)llGetLinkNumber(); \ int n = Len(hooks); \ LoopDown(n, RFEDIP_RESPOND(sender, this, RFEDIP_CHANNEL, protTETHER_RESPONSE, llGetLinkKey(llList2Integer(hooks, n)))); \ RFEDIP_END(sender, this, RFEDIP_CHANNEL); \ return; \ }

// Simply use the RfE-dip template as is. // // For devices that consist of many prims, it is better to use a // global variable for the list of hooks which isn´t updated on every // query. With such devices, use the template directly here rather // than including it, and adjust it accordingly. For the purpose of // this example, things are kept simple. //

  1. include <rfedip-template.lsl>

</lsl>


As you can see, "rfedip-generic-chainpoints.h" is included, which is relevant for this article:


<lsl>


// device specific protocol payload; for this device, this is // intentionally very similar to lockmeister // // The device specific protocol payload is what must be documented for // each device to be compatible. In this case, for example: // // "The device can be queried for the UUIDs of prims to which chains // can be attached. The token to query the device is "tether". The // device replies with the token "tether point", followed by the UUID // of a chaining point. Each chaining point is reported in a seperate // response message, one chaining point per message. Once all points // have been reported, the device signals end of communication. ..." //

  1. define protTETHER "tether"
  2. define protTETHER_RESPONSE "tether point"

</lsl>


The compilation process delivers the LSL script which you put into the object that becomes an rfedip-compliant device. Of course, when you do not use cpp and other tools, you would write such a script "directly":


<lsl> list getlinknumbersbyname(string name) { integer n = llGetObjectPrimCount(llGetLinkKey(llGetLinkNumber() ) ); list numbers = []; name = llToLower(name); if(n > 1) { while(n) { if((~llSubStringIndex(llToLower(llList2String(llGetLinkPrimitiveParams(n, [PRIM_NAME] ), 0) ), name) ) ) { numbers += n; } --n; } } else { if((~llSubStringIndex(llToLower(llGetObjectName() ), name) ) ) { numbers += n; } } return numbers; } default { state_entry() { llListen(-20131224, "", NULL_KEY, ""); } listen(integer channel, string name, key other_device, string _MESSAGE) { if("identify" == _MESSAGE) { llRegionSayTo(other_device, -20131224, llDumpList2String([llGetLinkKey(llGetLinkNumber()), other_device, "RFEDIP-1.0", "identity"], "|")); return; } list payload = llParseString2List((_MESSAGE), ["|"], []); if(llGetListLength(payload) < 4) return; if((llList2Key(payload, 0) != other_device) || (llList2Key(payload, 1) != llGetLinkKey(llGetLinkNumber())) || !(~llSubStringIndex(llList2String(payload, 2), "RFEDIP") )) return; if(llList2String(payload, 3) == "tether") { list hooks = getlinknumbersbyname("hook"); key sender = llList2Key(payload, 0); key this = llGetLinkKey(llGetLinkNumber()); if(!llGetListLength(hooks) && (llGetLinkNumber() < 2)) hooks = (list)llGetLinkNumber(); integer n = llGetListLength(hooks); while(n) { --n; llRegionSayTo(sender, -20131224, llDumpList2String([this, sender, "RFEDIP-1.0", "tether point", llGetLinkKey(llList2Integer(hooks, n))], "|")); }; llRegionSayTo(sender, -20131224, llDumpList2String([this, sender, "RFEDIP-1.0", "msg_end!", -20131224], "|")); return; }; } } </lsl>


Note: This device does not work when worn as an attachment, see llGetObjectPrimCount().

Second Example: A device using chaining points

The second example is a device that queries the device in the first example for the chaining points and uses those. You can use this device to automatically tie up your boat (none of the boats the author has seen in their berths in sl were really tied up ...), to nicely tie an agent to some piece of furniture, or for whatever else comes to mind.


On a side note: The problem is this: Attach N chains to X chain points which are around. Make it so that there is no more than one chain going to each chain point, and make sure the chains are each attached to the chain point closest to them, if possible. The result must not look retarded, and it can be ignored that it is sometimes advisable to cross the chains over.

Unless they get too many chains to deal with, humans solve this problem without even thinking. It is obvious where each chain needs to go and extremely easy to solve. Therefore, one would expect an algorithm that solves this problem to be equally simple. Surprisingly, it is not.


This example starts with the template from the first example, using a modified version of it. Things have been added to the template because this device requires them, and the template is not #included but used "directly".

To point out the part which is more relevant for the example, functions and definitions have been put into a separate file which is #included.


<lsl>

// Ratany fine Engineering Interface Device Protocol example // // implementation of a device that queries another rfedip device for // chaining points and then makes use of the points. // // Use this device to tie up your boat or something :)


// include the stuff that isn´t entirely relevant for the purpose of // this example and needed for this device --- this is only so to make // things easier to read //

  1. include <rfedip-second-example-header.h>


// This is a version of the template modified for this particular // device. // default { event listen(int channel, string name, key other_device, string _MESSAGE) { // identify this device // IfMessage(RFEDIP_protIDENTIFY_QUERY) { RFEDIP_RESPOND(other_device, llGetLinkKey(llGetLinkNumber()), RFEDIP_CHANNEL, RFEDIP_protIDENTIFY); return; }

// verify whether the received message looks like a // valid refdip-protocol message // list payload = ProtocolData(RFEDIP_sSEP); if(Len(payload) < RFEDIP_iMINMSGLEN) return; when((RFEDIP_ToSENDER(payload) != other_device) || (RFEDIP_ToRCPT(payload) != llGetLinkKey(llGetLinkNumber())) || !Instr(RFEDIP_ToPROTVERSION(payload), RFEDIP_sSUFFICIENT_VERSION)) return;

// extract the token from the rfedip message ... // string token = RFEDIP_ToFirstTOKEN(payload);

// // ... to do some device specific stuff // // The order of the message handling has been arranged // for better performance. //

when(protTETHER_RESPONSE == token) { // THIRD: Receive the responses to the query for points to attach chains to // and remember those points. // Enlist(lTargets, RFEDIP_ToFirstPARAM(payload)); return; }

when(RFEDIP_protEND == token) { IfStatus(stRECEIVING) { // Receiving an end-message means that the device which sent it has finished // answering. // --iDevicesAround; iDevicesAround = Max(iDevicesAround, 0); // ignore unexpected end-msgs

// FOURTH: When all answers have been received, make the chains. // In case an end-message gets lost, the timeout kicks in. // unless(iDevicesAround) mkchains(); }

return; }

when(RFEDIP_protIDENTIFY == token) { // SECOND: Ask a device that identifies itself for points to attach chains to. // ++iDevicesAround; RFEDIP_RESPOND(other_device, llGetLinkKey(llGetLinkNumber()), RFEDIP_CHANNEL, protTETHER); return; }

// when receiving messages not handled by this device, // indicate end of communication to potentially save // other devices unnecessary waiting times // RFEDIP_END(other_device, llGetLinkKey(llGetLinkNumber()), RFEDIP_CHANNEL); }

event touch_start(int t) { unless(Len(lChains)) { aftell("no chains to create"); return; }

IfStatus(stBUSY) { aftell("busy, please wait"); return; }

SetStatus(stBUSY); LoopChains(xChainHide(_n); yChainUnlink(_n)); aftell("querying for devices"); SoundPing; lTargets = [];

// keep track of how many devices are detected to be // able to decide whether all answers from all devices // have been received or not // iDevicesAround = 0;

// there isn´t a way around a timeout with this device :( // llSetTimerEvent(fTIMER_UNWAIT);

// FIRST: query for rfedip-compliant devices // RFEDIP_IDQUERY; SetStatus(stRECEIVING); }

event timer() { // A message indicating end of communication might not // have arrived. Go ahead with whatever information // has been received so far. // aftell("timeout"); mkchains(); }

event state_entry() { ClrStatus; yChainsInit;

llListen(RFEDIP_CHANNEL, "", NULL_KEY, ""); }

event changed(int w) { when(w & CHANGED_LINK) { // maybe do something else here if you need to sit on this device // LoopChains(xChainHide(_n); yChainUnlink(_n)); yChainsInit; } } } </lsl>


This is basically it. The listener event handles the rfedip-protocol messages and acts upon the tokens. Most of what is in the other events is specific for this device.

The functionality of this device is implemented in what´s in "rfedip-second-example-header.h". It´s a bit lengthy, and you can safely skip this part:


<lsl>

// header file for rfedip-example device // // Contains stuff that isn´t entirely relevant for the purpose of the // example.


// some standard definitions //

  1. include <lslstddef.h>
  2. include <colordef.h>

// use the getlinknumbersbylistnamedappend_attached() function from a // library that provides functions to deal with names and descriptions // of prims in order to figure out link numbers //

  1. define _USE_getlinknumbersbylistnamedappend_attached
  2. define _GETLINKNUMBERSBYLISTNAMEDAPPEND_ATTACHED_APPENDIX [NULL_KEY]
  3. include <getlinknumbers.lsl>

// use the geom_linecrosspoint() function from a library that provides // functions that deal with geometry //

  1. define _GEOM_USE_geom_linesegmentscross
  2. include <geometry.lsl>

// some standard definitions for rfedip: //

  1. include <rfedip.h>

// some definitions from devices that communicate with this // device //

  1. include <rfedip-generic-chainpoints.h>


// The standard library (lslstddef.h) provides status handling, which // requires an integer to store the status´ in: // int status;

  1. define stBUSY 1
  2. define stRECEIVING 2


// This particular device can have multiple chains, created from the // prims with names listed here. Add as many chains as you like, // until the script runs out of memory. //

  1. define lCHAINTOS ["Chain-0", "Chain-1", "Chain-2", "Chain-3", "Chain-4", "Chain-5", "Chain-6", "Chain-7"]


int iDevicesAround; // keep track of how many other devices have been found

  1. define iSTRIDE_lChains 3 // lChains is a strided list: [prim name, link number, uuid of target]
  2. define iINDEXOFFSET_lChains 2 // needed to deduct which chain is linked to a given target point

list lChains; list lTargets; // a list of uuids of prims to leash to, as reported via rfedip


// a few macro definitions to deal with the chains // // Consider them as a demonstration of the incredible usefulness of a // preprocessor. //

  1. define CHAINS_lPARTICLE_CHAIN(_n) [ \

PSYS_PART_MAX_AGE, 3.0, \

                                     PSYS_PART_FLAGS, PSYS_PART_FOLLOW_VELOCITY_MASK | PSYS_PART_TARGET_POS_MASK | PSYS_PART_FOLLOW_SRC_MASK | PSYS_PART_EMISSIVE_MASK, \
                                     PSYS_PART_START_COLOR, RandomColor, \
                                     PSYS_PART_START_SCALE, <0.2, 0.2, 0.0>, \
                                     PSYS_SRC_PATTERN, PSYS_SRC_PATTERN_DROP, \
                                     PSYS_SRC_BURST_RATE, 0.04,	\
                                     PSYS_SRC_ACCEL, <0.0, 0.0, -1.2>,	\
                                     PSYS_SRC_BURST_PART_COUNT, 1,	\
                                     PSYS_SRC_BURST_SPEED_MIN, 3.0,	\
                                     PSYS_SRC_BURST_SPEED_MAX, 3.0,	\
                                     PSYS_SRC_TARGET_KEY, kChainKey(_n), \
                                     PSYS_SRC_MAX_AGE, 0.0,		\
                                     PSYS_SRC_TEXTURE, "4cde01ac-4279-2742-71e1-47ff81cc3529" \

]


  1. define boolChainLinked(_n) (kChainKey(_n) != NULL_KEY)
  2. define fChainLength(_c) llVecDist(vChainPos(_c), vChainEndpos(_c))
  3. define iChainLinkNo(_n) llList2Integer(lChains, (_n) + 1)
  4. define kChainKey(_n) llList2Key(lChains, (_n) + 2)
  5. define sChainName(_n) llList2String(lChains, _n)
  6. define vChainEndpos(_c) RemotePos(kChainKey(_c))
  7. define vChainPos(_chain) (llGetRootPosition() + llList2Vector(GLPP(iChainLinkNo(_chain), [PRIM_POS_LOCAL]), 0) * llGetRootRotation())
  8. define xChainHide(_n) llLinkParticleSystem(iChainLinkNo(_n), [])
  9. define xChainShow(_n) llLinkParticleSystem(iChainLinkNo(_n), CHAINS_lPARTICLE_CHAIN(_n))
  10. define yChainLink(_n, _k) (lChains = llListReplaceList(lChains, (list)_k, (_n) + 2, (_n) + 2))
  11. define yChainUnlink(_n) (lChains = llListReplaceList(lChains, (list)NULL_KEY, (_n) + 2, (_n) + 2))
  12. define yChainsInit (lChains = getlinknumbersbylistnamedappend_attached(lCHAINTOS))
  1. define LoopChains(_do) int _n = Len(lChains); while(_n) { _n -= iSTRIDE_lChains; _do; }
  1. define kTargetKey(_target) llList2Key(lTargets, _target)
  2. define vTargetPos(_target) RemotePos(kTargetKey(_target))
  3. define fDistChainTarget(_c, _t) llVecDist(vChainPos(_c), vTargetPos(_t))


// unfortunately, this device needs a timer because messages can be // lost, or no compliant devices might be around //

  1. define fTIMER_UNWAIT 30.0

// sometimes stuff is undetermined //

  1. define fUNDETERMINED -1.0
  2. define iUNDETERMINED -1
  3. define vUNDETERMINED (<fUNDETERMINED, fUNDETERMINED, fUNDETERMINED>)


// figure out which chain is attached to a target point // // This should be a macro, yet with the ternary operator missing from // the script language, it´s not reasonable to implement it as a // macro here. // int iChainOfTarget(int t) { int x = LstIdx(lChains, kTargetKey(t)); if(~x) return (x - iINDEXOFFSET_lChains); return iUNDETERMINED; }


// figure out which chain target is closest to a given chain point // int closest_target(int chain) { int ret = iUNDETERMINED; vector chainpos = vChainPos(chain); float closest = fUNDETERMINED; int n = Len(lTargets); while(n) { --n;

float distance = llVecDist(vTargetPos(n), chainpos); if(fUNDETERMINED == closest) { closest = distance; ret = n; } else { if(distance < closest) { closest = distance; ret = n; } } }

return ret; }


// compute the average position of all the chain targets // vector avgpos_targets() { vector avg = vUNDETERMINED; int cnt = 0; int t = Len(lTargets); while(t) { --t;

avg += vTargetPos(t); ++cnt; }

return (avg / (float)cnt); }


// figure out which chain point is the furthest away from a given position // int furthest_chain(vector ref) { float distmax = fUNDETERMINED; int ret = iUNDETERMINED; int c = Len(lChains); while(c) { c -= iSTRIDE_lChains;

unless(boolChainLinked(c)) { float dist = llVecDist(vChainPos(c), ref); if(distmax < dist) { distmax = dist; ret = c; } } }

return ret; }


// swap the target points of two chains // void swap_chains(int ca, int cb) { key tmp = kChainKey(ca);

yChainLink(ca, kChainKey(cb)); yChainLink(cb, tmp); }


// figure out which chain is crossed by a given chain // int find_chain_crossedby(int chain) { vector start = vChainPos(chain); vector end = vChainEndpos(chain);

int c = Len(lChains); while(c) { c -= iSTRIDE_lChains;

when((chain != c) && boolChainLinked(c)) { if(geom_linesegmentscross(start, end, vChainPos(c), vChainEndpos(c))) return c; } }

return iUNDETERMINED; }


// Make a chain from each chain point to the chain target closest to // that chain point, no more than one chain per target. It would be // really interesting to see a better algorithm for this. // // caveats: It is undetermined whether a solution can be found in all // possible cases or not. // // The algorithm scales horribly. // void mkchains() { UnStatus(stRECEIVING); llSetTimerEvent(0.0); aftell("computing ...");

int continue = Len(lTargets); vector ref = avgpos_targets(); unless(vUNDETERMINED == ref) { int c = furthest_chain(ref); while(continue && (c != iUNDETERMINED)) { int t = closest_target(c); unless(iUNDETERMINED == t) { yChainLink(c, kTargetKey(t)); lTargets = llDeleteSubList(lTargets, t, t); --continue; } c = furthest_chain(ref); } }

lTargets = []; LoopChains(when(boolChainLinked(_n)) Enlist(lTargets, kChainKey(_n)));

bool swapped; do { swapped = FALSE;

int c = Len(lChains); while(c) { c -= iSTRIDE_lChains;

when(boolChainLinked(c)) { int crosses = find_chain_crossedby(c); unless(iUNDETERMINED == crosses) { swap_chains(c, crosses); swapped = TRUE; }

int t = closest_target(c); if(fDistChainTarget(c, t) < fChainLength(c)) { int cc = iChainOfTarget(t); unless(iUNDETERMINED == cc) { if(geom_linesegmentscross(vChainPos(c), vChainEndpos(c), vChainPos(cc), vTargetPos(t))) { swap_chains(c, cc); swapped = TRUE; } } else aftell("data mismatch"); } } } } while(swapped);

{ LoopChains(when(boolChainLinked(_n)) xChainShow(_n)); } UnStatus(stBUSY); aftell("done"); } </lsl>


Note: This device could be worn as an attachment.


Except for "colordef.h" and "geometry.lsl", the #included files are the same as with the first example.

Finally, here is the actual LSL script that results from the compilation:


<lsl> list getlinknumbersbylistnamedappend_attached(list names) { list strided = []; integer n = llGetNumberOfPrims();

do { string thisname = llList2String(llGetLinkPrimitiveParams(n, [PRIM_NAME] ), 0);

if((~llListFindList(names, [thisname]))) { strided += [thisname, n] + [NULL_KEY]; }

--n; } while(n > 0);

return strided; } integer geom_linesegmentscross(vector p1, vector p2, vector p3, vector p4) { vector a = p2 - p1; vector b = p3 - p4; vector c = p1 - p3; float alphaNumerator = b.y * c.x - b.x * c.y; float alphaDenominator = a.y * b.x - a.x * b.y; float betaNumerator = a.x * c.y - a.y * c.x; float betaDenominator = a.y * b.x - a.x * b.y; integer doIntersect = TRUE;

if (alphaDenominator == 0.0 || betaDenominator == 0.0) { doIntersect = FALSE; } else { if (alphaDenominator > 0.0) { if (alphaNumerator < 0.0 || alphaNumerator > alphaDenominator) { doIntersect = FALSE; } } else { if (alphaNumerator > 0.0 || alphaNumerator < alphaDenominator) { doIntersect = FALSE; } }

if (doIntersect && betaDenominator > 0.0) { if (betaNumerator < 0.0 || betaNumerator > betaDenominator) { doIntersect = FALSE; } } else { if (betaNumerator > 0.0 || betaNumerator < betaDenominator) { doIntersect = FALSE; } } }

return doIntersect; } integer status; integer iDevicesAround; list lChains; list lTargets; integer iChainOfTarget(integer t) { integer x = llListFindList(lChains, [llList2Key(lTargets, t)]);

if(~x) return (x - 2);

return -1; } integer closest_target(integer chain) { integer ret = -1; vector chainpos = (llGetRootPosition() + llList2Vector(llGetLinkPrimitiveParams(llList2Integer(lChains, (chain) + 1), [PRIM_POS_LOCAL]), 0) * llGetRootRotation()); float closest = -1.0; integer n = llGetListLength(lTargets);

while(n) { --n; float distance = llVecDist(llList2Vector(llGetObjectDetails(llList2Key(lTargets, n), [OBJECT_POS] ), 0), chainpos);

if(-1.0 == closest) { closest = distance; ret = n; } else { if(distance < closest) { closest = distance; ret = n; } } }

return ret; } vector avgpos_targets() { vector avg = ( < -1.0, -1.0, -1.0 > ); integer cnt = 0; integer t = llGetListLength(lTargets);

while(t) { --t; avg += llList2Vector(llGetObjectDetails(llList2Key(lTargets, t), [OBJECT_POS] ), 0); ++cnt; }

return (avg / (float)cnt); } integer furthest_chain(vector ref) { float distmax = -1.0; integer ret = -1; integer c = llGetListLength(lChains);

while(c) { c -= 3;

if(!((llList2Key(lChains, (c) + 2) != NULL_KEY))) { float dist = llVecDist((llGetRootPosition() + llList2Vector(llGetLinkPrimitiveParams(llList2Integer(lChains, (c) + 1), [PRIM_POS_LOCAL]), 0) * llGetRootRotation()), ref);

if(distmax < dist) { distmax = dist; ret = c; } } }

return ret; } swap_chains(integer ca, integer cb) { key tmp = llList2Key(lChains, (ca) + 2); (lChains = llListReplaceList(lChains, (list)llList2Key(lChains, (cb) + 2), (ca) + 2, (ca) + 2)); (lChains = llListReplaceList(lChains, (list)tmp, (cb) + 2, (cb) + 2)); } integer find_chain_crossedby(integer chain) { vector start = (llGetRootPosition() + llList2Vector(llGetLinkPrimitiveParams(llList2Integer(lChains, (chain) + 1), [PRIM_POS_LOCAL]), 0) * llGetRootRotation()); vector end = llList2Vector(llGetObjectDetails(llList2Key(lChains, (chain) + 2), [OBJECT_POS] ), 0); integer c = llGetListLength(lChains);

while(c) { c -= 3;

if((chain != c) && (llList2Key(lChains, (c) + 2) != NULL_KEY)) { if(geom_linesegmentscross(start, end, (llGetRootPosition() + llList2Vector(llGetLinkPrimitiveParams(llList2Integer(lChains, (c) + 1), [PRIM_POS_LOCAL]), 0) * llGetRootRotation()), llList2Vector(llGetObjectDetails(llList2Key(lChains, (c) + 2), [OBJECT_POS] ), 0))) return c; } }

return -1; } mkchains() { (status -= 2 * ( !!(status & 2) ) ); llSetTimerEvent(0.0); llSay(0, "(" + (string)( (61440 - llGetUsedMemory() ) >> 10) + "kB) ~> " + "computing ..."); integer continue = llGetListLength(lTargets); vector ref = avgpos_targets();

if(!(( < -1.0, -1.0, -1.0 > ) == ref)) { integer c = furthest_chain(ref);

while(continue && (c != -1)) { integer t = closest_target(c);

if(!(-1 == t)) { (lChains = llListReplaceList(lChains, (list)llList2Key(lTargets, t), (c) + 2, (c) + 2)); lTargets = llDeleteSubList(lTargets, t, t); --continue; }

c = furthest_chain(ref); } }

lTargets = []; integer _n = llGetListLength(lChains);

while(_n) { _n -= 3;

if((llList2Key(lChains, (_n) + 2) != NULL_KEY)) if((llGetUsedMemory() < 61440) && !~llListFindList(lTargets, [llList2Key(lChains, (_n) + 2)])) lTargets += [llList2Key(lChains, (_n) + 2)]; };

integer swapped;

do { swapped = FALSE; integer c = llGetListLength(lChains);

while(c) { c -= 3;

if((llList2Key(lChains, (c) + 2) != NULL_KEY)) { integer crosses = find_chain_crossedby(c);

if(!(-1 == crosses)) { swap_chains(c, crosses); swapped = TRUE; }

integer t = closest_target(c);

if(llVecDist((llGetRootPosition() + llList2Vector(llGetLinkPrimitiveParams(llList2Integer(lChains, (c) + 1), [PRIM_POS_LOCAL]), 0) * llGetRootRotation()), llList2Vector(llGetObjectDetails(llList2Key(lTargets, t), [OBJECT_POS] ), 0)) < llVecDist((llGetRootPosition() + llList2Vector(llGetLinkPrimitiveParams(llList2Integer(lChains, (c) + 1), [PRIM_POS_LOCAL]), 0) * llGetRootRotation()), llList2Vector(llGetObjectDetails(llList2Key(lChains, (c) + 2), [OBJECT_POS] ), 0))) { integer cc = iChainOfTarget(t);

if(!(-1 == cc)) { if(geom_linesegmentscross((llGetRootPosition() + llList2Vector(llGetLinkPrimitiveParams(llList2Integer(lChains, (c) + 1), [PRIM_POS_LOCAL]), 0) * llGetRootRotation()), llList2Vector(llGetObjectDetails(llList2Key(lChains, (c) + 2), [OBJECT_POS] ), 0), (llGetRootPosition() + llList2Vector(llGetLinkPrimitiveParams(llList2Integer(lChains, (cc) + 1), [PRIM_POS_LOCAL]), 0) * llGetRootRotation()), llList2Vector(llGetObjectDetails(llList2Key(lTargets, t), [OBJECT_POS] ), 0))) { swap_chains(c, cc); swapped = TRUE; } } else llSay(0, "(" + (string)( (61440 - llGetUsedMemory() ) >> 10) + "kB) ~> " + "data mismatch"); } } } } while(swapped);

{ integer _n = llGetListLength(lChains);

while(_n) { _n -= 3;

if((llList2Key(lChains, (_n) + 2) != NULL_KEY)) llLinkParticleSystem(llList2Integer(lChains, (_n) + 1), [ PSYS_PART_MAX_AGE, 3.0, PSYS_PART_FLAGS, PSYS_PART_FOLLOW_VELOCITY_MASK | PSYS_PART_TARGET_POS_MASK | PSYS_PART_FOLLOW_SRC_MASK | PSYS_PART_EMISSIVE_MASK, PSYS_PART_START_COLOR, <llFrand(1.1), llFrand(1.1), llFrand(1.1)>, PSYS_PART_START_SCALE, <0.2, 0.2, 0.0>, PSYS_SRC_PATTERN, PSYS_SRC_PATTERN_DROP, PSYS_SRC_BURST_RATE, 0.04, PSYS_SRC_ACCEL, < 0.0, 0.0, -1.2 >, PSYS_SRC_BURST_PART_COUNT, 1, PSYS_SRC_BURST_SPEED_MIN, 3.0, PSYS_SRC_BURST_SPEED_MAX, 3.0, PSYS_SRC_TARGET_KEY, llList2Key(lChains, (_n) + 2), PSYS_SRC_MAX_AGE, 0.0, PSYS_SRC_TEXTURE, "4cde01ac-4279-2742-71e1-47ff81cc3529" ]); }; } (status -= 1 * ( !!(status & 1) ) ); llSay(0, "(" + (string)( (61440 - llGetUsedMemory() ) >> 10) + "kB) ~> " + "done"); }

default { listen(integer channel, string name, key other_device, string _MESSAGE) { if("identify" == _MESSAGE) { llRegionSayTo(other_device, -20131224, llDumpList2String([llGetLinkKey(llGetLinkNumber()), other_device, "RFEDIP-1.0", "identity"], "|")); return; }

list payload = llParseString2List((_MESSAGE), ["|"], []);

if(llGetListLength(payload) < 4) return;

if((llList2Key(payload, 0) != other_device) || (llList2Key(payload, 1) != llGetLinkKey(llGetLinkNumber())) || !(~llSubStringIndex(llList2String(payload, 2), "RFEDIP") )) return;

string token = llList2String(payload, 3);

if("tether point" == token) { if((llGetUsedMemory() < 61440) && !~llListFindList(lTargets, [llList2String(payload, 4)])) lTargets += [llList2String(payload, 4)];

return; }

if("msg_end!" == token) { if(( !!(status & 2) ) ) { --iDevicesAround; iDevicesAround = ( ( (llAbs( (iDevicesAround) >= (0) ) ) * (iDevicesAround) ) + ( (llAbs( (iDevicesAround) < (0) ) ) * (0) ) );

if(!(iDevicesAround)) mkchains(); }

return; }

if("identity" == token) { ++iDevicesAround; llRegionSayTo(other_device, -20131224, llDumpList2String([llGetLinkKey(llGetLinkNumber()), other_device, "RFEDIP-1.0", "tether"], "|")); return; }

llRegionSayTo(other_device, -20131224, llDumpList2String([llGetLinkKey(llGetLinkNumber()), other_device, "RFEDIP-1.0", "msg_end!", -20131224], "|")); } touch_start(integer t) { if(!(llGetListLength(lChains))) { llSay(0, "(" + (string)( (61440 - llGetUsedMemory() ) >> 10) + "kB) ~> " + "no chains to create"); return; }

if(( !!(status & 1) ) ) { llSay(0, "(" + (string)( (61440 - llGetUsedMemory() ) >> 10) + "kB) ~> " + "busy, please wait"); return; }

(status += 1 * !(status & 1) ); integer _n = llGetListLength(lChains);

while(_n) { _n -= 3; llLinkParticleSystem(llList2Integer(lChains, (_n) + 1), []); (lChains = llListReplaceList(lChains, (list)NULL_KEY, (_n) + 2, (_n) + 2)); };

llSay(0, "(" + (string)( (61440 - llGetUsedMemory() ) >> 10) + "kB) ~> " + "querying for devices");

llPlaySound("971bc958-ea04-194f-a78a-12826264dae4", 1);

lTargets = [];

iDevicesAround = 0;

llSetTimerEvent(30.0);

llRegionSay(-20131224, "identify");

(status += 2 * !(status & 2) ); } timer() { llSay(0, "(" + (string)( (61440 - llGetUsedMemory() ) >> 10) + "kB) ~> " + "timeout"); mkchains(); } state_entry() { status = 0; (lChains = getlinknumbersbylistnamedappend_attached(["Chain-0", "Chain-1", "Chain-2", "Chain-3", "Chain-4", "Chain-5", "Chain-6", "Chain-7"])); llListen(-20131224, "", NULL_KEY, ""); } changed(integer w) { if(w & CHANGED_LINK) { integer _n = llGetListLength(lChains);

while(_n) { _n -= 3; llLinkParticleSystem(llList2Integer(lChains, (_n) + 1), []); (lChains = llListReplaceList(lChains, (list)NULL_KEY, (_n) + 2, (_n) + 2)); };

(lChains = getlinknumbersbylistnamedappend_attached(["Chain-0", "Chain-1", "Chain-2", "Chain-3", "Chain-4", "Chain-5", "Chain-6", "Chain-7"])); } } } </lsl>


References


History

  • 2013-12-27: initial page created
  • 2013-12-27: tokens changed to something more easily readable; different indentation used for LSL script
  • 2013-12-27: tried to improve the "About" section
  • 2013-12-29: added second example
  • todo: create some wiki as a central place to put information about devices and tokens they use, make example devices available on marketplace