Represents all of the texturable faces for an object
Grid objects have infinite faces, with each face using the properties of the default face unless set otherwise. So if you have a TextureEntry with a default texture uuid of X, and face 18 has a texture UUID of Y, every face would be textured with X except for face 18 that uses Y. In practice however, primitives utilize a maximum of nine faces
Ejemplo n.º 1
0
        public void TestCreate()
        {
            TestHelper.InMethod();
//            log4net.Config.XmlConfigurator.Configure();

            IConfigSource config = new IniConfigSource();
            config.AddConfig("NPC");
            config.Configs["NPC"].Set("Enabled", "true");

            AvatarFactoryModule afm = new AvatarFactoryModule();
            TestScene scene = SceneSetupHelpers.SetupScene();
            SceneSetupHelpers.SetupSceneModules(scene, config, afm, new NPCModule());
            TestClient originalClient = SceneSetupHelpers.AddClient(scene, TestHelper.ParseTail(0x1));
//            ScenePresence originalAvatar = scene.GetScenePresence(originalClient.AgentId);

            // 8 is the index of the first baked texture in AvatarAppearance
            UUID originalFace8TextureId = TestHelper.ParseTail(0x10);
            Primitive.TextureEntry originalTe = new Primitive.TextureEntry(UUID.Zero);
            Primitive.TextureEntryFace originalTef = originalTe.CreateFace(8);
            originalTef.TextureID = originalFace8TextureId;

            // We also need to add the texture to the asset service, otherwise the AvatarFactoryModule will tell
            // ScenePresence.SendInitialData() to reset our entire appearance.
            scene.AssetService.Store(AssetHelpers.CreateAsset(originalFace8TextureId));

            afm.SetAppearance(originalClient, originalTe, null);

            INPCModule npcModule = scene.RequestModuleInterface<INPCModule>();
            UUID npcId = npcModule.CreateNPC("John", "Smith", new Vector3(128, 128, 30), scene, originalClient.AgentId);

            ScenePresence npc = scene.GetScenePresence(npcId);

            Assert.That(npc, Is.Not.Null);
            Assert.That(npc.Appearance.Texture.FaceTextures[8].TextureID, Is.EqualTo(originalFace8TextureId));
        }
Ejemplo n.º 2
0
        public void AvatarAppearanceTest()
        {
            Primitive.TextureEntry textures = new Primitive.TextureEntry(AppearanceManager.DEFAULT_AVATAR_TEXTURE);
            byte[] visualParams = new byte[218];
            rand.NextBytes(visualParams);

            UUID receivedAgentID = UUID.Zero;
            Primitive.TextureEntry receivedTextureEntry = null;
            byte[] receivedVisualParams = null;

            AutoResetEvent callbackEvent = new AutoResetEvent(false);
            OutgoingPacketCallback callback = new OutgoingPacketCallback(
                delegate(Packet packet, UUID agentID, PacketCategory category)
                {
                    if (packet is AvatarAppearancePacket)
                    {
                        AvatarAppearancePacket appearance = (AvatarAppearancePacket)packet;

                        receivedAgentID = appearance.Sender.ID;
                        receivedTextureEntry = new Primitive.TextureEntry(appearance.ObjectData.TextureEntry, 0, appearance.ObjectData.TextureEntry.Length);
                        receivedVisualParams = new byte[appearance.VisualParam.Length];
                        for (int i = 0; i < receivedVisualParams.Length; i++)
                            receivedVisualParams[i] = appearance.VisualParam[i].ParamValue;

                        callbackEvent.Set();
                    }

                    return false;
                }
            );

            simian.Scenes[0].UDP.OnOutgoingPacket += callback;
            simian.Scenes[0].AgentAppearance(this, agent, textures, visualParams);

            Assert.IsTrue(callbackEvent.WaitOne(1000, false), "Timed out waiting for callback");
            simian.Scenes[0].UDP.OnOutgoingPacket -= callback;
            
            Assert.That(receivedAgentID == agent.ID, "Agent ID mismatch");
            
            Assert.That(receivedVisualParams.Length == 218, "VisualParams has an incorrect length");
            for (int i = 0; i < 218; i++)
                Assert.That(receivedVisualParams[i] == visualParams[i], "VisualParam mismatch at position " + i);

            Assert.That(receivedTextureEntry.DefaultTexture.TextureID == textures.DefaultTexture.TextureID, "Default texture mismatch");
            for (int i = 0; i < receivedTextureEntry.FaceTextures.Length; i++)
            {
                Assert.That(
                    (receivedTextureEntry.FaceTextures[i] == null && textures.FaceTextures[i] == null) ||
                    (receivedTextureEntry.FaceTextures[i].TextureID == textures.FaceTextures[i].TextureID), "TextureEntry mismatch at position " + i);
            }
        }
        public void TestSetAppearance()
        {
            TestHelpers.InMethod();
//            TestHelpers.EnableLogging();

            UUID userId = TestHelpers.ParseTail(0x1);
            UUID bakedTextureID = TestHelpers.ParseTail(0x2);

            // We need an asset cache because otherwise the LocalAssetServiceConnector will short-circuit directly
            // to the AssetService, which will then store temporary and local assets permanently
            CoreAssetCache assetCache = new CoreAssetCache();
            
            AvatarFactoryModule afm = new AvatarFactoryModule();
            TestScene scene = new SceneHelpers(assetCache).SetupScene();
            SceneHelpers.SetupSceneModules(scene, afm);
            ScenePresence sp = SceneHelpers.AddScenePresence(scene, userId);

            // TODO: Use the actual BunchOfCaps functionality once we slot in the CapabilitiesModules
            AssetBase bakedTextureAsset;
            bakedTextureAsset 
                = new AssetBase(
                    bakedTextureID, "Test Baked Texture", (sbyte)AssetType.Texture, userId.ToString());
            bakedTextureAsset.Data = new byte[] { 2 }; // Not necessary to have a genuine JPEG2000 asset here yet
            bakedTextureAsset.Temporary = true;
            bakedTextureAsset.Local = true;
            scene.AssetService.Store(bakedTextureAsset);

            byte[] visualParams = new byte[AvatarAppearance.VISUALPARAM_COUNT];
            for (byte i = 0; i < visualParams.Length; i++)
                visualParams[i] = i;

            Primitive.TextureEntry bakedTextureEntry = new Primitive.TextureEntry(TestHelpers.ParseTail(0x10));
            uint eyesFaceIndex = (uint)AppearanceManager.BakeTypeToAgentTextureIndex(BakeType.Eyes);
            Primitive.TextureEntryFace eyesFace = bakedTextureEntry.CreateFace(eyesFaceIndex);

            int rebakeRequestsReceived = 0;
            ((TestClient)sp.ControllingClient).OnReceivedSendRebakeAvatarTextures += id => rebakeRequestsReceived++;

            // This is the alpha texture
            eyesFace.TextureID = bakedTextureID;
            afm.SetAppearance(sp, bakedTextureEntry, visualParams, null);
    
            Assert.That(rebakeRequestsReceived, Is.EqualTo(0));

            AssetBase eyesBake = scene.AssetService.Get(bakedTextureID.ToString());
            Assert.That(eyesBake, Is.Not.Null);
            Assert.That(eyesBake.Temporary, Is.True);
            Assert.That(eyesBake.Local, Is.True);
        }
Ejemplo n.º 4
0
Archivo: Penny.cs Proyecto: zadark/par
 public Packet ApHand(Packet packet, IPEndPoint sim)
 {
     if (form.getChecked()==false)
         {
             return packet;
         }
         AgentSetAppearancePacket packet2 = (AgentSetAppearancePacket) packet;
         if ((packet2.ObjectData == null) || (packet2.ObjectData.TextureEntry == null))
         {
             return packet;
         }
         Primitive.TextureEntry entry = new Primitive.TextureEntry(packet2.ObjectData.TextureEntry, 0, packet2.ObjectData.TextureEntry.Length);
         if (((entry == null) || (entry.FaceTextures == null)) || (entry.FaceTextures.Length <= 0))
         {
             return packet;
         }
         Console.WriteLine("Penny is replacing textures...");
         UUID uuid =  new UUID("5aa5c70d-d787-571b-0495-4fc1bdef1500");
         for (int i = 0; i <= 7; i++)
         {
             if (entry.FaceTextures[i] != null)
             {
                 entry.FaceTextures[i].TextureID = uuid;
             }
         }
         for (int j = 12; j <= 0x12; j++)
         {
             if (entry.FaceTextures[j] != null)
             {
                 entry.FaceTextures[j].TextureID = uuid;
             }
         }
         if (packet2.ObjectData != null)
         {
             packet2.ObjectData.TextureEntry = entry.GetBytes();
         }
         Console.WriteLine("OK! Thanks Day!");
         return packet2;
 }
Ejemplo n.º 5
0
 protected virtual void SetDefaultTexture()
 {
     m_texture = new Primitive.TextureEntry(new UUID("C228D1CF-4B5D-4BA8-84F4-899A0796AA97"));
     for (uint i = 0; i < TEXTURE_COUNT; i++)
         m_texture.CreateFace(i).TextureID = new UUID(AppearanceManager.DEFAULT_AVATAR_TEXTURE);
 }
Ejemplo n.º 6
0
        public AvatarAppearance(UUID avatarID, AvatarWearable[] wearables, Primitive.TextureEntry textureEntry, byte[] visualParams)
        {
            //            m_log.WarnFormat("[AVATAR APPEARANCE] create initialized appearance for {0}",avatarID);

            m_serial = 1;
            m_owner = avatarID;

            if (wearables != null)
                m_wearables = wearables;
            else
                SetDefaultWearables();

            if (textureEntry != null)
                m_texture = textureEntry;
            else
                SetDefaultTexture();

            if (visualParams != null)
                m_visualparams = visualParams;
            else
                SetDefaultParams();

            SetHeight();

            m_attachments = new Dictionary<int, List<AvatarAttachment>>();
        }
Ejemplo n.º 7
0
 Primitive.TextureEntry Copy (Primitive.TextureEntry c, UUID id)
 {
     Primitive.TextureEntry Textures = new Primitive.TextureEntry (id);
     Textures.DefaultTexture = CopyFace (c.DefaultTexture, Textures.DefaultTexture);
     //for(int i = 0; i < c.FaceTextures.Length; i++)
     //{
     //    Textures.FaceTextures[i] = c.FaceTextures[i];
     //}
     return Textures;
 }
Ejemplo n.º 8
0
        /// <summary>Process an incoming packet and raise the appropriate events</summary>
        /// <param name="sender">The sender</param>
        /// <param name="e">The EventArgs object containing the packet data</param>
        protected void AvatarAppearanceHandler(object sender, PacketReceivedEventArgs e)
        {
            if (m_AvatarAppearance != null || Client.Settings.AVATAR_TRACKING)
            {
                Packet packet = e.Packet;
                Simulator simulator = e.Simulator;

                AvatarAppearancePacket appearance = (AvatarAppearancePacket)packet;

                List<byte> visualParams = new List<byte>();
                foreach (AvatarAppearancePacket.VisualParamBlock block in appearance.VisualParam)
                {
                    visualParams.Add(block.ParamValue);
                }

                Primitive.TextureEntry textureEntry = new Primitive.TextureEntry(appearance.ObjectData.TextureEntry, 0,
                        appearance.ObjectData.TextureEntry.Length);

                Primitive.TextureEntryFace defaultTexture = textureEntry.DefaultTexture;
                Primitive.TextureEntryFace[] faceTextures = textureEntry.FaceTextures;

                Avatar av = simulator.ObjectsAvatars.Find((Avatar a) => { return a.ID == appearance.Sender.ID; });
                if (av != null)
                {
                    av.Textures = textureEntry;
                    av.VisualParameters = visualParams.ToArray();
                }

                OnAvatarAppearance(new AvatarAppearanceEventArgs(simulator, appearance.Sender.ID, appearance.Sender.IsTrial,
                    defaultTexture, faceTextures, visualParams));
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Set up appearance texture ids.
        /// </summary>
        /// <returns>
        /// True if any existing texture id was changed by the new data.
        /// False if there were no changes or no existing texture ids.
        /// </returns>
        public virtual bool SetTextureEntries(Primitive.TextureEntry textureEntry)
        {
            if (textureEntry == null)
                return false;

            // There are much simpler versions of this copy that could be
            // made. We determine if any of the textures actually
            // changed to know if the appearance should be saved later
            bool changed = false;
            for (uint i = 0; i < AvatarAppearance.TEXTURE_COUNT; i++)
            {
                Primitive.TextureEntryFace newface = textureEntry.FaceTextures[i];
                Primitive.TextureEntryFace oldface = m_texture.FaceTextures[i];

                if (newface == null)
                {
                    if (oldface == null)
                        continue;
                }
                else
                {
                    if (oldface != null && oldface.TextureID == newface.TextureID)
                        continue;
                }

                changed = true;
            }

            m_texture = textureEntry;
            
            return changed;
        }
Ejemplo n.º 10
0
        public AvatarAppearance(AvatarAppearance appearance, bool copyWearables, bool copyBaked)
        {
//            m_log.WarnFormat("[AVATAR APPEARANCE] create from an existing appearance");

            if (appearance == null)
            {
                m_serial = 0;
                SetDefaultWearables();
                SetDefaultTexture();
                SetDefaultParams();
//                SetHeight();
                SetSize(new Vector3(0.45f, 0.6f, 1.9f));
                m_attachments = new Dictionary<int, List<AvatarAttachment>>();

                return;
            }

            m_serial = appearance.Serial;

            if (copyWearables && (appearance.Wearables != null))
            {
                m_wearables = new AvatarWearable[appearance.Wearables.Length];
                for (int i = 0; i < appearance.Wearables.Length; i++)
                {
                    m_wearables[i] = new AvatarWearable();
                    AvatarWearable wearable = appearance.Wearables[i];
                    for (int j = 0; j < wearable.Count; j++)
                            m_wearables[i].Add(wearable[j].ItemID, wearable[j].AssetID);                       
                 }
            }
            else
                ClearWearables();

            m_texture = null;
            if (appearance.Texture != null)
            {
                byte[] tbytes = appearance.Texture.GetBytes();
                m_texture = new Primitive.TextureEntry(tbytes,0,tbytes.Length);
                if (copyBaked && appearance.m_cacheitems != null)
                    m_cacheitems = (WearableCacheItem[])appearance.m_cacheitems.Clone();
                else
                    m_cacheitems = null;
            }

            m_visualparams = null;
            if (appearance.VisualParams != null)
                m_visualparams = (byte[])appearance.VisualParams.Clone();

//            m_avatarHeight = appearance.m_avatarHeight;
            SetSize(appearance.AvatarSize);

            // Copy the attachment, force append mode since that ensures consistency
            m_attachments = new Dictionary<int, List<AvatarAttachment>>();
            foreach (AvatarAttachment attachment in appearance.GetAttachments())
                AppendAttachment(new AvatarAttachment(attachment));
        }
        /// <summary>
        /// Parses add request
        /// </summary>
        /// <param name="request"></param>
        /// <param name="AgentId"></param>
        /// <param name="cap"></param>
        /// <returns></returns>
        public Hashtable ProcessAdd(Hashtable request, UUID AgentId, Caps cap)
        {
            Hashtable responsedata = new Hashtable();
            responsedata["int_response_code"] = 400; //501; //410; //404;
            responsedata["content_type"] = "text/plain";
            responsedata["keepalive"] = false;
            responsedata["str_response_string"] = "Request wasn't what was expected";
            ScenePresence avatar;

            if (!m_scene.TryGetScenePresence(AgentId, out avatar))
                return responsedata;

            OSDMap r = (OSDMap)OSDParser.Deserialize((string)request["requestbody"]);
            UploadObjectAssetMessage message = new UploadObjectAssetMessage();
            try
            {
                message.Deserialize(r);

            }
            catch (Exception ex)
            {
                m_log.Error("[UPLOAD OBJECT ASSET MODULE]: Error deserializing message " + ex.ToString());
                message = null;
            }

            if (message == null)
            {
                responsedata["int_response_code"] = 400; //501; //410; //404;
                responsedata["content_type"] = "text/plain";
                responsedata["keepalive"] = false;
                responsedata["str_response_string"] =
                    "<llsd><map><key>error</key><string>Error parsing Object</string></map></llsd>";

                return responsedata;
            }

            Vector3 pos = avatar.AbsolutePosition + (Vector3.UnitX * avatar.Rotation);
            Quaternion rot = Quaternion.Identity;
            Vector3 rootpos = Vector3.Zero;
//            Quaternion rootrot = Quaternion.Identity;

            SceneObjectGroup rootGroup = null;
            SceneObjectGroup[] allparts = new SceneObjectGroup[message.Objects.Length];
            for (int i = 0; i < message.Objects.Length; i++)
            {
                UploadObjectAssetMessage.Object obj = message.Objects[i];
                PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox();

                if (i == 0)
                {
                    rootpos = obj.Position;
//                    rootrot = obj.Rotation;                    
                }

                // Combine the extraparams data into it's ugly blob again....
                //int bytelength = 0;
                //for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++)
                //{
                //    bytelength += obj.ExtraParams[extparams].ExtraParamData.Length;
                //}
                //byte[] extraparams = new byte[bytelength];
                //int position = 0;



                //for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++)
                //{
                //    Buffer.BlockCopy(obj.ExtraParams[extparams].ExtraParamData, 0, extraparams, position,
                //                     obj.ExtraParams[extparams].ExtraParamData.Length);
                //
                //    position += obj.ExtraParams[extparams].ExtraParamData.Length;
               // }

                //pbs.ExtraParams = extraparams;
                for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++)
                {
                    UploadObjectAssetMessage.Object.ExtraParam extraParam = obj.ExtraParams[extparams];
                    switch ((ushort)extraParam.Type)
                    {
                        case (ushort)ExtraParamType.Sculpt:
                            Primitive.SculptData sculpt = new Primitive.SculptData(extraParam.ExtraParamData, 0);

                            pbs.SculptEntry = true;

                            pbs.SculptTexture = obj.SculptID;
                            pbs.SculptType = (byte)sculpt.Type;

                            break;
                        case (ushort)ExtraParamType.Flexible:
                            Primitive.FlexibleData flex = new Primitive.FlexibleData(extraParam.ExtraParamData, 0);
                            pbs.FlexiEntry = true;
                            pbs.FlexiDrag = flex.Drag;
                            pbs.FlexiForceX = flex.Force.X;
                            pbs.FlexiForceY = flex.Force.Y;
                            pbs.FlexiForceZ = flex.Force.Z;
                            pbs.FlexiGravity = flex.Gravity;
                            pbs.FlexiSoftness = flex.Softness;
                            pbs.FlexiTension = flex.Tension;
                            pbs.FlexiWind = flex.Wind;
                            break;
                        case (ushort)ExtraParamType.Light:
                            Primitive.LightData light = new Primitive.LightData(extraParam.ExtraParamData, 0);
                            pbs.LightColorA = light.Color.A;
                            pbs.LightColorB = light.Color.B;
                            pbs.LightColorG = light.Color.G;
                            pbs.LightColorR = light.Color.R;
                            pbs.LightCutoff = light.Cutoff;
                            pbs.LightEntry = true;
                            pbs.LightFalloff = light.Falloff;
                            pbs.LightIntensity = light.Intensity;
                            pbs.LightRadius = light.Radius;
                            break;
                        case 0x40:
                            pbs.ReadProjectionData(extraParam.ExtraParamData, 0);
                            break;
                    }
                }

                pbs.PathBegin = (ushort) obj.PathBegin;
                pbs.PathCurve = (byte) obj.PathCurve;
                pbs.PathEnd = (ushort) obj.PathEnd;
                pbs.PathRadiusOffset = (sbyte) obj.RadiusOffset;
                pbs.PathRevolutions = (byte) obj.Revolutions;
                pbs.PathScaleX = (byte) obj.ScaleX;
                pbs.PathScaleY = (byte) obj.ScaleY;
                pbs.PathShearX = (byte) obj.ShearX;
                pbs.PathShearY = (byte) obj.ShearY;
                pbs.PathSkew = (sbyte) obj.Skew;
                pbs.PathTaperX = (sbyte) obj.TaperX;
                pbs.PathTaperY = (sbyte) obj.TaperY;
                pbs.PathTwist = (sbyte) obj.Twist;
                pbs.PathTwistBegin = (sbyte) obj.TwistBegin;
                pbs.HollowShape = (HollowShape) obj.ProfileHollow;
                pbs.PCode = (byte) PCode.Prim;
                pbs.ProfileBegin = (ushort) obj.ProfileBegin;
                pbs.ProfileCurve = (byte) obj.ProfileCurve;
                pbs.ProfileEnd = (ushort) obj.ProfileEnd;
                pbs.Scale = obj.Scale;
                pbs.State = (byte) 0;
                pbs.LastAttachPoint = (byte) 0;
                SceneObjectPart prim = new SceneObjectPart();
                prim.UUID = UUID.Random();
                prim.CreatorID = AgentId;
                prim.OwnerID = AgentId;
                prim.GroupID = obj.GroupID;
                prim.LastOwnerID = prim.OwnerID;
                prim.CreationDate = Util.UnixTimeSinceEpoch();
                prim.Name = obj.Name;
                prim.Description = "";

                prim.PayPrice[0] = -2;
                prim.PayPrice[1] = -2;
                prim.PayPrice[2] = -2;
                prim.PayPrice[3] = -2;
                prim.PayPrice[4] = -2;
                Primitive.TextureEntry tmp =
                    new Primitive.TextureEntry(UUID.Parse("89556747-24cb-43ed-920b-47caed15465f"));

                for (int j = 0; j < obj.Faces.Length; j++)
                {
                    UploadObjectAssetMessage.Object.Face face = obj.Faces[j];

                    Primitive.TextureEntryFace primFace = tmp.CreateFace((uint) j);

                    primFace.Bump = face.Bump;
                    primFace.RGBA = face.Color;
                    primFace.Fullbright = face.Fullbright;
                    primFace.Glow = face.Glow;
                    primFace.TextureID = face.ImageID;
                    primFace.Rotation = face.ImageRot;
                    primFace.MediaFlags = ((face.MediaFlags & 1) != 0);

                    primFace.OffsetU = face.OffsetS;
                    primFace.OffsetV = face.OffsetT;
                    primFace.RepeatU = face.ScaleS;
                    primFace.RepeatV = face.ScaleT;
                    primFace.TexMapType = (MappingType) (face.MediaFlags & 6);
                }

                pbs.TextureEntry = tmp.GetBytes();
                prim.Shape = pbs;
                prim.Scale = obj.Scale;
                
                SceneObjectGroup grp = new SceneObjectGroup();

                grp.SetRootPart(prim);
                prim.ParentID = 0;
                if (i == 0)
                {
                    rootGroup = grp;
                   
                }
                grp.AttachToScene(m_scene);
                grp.AbsolutePosition = obj.Position;
                prim.RotationOffset = obj.Rotation;
                
                // Required for linking
                grp.RootPart.ClearUpdateSchedule();
                
                if (m_scene.Permissions.CanRezObject(1, avatar.UUID, pos))
                {
                    m_scene.AddSceneObject(grp);
                    grp.AbsolutePosition = obj.Position;
                }
                
                allparts[i] = grp;
            }

            for (int j = 1; j < allparts.Length; j++)
            {
                // Required for linking
                rootGroup.RootPart.ClearUpdateSchedule();
                allparts[j].RootPart.ClearUpdateSchedule();
                rootGroup.LinkToGroup(allparts[j]);
            }

            rootGroup.ScheduleGroupForFullUpdate();
            pos
                = m_scene.GetNewRezLocation(
                    Vector3.Zero, rootpos, UUID.Zero, rot, (byte)1, 1, true, allparts[0].GroupScale, false);
           
            responsedata["int_response_code"] = 200; //501; //410; //404;
            responsedata["content_type"] = "text/plain";
            responsedata["keepalive"] = false;
            responsedata["str_response_string"] = String.Format("<llsd><map><key>local_id</key>{0}</map></llsd>", ConvertUintToBytes(allparts[0].LocalId));

            return responsedata;
        }
Ejemplo n.º 12
0
        public void TestCreate()
        {
            TestHelpers.InMethod();
//            log4net.Config.XmlConfigurator.Configure();

            ScenePresence sp = SceneHelpers.AddScenePresence(scene, TestHelpers.ParseTail(0x1));
//            ScenePresence originalAvatar = scene.GetScenePresence(originalClient.AgentId);

            // 8 is the index of the first baked texture in AvatarAppearance
            UUID originalFace8TextureId = TestHelpers.ParseTail(0x10);
            Primitive.TextureEntry originalTe = new Primitive.TextureEntry(UUID.Zero);
            Primitive.TextureEntryFace originalTef = originalTe.CreateFace(8);
            originalTef.TextureID = originalFace8TextureId;

            // We also need to add the texture to the asset service, otherwise the AvatarFactoryModule will tell
            // ScenePresence.SendInitialData() to reset our entire appearance.
            scene.AssetService.Store(AssetHelpers.CreateNotecardAsset(originalFace8TextureId));

            afm.SetAppearance(sp, originalTe, null);

            INPCModule npcModule = scene.RequestModuleInterface<INPCModule>();
            UUID npcId = npcModule.CreateNPC("John", "Smith", new Vector3(128, 128, 30), scene, sp.Appearance);

            ScenePresence npc = scene.GetScenePresence(npcId);

            Assert.That(npc, Is.Not.Null);
            Assert.That(npc.Appearance.Texture.FaceTextures[8].TextureID, Is.EqualTo(originalFace8TextureId));
            Assert.That(umm.GetUserName(npc.UUID), Is.EqualTo(string.Format("{0} {1}", npc.Firstname, npc.Lastname)));
        }
Ejemplo n.º 13
0
        private void TestAddRemoveNPCs(int numberOfNpcs)
        {
            ScenePresence sp = SceneHelpers.AddScenePresence(scene, TestHelpers.ParseTail(0x1));
//            ScenePresence originalAvatar = scene.GetScenePresence(originalClient.AgentId);

            // 8 is the index of the first baked texture in AvatarAppearance
            UUID originalFace8TextureId = TestHelpers.ParseTail(0x10);
            Primitive.TextureEntry originalTe = new Primitive.TextureEntry(UUID.Zero);
            Primitive.TextureEntryFace originalTef = originalTe.CreateFace(8);
            originalTef.TextureID = originalFace8TextureId;

            // We also need to add the texture to the asset service, otherwise the AvatarFactoryModule will tell
            // ScenePresence.SendInitialData() to reset our entire appearance.
            scene.AssetService.Store(AssetHelpers.CreateNotecardAsset(originalFace8TextureId));

            afm.SetAppearance(sp, originalTe, null);

            INPCModule npcModule = scene.RequestModuleInterface<INPCModule>();

            List<UUID> npcs = new List<UUID>();

            long startGcMemory = GC.GetTotalMemory(true);
            Stopwatch sw = new Stopwatch();
            sw.Start();

            for (int i = 0; i < numberOfNpcs; i++)
            {
                npcs.Add(
                    npcModule.CreateNPC("John", "Smith", new Vector3(128, 128, 30), UUID.Zero, true, scene, sp.Appearance));
            }

            for (int i = 0; i < numberOfNpcs; i++)
            {
                Assert.That(npcs[i], Is.Not.Null);

                ScenePresence npc = scene.GetScenePresence(npcs[i]);
                Assert.That(npc, Is.Not.Null);
            }

            for (int i = 0; i < numberOfNpcs; i++)
            {
                Assert.That(npcModule.DeleteNPC(npcs[i], scene), Is.True);
                ScenePresence npc = scene.GetScenePresence(npcs[i]);
                Assert.That(npc, Is.Null);
            }

            sw.Stop();

            long endGcMemory = GC.GetTotalMemory(true);

            Console.WriteLine("Took {0} ms", sw.ElapsedMilliseconds);
            Console.WriteLine(
                "End {0} MB, Start {1} MB, Diff {2} MB",
                endGcMemory / 1024 / 1024,
                startGcMemory / 1024 / 1024,
                (endGcMemory - startGcMemory) / 1024 / 1024);
        }
Ejemplo n.º 14
0
        public void CopyFrom(AgentData cAgent)
        {
            m_originRegionID = cAgent.RegionID;

            m_callbackURI = cAgent.CallbackURI;

            m_pos = cAgent.Position;
            m_velocity = cAgent.Velocity;
            m_CameraCenter = cAgent.Center;
            //m_avHeight = cAgent.Size.Z;
            m_CameraAtAxis = cAgent.AtAxis;
            m_CameraLeftAxis = cAgent.LeftAxis;
            m_CameraUpAxis = cAgent.UpAxis;

            m_DrawDistance = cAgent.Far;

            if ((cAgent.Throttles != null) && cAgent.Throttles.Length > 0)
                ControllingClient.SetChildAgentThrottle(cAgent.Throttles);

            m_headrotation = cAgent.HeadRotation;
            m_bodyRot = cAgent.BodyRotation;
            m_AgentControlFlags = (AgentManager.ControlFlags)cAgent.ControlFlags; 

            if (m_scene.Permissions.IsGod(new UUID(cAgent.AgentID)))
                m_godLevel = cAgent.GodLevel;
            m_setAlwaysRun = cAgent.AlwaysRun;

            uint i = 0;
            try
            {
                if (cAgent.Wearables == null)
                   cAgent.Wearables  = new UUID[0];
                AvatarWearable[] wears = new AvatarWearable[cAgent.Wearables.Length / 2];
                for (uint n = 0; n < cAgent.Wearables.Length; n += 2)
                {
                    UUID itemId = cAgent.Wearables[n];
                    UUID assetId = cAgent.Wearables[n + 1];
                    wears[i++] = new AvatarWearable(itemId, assetId);
                }
                m_appearance.Wearables = wears;
                Primitive.TextureEntry te;
                if (cAgent.AgentTextures != null && cAgent.AgentTextures.Length > 1)
                    te = new Primitive.TextureEntry(cAgent.AgentTextures, 0, cAgent.AgentTextures.Length);
                else
                    te = AvatarAppearance.GetDefaultTexture();
                if ((cAgent.VisualParams == null) || (cAgent.VisualParams.Length < AvatarAppearance.VISUALPARAM_COUNT))
                    cAgent.VisualParams = AvatarAppearance.GetDefaultVisualParams();
                m_appearance.SetAppearance(te, (byte[])cAgent.VisualParams.Clone());
            }
            catch (Exception e)
            {
                m_log.Warn("[SCENE PRESENCE]: exception in CopyFrom " + e.Message);
            }

            // Attachments
            try
            {
                if (cAgent.Attachments != null)
                {
                    foreach (AttachmentData att in cAgent.Attachments)
                    {
                        m_appearance.SetAttachment(att.AttachPoint, att.ItemID, att.AssetID);
                    }
                }
            }
            catch { } 

            // Animations
            try
            {
                Animator.ResetAnimations();
                Animator.Animations.FromArray(cAgent.Anims);
            }
            catch {  }

            //cAgent.GroupID = ??
            //Groups???
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Convert raw uploaded data into the appropriate asset and item.
        /// </summary>
        /// <param name="assetID"></param>
        /// <param name="inventoryItem"></param>
        /// <param name="data"></param>
        public void UploadCompleteHandler(string assetName, string assetDescription, UUID assetID,
                                          UUID inventoryItem, UUID parentFolder, byte[] data, string inventoryType,
                                          string assetType, int cost,
                                          UUID texturesFolder, int nreqtextures, int nreqmeshs, int nreqinstances,
                                          bool IsAtestUpload, ref string error,
                                          ref int nextOwnerMask, ref int groupMask, ref int everyoneMask)
        {
            lock (m_ModelCost)
                m_FileAgentInventoryState = FileAgentInventoryState.processUpload;

            m_log.DebugFormat(
                "[BUNCH OF CAPS]: Uploaded asset {0} for inventory item {1}, inv type {2}, asset type {3}",
                assetID, inventoryItem, inventoryType, assetType);

            sbyte assType = 0;
            sbyte inType = 0;

            IClientAPI client = null;

            UUID owner_id = m_HostCapsObj.AgentID;
            UUID creatorID;

            bool istest = IsAtestUpload && m_enableFreeTestUpload && (cost > 0);

            bool restrictPerms = m_RestrictFreeTestUploadPerms && istest;

            if (istest && m_testAssetsCreatorID != UUID.Zero)
                creatorID = m_testAssetsCreatorID;
            else
                creatorID = owner_id;

            string creatorIDstr = creatorID.ToString();

            IMoneyModule mm = m_Scene.RequestModuleInterface<IMoneyModule>();
            if (mm != null)
            {
                // make sure client still has enougth credit
                if (!mm.UploadCovered(m_HostCapsObj.AgentID, (int)cost))
                {
                    error = "Insufficient funds.";
                    return;
                }
            }

            // strings to types
            if (inventoryType == "sound")
            {
                inType = (sbyte)InventoryType.Sound;
                assType = (sbyte)AssetType.Sound;
            }
            else if (inventoryType == "snapshot")
            {
                inType = (sbyte)InventoryType.Snapshot;
            }
            else if (inventoryType == "animation")
            {
                inType = (sbyte)InventoryType.Animation;
                assType = (sbyte)AssetType.Animation;
            }
            else if (inventoryType == "animset")
            {
                inType = (sbyte)CustomInventoryType.AnimationSet;
                assType = (sbyte)CustomAssetType.AnimationSet;
                m_log.Debug("got animset upload request");
            }
            else if (inventoryType == "wearable")
            {
                inType = (sbyte)InventoryType.Wearable;
                switch (assetType)
                {
                    case "bodypart":
                        assType = (sbyte)AssetType.Bodypart;
                        break;
                    case "clothing":
                        assType = (sbyte)AssetType.Clothing;
                        break;
                }
            }
            else if (inventoryType == "object")
            {
                if (assetType == "mesh") // this code for now is for mesh models uploads only
                {
                    inType = (sbyte)InventoryType.Object;
                    assType = (sbyte)AssetType.Object;

                    List<Vector3> positions = new List<Vector3>();
                    List<Quaternion> rotations = new List<Quaternion>();
                    OSDMap request = (OSDMap)OSDParser.DeserializeLLSDXml(data);

                    // compare and get updated information
/* does nothing still we do need something to avoid special viewer to upload something diferent from the cost estimation
                    bool mismatchError = true;

                    while (mismatchError)
                    {
                        mismatchError = false;
                    }

                    if (mismatchError)
                    {
                        error = "Upload and fee estimation information don't match";
                        lock (m_ModelCost)
                            m_FileAgentInventoryState = FileAgentInventoryState.idle;

                        return;
                    }
*/
                    OSDArray instance_list = (OSDArray)request["instance_list"];
                    OSDArray mesh_list = (OSDArray)request["mesh_list"];
                    OSDArray texture_list = (OSDArray)request["texture_list"];
                    SceneObjectGroup grp = null;

                    // create and store texture assets
                    bool doTextInv = (!istest && m_enableModelUploadTextureToInventory &&
                                    texturesFolder != UUID.Zero);


                    List<UUID> textures = new List<UUID>();

                   
//                    if (doTextInv)
                        m_Scene.TryGetClient(m_HostCapsObj.AgentID, out client);

                    if(client == null) // don't put textures in inventory if there is no client
                        doTextInv = false;

                    for (int i = 0; i < texture_list.Count; i++)
                    {
                        AssetBase textureAsset = new AssetBase(UUID.Random(), assetName, (sbyte)AssetType.Texture, creatorIDstr);
                        textureAsset.Data = texture_list[i].AsBinary();
                        if (istest)
                            textureAsset.Local = true;
                        m_assetService.Store(textureAsset);
                        textures.Add(textureAsset.FullID);

                        if (doTextInv)
                        {
                            string name = assetName;
                            if (name.Length > 25)
                                name = name.Substring(0, 24);
                            name += "_Texture#" + i.ToString();
                            InventoryItemBase texitem = new InventoryItemBase();
                            texitem.Owner = m_HostCapsObj.AgentID;
                            texitem.CreatorId = creatorIDstr;
                            texitem.CreatorData = String.Empty;
                            texitem.ID = UUID.Random();
                            texitem.AssetID = textureAsset.FullID;
                            texitem.Description = "mesh model texture";
                            texitem.Name = name;
                            texitem.AssetType = (int)AssetType.Texture;
                            texitem.InvType = (int)InventoryType.Texture;
                            texitem.Folder = texturesFolder;

                            texitem.CurrentPermissions
                                = (uint)(PermissionMask.Move | PermissionMask.Copy | PermissionMask.Modify | PermissionMask.Transfer | PermissionMask.Export);

                            texitem.BasePermissions = (uint)PermissionMask.All | (uint)PermissionMask.Export;
                            texitem.EveryOnePermissions = 0;
                            texitem.NextPermissions = (uint)PermissionMask.All;
                            texitem.CreationDate = Util.UnixTimeSinceEpoch();

                            m_Scene.AddInventoryItem(client, texitem);
                            texitem = null;
                        }
                    }

                    // create and store meshs assets
                    List<UUID> meshAssets = new List<UUID>();
                    List<bool> meshAvatarSkeletons = new List<bool>();
                    List<bool> meshAvatarColliders = new List<bool>();

                    bool curAvSkeleton;
                    bool curAvCollider;
                    for (int i = 0; i < mesh_list.Count; i++)
                    {
                        curAvSkeleton = false;
                        curAvCollider = false;

                        // we do need to parse the mesh now
                        OSD osd = OSDParser.DeserializeLLSDBinary(mesh_list[i]);
                        if (osd is OSDMap)
                        {
                            OSDMap mosd = (OSDMap)osd;
                            if (mosd.ContainsKey("skeleton"))
                            {
                                OSDMap skeleton = (OSDMap)mosd["skeleton"];
                                int sksize = skeleton["size"].AsInteger();
                                if (sksize > 0)
                                    curAvSkeleton = true;
                            }
                        }

                        AssetBase meshAsset = new AssetBase(UUID.Random(), assetName, (sbyte)AssetType.Mesh, creatorIDstr);
                        meshAsset.Data = mesh_list[i].AsBinary();
                        if (istest)
                            meshAsset.Local = true;
                        m_assetService.Store(meshAsset);
                        meshAssets.Add(meshAsset.FullID);
                        meshAvatarSkeletons.Add(curAvSkeleton);
                        meshAvatarColliders.Add(curAvCollider);

                        // test code 
                        if (curAvSkeleton && client != null)
                        {
                            string name = assetName;
                            if (name.Length > 25)
                                name = name.Substring(0, 24);
                            name += "_Mesh#" + i.ToString();
                            InventoryItemBase meshitem = new InventoryItemBase();
                            meshitem.Owner = m_HostCapsObj.AgentID;
                            meshitem.CreatorId = creatorIDstr;
                            meshitem.CreatorData = String.Empty;
                            meshitem.ID = UUID.Random();
                            meshitem.AssetID = meshAsset.FullID;
                            meshitem.Description = "mesh ";
                            meshitem.Name = name;
                            meshitem.AssetType = (int)AssetType.Mesh;
                            meshitem.InvType = (int)InventoryType.Mesh;
                            //                            meshitem.Folder = UUID.Zero; // send to default

                            meshitem.Folder = parentFolder; // dont let it go to folder Meshes that viewers dont show

                            // If we set PermissionMask.All then when we rez the item the next permissions will replace the current
                            // (owner) permissions.  This becomes a problem if next permissions are changed.
                            meshitem.CurrentPermissions
                                = (uint)(PermissionMask.Move | PermissionMask.Copy | PermissionMask.Modify | PermissionMask.Transfer);

                            meshitem.BasePermissions = (uint)PermissionMask.All;
                            meshitem.EveryOnePermissions = 0;
                            meshitem.NextPermissions = (uint)PermissionMask.All;
                            meshitem.CreationDate = Util.UnixTimeSinceEpoch();

                            m_Scene.AddInventoryItem(client, meshitem);
                            meshitem = null;
                        }
                    }

                    int skipedMeshs = 0;
                    // build prims from instances
                    for (int i = 0; i < instance_list.Count; i++)
                    {
                        OSDMap inner_instance_list = (OSDMap)instance_list[i];

                        // skip prims that are 2 small
                        Vector3 scale = inner_instance_list["scale"].AsVector3();

                        if (scale.X < m_PrimScaleMin || scale.Y < m_PrimScaleMin || scale.Z < m_PrimScaleMin)
                        {
                            skipedMeshs++;
                            continue;
                        }

                        PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox();

                        Primitive.TextureEntry textureEntry
                            = new Primitive.TextureEntry(Primitive.TextureEntry.WHITE_TEXTURE);


                        OSDArray face_list = (OSDArray)inner_instance_list["face_list"];
                        for (uint face = 0; face < face_list.Count; face++)
                        {
                            OSDMap faceMap = (OSDMap)face_list[(int)face];
                            Primitive.TextureEntryFace f = pbs.Textures.CreateFace(face);
                            if (faceMap.ContainsKey("fullbright"))
                                f.Fullbright = faceMap["fullbright"].AsBoolean();
                            if (faceMap.ContainsKey("diffuse_color"))
                                f.RGBA = faceMap["diffuse_color"].AsColor4();

                            int textureNum = faceMap["image"].AsInteger();
                            float imagerot = faceMap["imagerot"].AsInteger();
                            float offsets = (float)faceMap["offsets"].AsReal();
                            float offsett = (float)faceMap["offsett"].AsReal();
                            float scales = (float)faceMap["scales"].AsReal();
                            float scalet = (float)faceMap["scalet"].AsReal();

                            if (imagerot != 0)
                                f.Rotation = imagerot;

                            if (offsets != 0)
                                f.OffsetU = offsets;

                            if (offsett != 0)
                                f.OffsetV = offsett;

                            if (scales != 0)
                                f.RepeatU = scales;

                            if (scalet != 0)
                                f.RepeatV = scalet;

                            if (textures.Count > textureNum)
                                f.TextureID = textures[textureNum];
                            else
                                f.TextureID = Primitive.TextureEntry.WHITE_TEXTURE;

                            textureEntry.FaceTextures[face] = f;
                        }

                        pbs.TextureEntry = textureEntry.GetBytes();

                        bool hasmesh = false;
                        if (inner_instance_list.ContainsKey("mesh")) // seems to happen always but ...
                        {
                            int meshindx = inner_instance_list["mesh"].AsInteger();
                            if (meshAssets.Count > meshindx)
                            {
                                pbs.SculptEntry = true;
                                pbs.SculptType = (byte)SculptType.Mesh;
                                pbs.SculptTexture = meshAssets[meshindx]; // actual asset UUID after meshs suport introduction
                                // data will be requested from asset on rez (i hope)
                                hasmesh = true;
                            }
                        }

                        Vector3 position = inner_instance_list["position"].AsVector3();
                        Quaternion rotation = inner_instance_list["rotation"].AsQuaternion();

                        // for now viwers do send fixed defaults
                        // but this may change
//                        int physicsShapeType = inner_instance_list["physics_shape_type"].AsInteger();
                        byte physicsShapeType = (byte)PhysShapeType.convex; // default is simple convex
//                        int material = inner_instance_list["material"].AsInteger();
                        byte material = (byte)Material.Wood;

// no longer used - begin ------------------------
//                    int mesh = inner_instance_list["mesh"].AsInteger();

//                    OSDMap permissions = (OSDMap)inner_instance_list["permissions"];
//                    int base_mask = permissions["base_mask"].AsInteger();
//                    int everyone_mask = permissions["everyone_mask"].AsInteger();
//                    UUID creator_id = permissions["creator_id"].AsUUID();
//                    UUID group_id = permissions["group_id"].AsUUID();
//                    int group_mask = permissions["group_mask"].AsInteger();
//                    bool is_owner_group = permissions["is_owner_group"].AsBoolean();
//                    UUID last_owner_id = permissions["last_owner_id"].AsUUID();
//                    int next_owner_mask = permissions["next_owner_mask"].AsInteger();
//                    UUID owner_id = permissions["owner_id"].AsUUID();
//                    int owner_mask = permissions["owner_mask"].AsInteger();
// no longer used - end ------------------------
                       

                        SceneObjectPart prim
                            = new SceneObjectPart(owner_id, pbs, position, Quaternion.Identity, Vector3.Zero);

                        prim.Scale = scale;
                        rotations.Add(rotation);
                        positions.Add(position);
                        prim.UUID = UUID.Random();
                        prim.CreatorID = creatorID;
                        prim.OwnerID = owner_id;
                        prim.GroupID = UUID.Zero;
                        prim.LastOwnerID = creatorID;
                        prim.CreationDate = Util.UnixTimeSinceEpoch();
                        
                        if (grp == null)
                            prim.Name = assetName;
                        else
                            prim.Name = assetName + "#" + i.ToString();

                        prim.EveryoneMask = 0;
                        prim.GroupMask = 0;

                        if (restrictPerms)
                        {
                            prim.BaseMask = (uint)(PermissionMask.Move | PermissionMask.Modify);
                            prim.OwnerMask = (uint)(PermissionMask.Move | PermissionMask.Modify);
                            prim.NextOwnerMask = 0;
                        }
                        else
                        {
                            prim.BaseMask = (uint)PermissionMask.All | (uint)PermissionMask.Export;
                            prim.OwnerMask = (uint)PermissionMask.All | (uint)PermissionMask.Export;
                            prim.GroupMask = prim.BaseMask & (uint)groupMask;
                            prim.EveryoneMask = prim.BaseMask & (uint)everyoneMask;
                            prim.NextOwnerMask = prim.BaseMask & (uint)nextOwnerMask;
                            // If the viewer gives us bogus permissions, revert to the SL
                            // default of transfer only.
                            if ((prim.NextOwnerMask & (uint)PermissionMask.All) == 0)
                                prim.NextOwnerMask = (uint)PermissionMask.Transfer;
                        }

                        if(istest)
                            prim.Description = "For testing only. Other uses are prohibited";
                        else
                            prim.Description = "";

                        prim.Material = material;
                        prim.PhysicsShapeType = physicsShapeType;

//                    prim.BaseMask = (uint)base_mask;
//                    prim.EveryoneMask = (uint)everyone_mask;
//                    prim.GroupMask = (uint)group_mask;
//                    prim.NextOwnerMask = (uint)next_owner_mask;
//                    prim.OwnerMask = (uint)owner_mask;

                        if (grp == null)
                        {
                            grp = new SceneObjectGroup(prim);
                            grp.LastOwnerID = creatorID;
                        }
                        else
                            grp.AddPart(prim);
                    }

                    Vector3 rootPos = positions[0];

                    if (grp.Parts.Length > 1)
                    {
                        // Fix first link number
                        grp.RootPart.LinkNum++;

                        Quaternion rootRotConj = Quaternion.Conjugate(rotations[0]);
                        Quaternion tmprot;
                        Vector3 offset;

                        // fix children rotations and positions
                        for (int i = 1; i < rotations.Count; i++)
                        {
                            tmprot = rotations[i];
                            tmprot = rootRotConj * tmprot;

                            grp.Parts[i].RotationOffset = tmprot;

                            offset = positions[i] - rootPos;

                            offset *= rootRotConj;
                            grp.Parts[i].OffsetPosition = offset;
                        }

                        grp.AbsolutePosition = rootPos;
                        grp.UpdateGroupRotationR(rotations[0]);
                    }
                    else
                    {
                        grp.AbsolutePosition = rootPos;
                        grp.UpdateGroupRotationR(rotations[0]);
                    }

                    data = ASCIIEncoding.ASCII.GetBytes(SceneObjectSerializer.ToOriginalXmlFormat(grp));
                }

                else // not a mesh model
                {
                    m_log.ErrorFormat("[CAPS Asset Upload] got unsuported assetType for object upload");
                    return;
                }
            }

            AssetBase asset;
            asset = new AssetBase(assetID, assetName, assType, creatorIDstr);
            asset.Data = data;
            if (istest)
                asset.Local = true;
            if (AddNewAsset != null)
                AddNewAsset(asset);
            else if (m_assetService != null)
                m_assetService.Store(asset);

            InventoryItemBase item = new InventoryItemBase();
            item.Owner = m_HostCapsObj.AgentID;
            item.CreatorId = creatorIDstr;
            item.CreatorData = String.Empty;
            item.ID = inventoryItem;
            item.AssetID = asset.FullID;
            if (istest)
            {
                item.Description = "For testing only. Other uses are prohibited";
                item.Flags = (uint) (InventoryItemFlags.SharedSingleReference);
            }
            else
                item.Description = assetDescription;
            item.Name = assetName;
            item.AssetType = assType;
            item.InvType = inType;
            item.Folder = parentFolder;

            // If we set PermissionMask.All then when we rez the item the next permissions will replace the current
            // (owner) permissions.  This becomes a problem if next permissions are changed.

            if (inType == (sbyte)CustomInventoryType.AnimationSet)
            {
                AnimationSet.setCreateItemPermitions(item);
            }

            else if (restrictPerms)
            {
                item.BasePermissions = (uint)(PermissionMask.Move | PermissionMask.Modify);
                item.CurrentPermissions = (uint)(PermissionMask.Move | PermissionMask.Modify);
                item.GroupPermissions = 0;
                item.EveryOnePermissions = 0;
                item.NextPermissions = 0;
            }
            else
            {
                item.BasePermissions = (uint)PermissionMask.All | (uint)PermissionMask.Export;
                item.CurrentPermissions = (uint)PermissionMask.All | (uint)PermissionMask.Export;
                item.GroupPermissions = item.BasePermissions & (uint)groupMask;
                item.EveryOnePermissions = item.BasePermissions & (uint)everyoneMask;
                item.NextPermissions = item.BasePermissions & (uint)nextOwnerMask;
                if ((item.NextPermissions & (uint)PermissionMask.All) == 0)
                    item.NextPermissions = (uint)PermissionMask.Transfer;
            }

            item.CreationDate = Util.UnixTimeSinceEpoch();

            everyoneMask = (int)item.EveryOnePermissions;
            groupMask = (int)item.GroupPermissions;
            nextOwnerMask = (int)item.NextPermissions;

            m_Scene.TryGetClient(m_HostCapsObj.AgentID, out client);

            if (AddNewInventoryItem != null)
            {
                if (istest)
                {
                    m_Scene.AddInventoryItem(client, item);
/*
                    AddNewInventoryItem(m_HostCapsObj.AgentID, item, 0);
                    if (client != null)
                        client.SendAgentAlertMessage("Upload will have no cost, for personal test purposes only. Other uses are forbiden. Items may not work on a another region" , true);
 */
                }
                else
                {
                    AddNewInventoryItem(m_HostCapsObj.AgentID, item, (uint)cost);
//                    if (client != null)
//                    {
//                        // let users see anything..  i don't so far
//                        string str;
//                        if (cost > 0)
//                            // dont remember where is money unit name to put here
//                            str = "Upload complete. charged " + cost.ToString() + "$";
//                        else
//                            str = "Upload complete";
//                        client.SendAgentAlertMessage(str, true);
//                    }
                }
            }

            lock (m_ModelCost)
                m_FileAgentInventoryState = FileAgentInventoryState.idle;
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Update the texture entry for this part.
        /// </summary>
        /// <param name="newTex"></param>
        public void UpdateTextureEntry(Primitive.TextureEntry newTex)
        {
            Primitive.TextureEntry oldTex = Shape.Textures;

            Changed changeFlags = 0;

            Primitive.TextureEntryFace fallbackNewFace = newTex.DefaultTexture;
            Primitive.TextureEntryFace fallbackOldFace = oldTex.DefaultTexture;
           
            // On Incoming packets, sometimes newText.DefaultTexture is null.  The assumption is that all 
            // other prim-sides are set, but apparently that's not always the case.  Lets assume packet/data corruption at this point.
            if (fallbackNewFace == null)
            {
                fallbackNewFace = new Primitive.TextureEntry(Util.BLANK_TEXTURE_UUID).CreateFace(0);
                newTex.DefaultTexture = fallbackNewFace;
            }
            if (fallbackOldFace == null)
            {
                fallbackOldFace = new Primitive.TextureEntry(Util.BLANK_TEXTURE_UUID).CreateFace(0);
                oldTex.DefaultTexture = fallbackOldFace;
            }

            // Materials capable viewers can send a ObjectImage packet
            // when nothing in TE has changed. MaterialID should be updated
            // by the RenderMaterials CAP handler, so updating it here may cause a
            // race condtion. Therefore, if no non-materials TE fields have changed, 
            // we should ignore any changes and not update Shape.TextureEntry

            bool otherFieldsChanged = false;

            for (int i = 0 ; i < GetNumberOfSides(); i++)
            {

                Primitive.TextureEntryFace newFace = newTex.DefaultTexture;
                Primitive.TextureEntryFace oldFace = oldTex.DefaultTexture;

                if (oldTex.FaceTextures[i] != null)
                    oldFace = oldTex.FaceTextures[i];
                if (newTex.FaceTextures[i] != null)
                    newFace = newTex.FaceTextures[i];

                Color4 oldRGBA = oldFace.RGBA;
                Color4 newRGBA = newFace.RGBA;

                if (oldRGBA.R != newRGBA.R ||
                    oldRGBA.G != newRGBA.G ||
                    oldRGBA.B != newRGBA.B ||
                    oldRGBA.A != newRGBA.A)
                    changeFlags |= Changed.COLOR;

                if (oldFace.TextureID != newFace.TextureID)
                    changeFlags |= Changed.TEXTURE;

                // Max change, skip the rest of testing
                if (changeFlags == (Changed.TEXTURE | Changed.COLOR))
                    break;

                if (!otherFieldsChanged)
                {
                    if (oldFace.Bump != newFace.Bump) otherFieldsChanged = true;
                    if (oldFace.Fullbright != newFace.Fullbright) otherFieldsChanged = true;
                    if (oldFace.Glow != newFace.Glow) otherFieldsChanged = true;
                    if (oldFace.MediaFlags != newFace.MediaFlags) otherFieldsChanged = true;
                    if (oldFace.OffsetU != newFace.OffsetU) otherFieldsChanged = true;
                    if (oldFace.OffsetV != newFace.OffsetV) otherFieldsChanged = true;
                    if (oldFace.RepeatU != newFace.RepeatU) otherFieldsChanged = true;
                    if (oldFace.RepeatV != newFace.RepeatV) otherFieldsChanged = true;
                    if (oldFace.Rotation != newFace.Rotation) otherFieldsChanged = true;
                    if (oldFace.Shiny != newFace.Shiny) otherFieldsChanged = true;
                    if (oldFace.TexMapType != newFace.TexMapType) otherFieldsChanged = true;
                }
            }

            if (changeFlags != 0 || otherFieldsChanged)
            {
                m_shape.TextureEntry = newTex.GetBytes();
                if (changeFlags != 0)
                    TriggerScriptChangedEvent(changeFlags);
                UpdateFlag = UpdateRequired.FULL;
                ParentGroup.HasGroupChanged = true;

                //This is madness..
                //ParentGroup.ScheduleGroupForFullUpdate();
                //This is sparta
                ScheduleFullUpdate();
            }
        }
Ejemplo n.º 17
0
        public AvatarAppearance(AvatarWearable[] wearables, Primitive.TextureEntry textureEntry, byte[] visualParams)
        {
//            m_log.WarnFormat("[AVATAR APPEARANCE] create initialized appearance");

            m_serial = 0;

            if (wearables != null)
                m_wearables = wearables;
            else
                SetDefaultWearables();

            if (textureEntry != null)
                m_texture = textureEntry;
            else
                SetDefaultTexture();

            if (visualParams != null)
                m_visualparams = visualParams;
            else
                SetDefaultParams();

//            SetHeight();
            if(m_avatarHeight == 0)
                SetSize(new Vector3(0.45f,0.6f,1.9f));

            m_attachments = new Dictionary<int, List<AvatarAttachment>>();
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Find the materials used in the SOP, and add them to 'm_regionMaterials'.
        /// </summary>
        private void GetStoredMaterialsInPart(SceneObjectPart part)
        { 
            if (part.Shape == null)
                return;

            var te = new Primitive.TextureEntry(part.Shape.TextureEntry, 0, part.Shape.TextureEntry.Length);
            if (te == null)
                return;

            GetLegacyStoredMaterialsInPart(part);

            if (te.DefaultTexture != null)
                GetStoredMaterialInFace(part, te.DefaultTexture);
            else
                m_log.WarnFormat(
                    "[Materials]: Default texture for part {0} (part of object {1)) in {2} unexpectedly null.  Ignoring.", 
                    part.Name, part.ParentGroup.Name, m_scene.Name);

            foreach (Primitive.TextureEntryFace face in te.FaceTextures)
            {
                if (face != null)
                    GetStoredMaterialInFace(part, face);
            }
        }
Ejemplo n.º 19
0
        protected virtual void SetDefaultTexture()
        {
            m_texture = new Primitive.TextureEntry(new UUID(AppearanceManager.DEFAULT_AVATAR_TEXTURE));

            // for (uint i = 0; i < TEXTURE_COUNT; i++)
            //     m_texture.CreateFace(i).TextureID = new UUID(AppearanceManager.DEFAULT_AVATAR_TEXTURE);
        }
Ejemplo n.º 20
0
        public string RenderMaterialsPostCap(string request, UUID agentID)
        {
            OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request);
            OSDMap resp = new OSDMap();

            OSDMap materialsFromViewer = null;

            OSDArray respArr = new OSDArray();

            if (req.ContainsKey("Zipped"))
            {
                OSD osd = null;

                byte[] inBytes = req["Zipped"].AsBinary();

                try 
                {
                    osd = ZDecompressBytesToOsd(inBytes);

                    if (osd != null)
                    {
                        if (osd is OSDArray) // assume array of MaterialIDs designating requested material entries
                        {
                            foreach (OSD elem in (OSDArray)osd)
                            {
                                try
                                {
                                    UUID id = new UUID(elem.AsBinary(), 0);

                                    lock (m_regionMaterials)
                                    {
                                        if (m_regionMaterials.ContainsKey(id))
                                        {
                                            OSDMap matMap = new OSDMap();
                                            matMap["ID"] = OSD.FromBinary(id.GetBytes());
                                            matMap["Material"] = m_regionMaterials[id];
                                            respArr.Add(matMap);
                                        }
                                        else
                                        {
                                            m_log.Warn("[Materials]: request for unknown material ID: " + id.ToString());

                                            // Theoretically we could try to load the material from the assets service,
                                            // but that shouldn't be necessary because the viewer should only request
                                            // materials that exist in a prim on the region, and all of these materials
                                            // are already stored in m_regionMaterials.
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    m_log.Error("Error getting materials in response to viewer request", e);
                                    continue;
                                }
                            }
                        }
                        else if (osd is OSDMap) // request to assign a material
                        {
                            materialsFromViewer = osd as OSDMap;

                            if (materialsFromViewer.ContainsKey("FullMaterialsPerFace"))
                            {
                                OSD matsOsd = materialsFromViewer["FullMaterialsPerFace"];
                                if (matsOsd is OSDArray)
                                {
                                    OSDArray matsArr = matsOsd as OSDArray;

                                    try
                                    {
                                        foreach (OSDMap matsMap in matsArr)
                                        {
                                            uint primLocalID = 0;
                                            try {
                                                primLocalID = matsMap["ID"].AsUInteger();
                                            }
                                            catch (Exception e) {
                                                m_log.Warn("[Materials]: cannot decode \"ID\" from matsMap: " + e.Message);
                                                continue;
                                            }

                                            OSDMap mat = null;
                                            try
                                            {
                                                mat = matsMap["Material"] as OSDMap;
                                            }
                                            catch (Exception e)
                                            {
                                                m_log.Warn("[Materials]: cannot decode \"Material\" from matsMap: " + e.Message);
                                                continue;
                                            }

                                            SceneObjectPart sop = m_scene.GetSceneObjectPart(primLocalID);
                                            if (sop == null)
                                            {
                                                m_log.WarnFormat("[Materials]: SOP not found for localId: {0}", primLocalID.ToString());
                                                continue;
                                            }

                                            if (!m_scene.Permissions.CanEditObject(sop.UUID, agentID))
                                            {
                                                m_log.WarnFormat("User {0} can't edit object {1} {2}", agentID, sop.Name, sop.UUID);
                                                continue;
                                            }

                                            Primitive.TextureEntry te = new Primitive.TextureEntry(sop.Shape.TextureEntry, 0, sop.Shape.TextureEntry.Length);
                                            if (te == null)
                                            {
                                                m_log.WarnFormat("[Materials]: Error in TextureEntry for SOP {0} {1}", sop.Name, sop.UUID);
                                                continue;
                                            }


                                            UUID id;
                                            if (mat == null)
                                            {
                                                // This happens then the user removes a material from a prim
                                                id = UUID.Zero;
                                            }
                                            else
                                            {
                                                id = StoreMaterialAsAsset(agentID, mat, sop);
                                            }


                                            int face = -1;

                                            if (matsMap.ContainsKey("Face"))
                                            {
                                                face = matsMap["Face"].AsInteger();
                                                Primitive.TextureEntryFace faceEntry = te.CreateFace((uint)face);
                                                faceEntry.MaterialID = id;
                                            }
                                            else
                                            {
                                                if (te.DefaultTexture == null)
                                                    m_log.WarnFormat("[Materials]: TextureEntry.DefaultTexture is null in {0} {1}", sop.Name, sop.UUID);
                                                else
                                                    te.DefaultTexture.MaterialID = id;
                                            }

                                            //m_log.DebugFormat("[Materials]: in \"{0}\" {1}, setting material ID for face {2} to {3}", sop.Name, sop.UUID, face, id);

                                            // We can't use sop.UpdateTextureEntry(te) because it filters, so do it manually
                                            sop.Shape.TextureEntry = te.GetBytes();

                                            if (sop.ParentGroup != null)
                                            {
                                                sop.TriggerScriptChangedEvent(Changed.TEXTURE);
                                                sop.UpdateFlag = UpdateRequired.FULL;
                                                sop.ParentGroup.HasGroupChanged = true;
                                                sop.ScheduleFullUpdate();
                                            }
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        m_log.Warn("[Materials]: exception processing received material ", e);
                                    }
                                }
                            }
                        }
                    }

                }
                catch (Exception e)
                {
                    m_log.Warn("[Materials]: exception decoding zipped CAP payload ", e);
                    //return "";
                }
            }

            
            resp["Zipped"] = ZCompressOSD(respArr, false);
            string response = OSDParser.SerializeLLSDXmlString(resp);

            //m_log.Debug("[Materials]: cap request: " + request);
            //m_log.Debug("[Materials]: cap request (zipped portion): " + ZippedOsdBytesToString(req["Zipped"].AsBinary()));
            //m_log.Debug("[Materials]: cap response: " + response);
            return response;
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Deserialization of agent data.
        /// Avoiding reflection makes it painful to write, but that's the price!
        /// </summary>
        /// <param name="hash"></param>
        public virtual void Unpack(OSDMap args)
        {
            // DEBUG ON
            m_log.WarnFormat("[CHILDAGENTDATAUPDATE] Unpack data");
            // DEBUG OFF

            if (args.ContainsKey("region_id"))
                UUID.TryParse(args["region_id"].AsString(), out RegionID);

            if (args["circuit_code"] != null)
                UInt32.TryParse((string)args["circuit_code"].AsString(), out CircuitCode);

            if (args["agent_uuid"] != null)
                AgentID = args["agent_uuid"].AsUUID();

            if (args["session_uuid"] != null)
                SessionID = args["session_uuid"].AsUUID();

            if (args["position"] != null)
                Vector3.TryParse(args["position"].AsString(), out Position);

            if (args["velocity"] != null)
                Vector3.TryParse(args["velocity"].AsString(), out Velocity);

            if (args["center"] != null)
                Vector3.TryParse(args["center"].AsString(), out Center);

            if (args["size"] != null)
                Vector3.TryParse(args["size"].AsString(), out Size);

            if (args["at_axis"] != null)
                Vector3.TryParse(args["at_axis"].AsString(), out AtAxis);

            if (args["left_axis"] != null)
                Vector3.TryParse(args["left_axis"].AsString(), out AtAxis);

            if (args["up_axis"] != null)
                Vector3.TryParse(args["up_axis"].AsString(), out AtAxis);

            if (args["changed_grid"] != null)
                ChangedGrid = args["changed_grid"].AsBoolean();

            if (args["far"] != null)
                Far = (float)(args["far"].AsReal());

            if (args["aspect"] != null)
                Aspect = (float)args["aspect"].AsReal();

            if (args["throttles"] != null)
                Throttles = args["throttles"].AsBinary();

            if (args["locomotion_state"] != null)
                UInt32.TryParse(args["locomotion_state"].AsString(), out LocomotionState);

            if (args["head_rotation"] != null)
                Quaternion.TryParse(args["head_rotation"].AsString(), out HeadRotation);

            if (args["body_rotation"] != null)
                Quaternion.TryParse(args["body_rotation"].AsString(), out BodyRotation);

            if (args["control_flags"] != null)
                UInt32.TryParse(args["control_flags"].AsString(), out ControlFlags);

            if (args["energy_level"] != null)
                EnergyLevel = (float)(args["energy_level"].AsReal());

            //This IS checked later
            if (args["god_level"] != null)
                Byte.TryParse(args["god_level"].AsString(), out GodLevel);

            if (args["speed"] != null)
                float.TryParse(args["speed"].AsString(), out Speed);
            else
                Speed = 1;

            if (args["draw_distance"] != null)
                float.TryParse(args["draw_distance"].AsString(), out DrawDistance);
            else
                DrawDistance = 0;

            //Reset this to fix movement... since regions are being bad about this
            if (Speed == 0)
                Speed = 1;

            if (args["always_run"] != null)
                AlwaysRun = args["always_run"].AsBoolean();

            if (args["sent_initial_wearables"] != null)
                SentInitialWearables = args["sent_initial_wearables"].AsBoolean();
            else
                SentInitialWearables = false;

            if (args["prey_agent"] != null)
                PreyAgent = args["prey_agent"].AsUUID();

            if (args["agent_access"] != null)
                Byte.TryParse(args["agent_access"].AsString(), out AgentAccess);

            if (args["active_group_id"] != null)
                ActiveGroupID = args["active_group_id"].AsUUID();

            if ((args["groups"] != null) && (args["groups"]).Type == OSDType.Array)
            {
                OSDArray groups = (OSDArray)(args["groups"]);
                Groups = new AgentGroupData[groups.Count];
                int i = 0;
                foreach (OSD o in groups)
                {
                    if (o.Type == OSDType.Map)
                    {
                        Groups[i++] = new AgentGroupData((OSDMap)o);
                    }
                }
            }

            if ((args["animations"] != null) && (args["animations"]).Type == OSDType.Array)
            {
                OSDArray anims = (OSDArray)(args["animations"]);
                Anims = new Animation[anims.Count];
                int i = 0;
                foreach (OSD o in anims)
                {
                    if (o.Type == OSDType.Map)
                    {
                        Anims[i++] = new Animation((OSDMap)o);
                    }
                }
            }

            //if ((args["agent_textures"] != null) && (args["agent_textures"]).Type == OSDType.Array)
            //{
            //    OSDArray textures = (OSDArray)(args["agent_textures"]);
            //    AgentTextures = new UUID[textures.Count];
            //    int i = 0;
            //    foreach (OSD o in textures)
            //        AgentTextures[i++] = o.AsUUID();
            //}

            Appearance = new AvatarAppearance(AgentID);

            // The code to unpack textures, visuals, wearables and attachments
            // should be removed; packed appearance contains the full appearance
            // This is retained for backward compatibility only
            if (args["texture_entry"] != null)
            {
                byte[] rawtextures = args["texture_entry"].AsBinary();
                Primitive.TextureEntry textures = new Primitive.TextureEntry(rawtextures, 0, rawtextures.Length);
                List<UUID> changed = new List<UUID>();
                Appearance.SetTextureEntries(textures, out changed);
            }

            if (args["visual_params"] != null)
                Appearance.SetVisualParams(args["visual_params"].AsBinary());

            if ((args["wearables"] != null) && (args["wearables"]).Type == OSDType.Array)
            {
                OSDArray wears = (OSDArray)(args["wearables"]);
                for (int i = 0; i < wears.Count / 2; i++)
                {
                    AvatarWearable awear = new AvatarWearable((OSDArray)wears[i]);
                    Appearance.SetWearable(i, awear);
                }
            }

            if ((args["attachments"] != null) && (args["attachments"]).Type == OSDType.Array)
            {
                OSDArray attachs = (OSDArray)(args["attachments"]);
                foreach (OSD o in attachs)
                {
                    if (o.Type == OSDType.Map)
                    {
                        // We know all of these must end up as attachments so we
                        // append rather than replace to ensure multiple attachments
                        // per point continues to work
                        Appearance.AppendAttachment(new AvatarAttachment((OSDMap)o));
                    }
                }
            }
            // end of code to remove

            if (args.ContainsKey("packed_appearance") && (args["packed_appearance"]).Type == OSDType.Map)
                Appearance = new AvatarAppearance(AgentID, (OSDMap)args["packed_appearance"]);
            // DEBUG ON
            else
                m_log.WarnFormat("[CHILDAGENTDATAUPDATE] No packed appearance");
            // DEBUG OFF

            if ((args["controllers"] != null) && (args["controllers"]).Type == OSDType.Array)
            {
                OSDArray controls = (OSDArray)(args["controllers"]);
                Controllers = new ControllerData[controls.Count];
                int i = 0;
                foreach (OSD o in controls)
                {
                    if (o.Type == OSDType.Map)
                    {
                        Controllers[i++] = new ControllerData((OSDMap)o);
                    }
                }
            }

            if (args["callback_uri"] != null)
                CallbackURI = args["callback_uri"].AsString();
        }
Ejemplo n.º 22
0
        public PrimitiveBaseShape(bool noShape)
        {
            if (noShape)
                return;

            PCode = (byte)PCodeEnum.Primitive;
            ExtraParams = new byte[1];
            Textures = new Primitive.TextureEntry(DEFAULT_TEXTURE_ID);
            RenderMaterials = new RenderMaterials();
        }
Ejemplo n.º 23
0
        ///<summary>
        ///</summary>
        ///<param name = "assetID"></param>
        ///<param name = "inventoryItem"></param>
        ///<param name = "data"></param>
        public UUID UploadCompleteHandler(string assetName, string assetDescription, UUID assetID,
                                          UUID inventoryItem, UUID parentFolder, byte[] data, string inventoryType,
                                          string assetType, uint everyone_mask, uint group_mask, uint next_owner_mask)
        {
            sbyte assType = 0;
            sbyte inType = 0;

            if (inventoryType == "sound")
            {
                inType = 1;
                assType = 1;
            }
            else if (inventoryType == "animation")
            {
                inType = 19;
                assType = 20;
            }
            else if (inventoryType == "snapshot")
            {
                inType = 15;
                assType = 0;
            }
            else if (inventoryType == "wearable")
            {
                inType = 18;
                switch (assetType)
                {
                    case "bodypart":
                        assType = 13;
                        break;
                    case "clothing":
                        assType = 5;
                        break;
                }
            }
            else if (inventoryType == "object")
            {
                inType = (sbyte) InventoryType.Object;
                assType = (sbyte) AssetType.Object;

                List<Vector3> positions = new List<Vector3>();
                List<Quaternion> rotations = new List<Quaternion>();
                OSDMap request = (OSDMap) OSDParser.DeserializeLLSDXml(data);
                OSDArray instance_list = (OSDArray) request["instance_list"];
                OSDArray mesh_list = (OSDArray) request["mesh_list"];
                OSDArray texture_list = (OSDArray) request["texture_list"];
                SceneObjectGroup grp = null;

                List<UUID> textures = new List<UUID>();
#if(!ISWIN)
                for (int i = 0; i < texture_list.Count; i++)
                {
                    AssetBase textureAsset = new AssetBase(UUID.Random(), assetName, AssetType.Texture, m_service.AgentID);
                    textureAsset.Data = texture_list[i].AsBinary();
                    textureAsset.ID = m_assetService.Store(textureAsset);
                    textures.Add(textureAsset.ID);
                }
#else
                foreach (AssetBase textureAsset in texture_list.Select(t => new AssetBase(UUID.Random(), assetName, AssetType.Texture,
                                                                                          m_service.AgentID) {Data = t.AsBinary()}))
                {
                    textureAsset.ID = m_assetService.Store(textureAsset);
                    textures.Add(textureAsset.ID);
                }
#endif
                InventoryFolderBase meshFolder = m_inventoryService.GetFolderForType(m_service.AgentID,
                                                                                     InventoryType.Mesh, AssetType.Mesh);
                for (int i = 0; i < mesh_list.Count; i++)
                {
                    PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox();

                    Primitive.TextureEntry textureEntry =
                        new Primitive.TextureEntry(Primitive.TextureEntry.WHITE_TEXTURE);
                    OSDMap inner_instance_list = (OSDMap) instance_list[i];

                    OSDArray face_list = (OSDArray) inner_instance_list["face_list"];
                    for (uint face = 0; face < face_list.Count; face++)
                    {
                        OSDMap faceMap = (OSDMap) face_list[(int) face];
                        Primitive.TextureEntryFace f = pbs.Textures.CreateFace(face);
                        if (faceMap.ContainsKey("fullbright"))
                            f.Fullbright = faceMap["fullbright"].AsBoolean();
                        if (faceMap.ContainsKey("diffuse_color"))
                            f.RGBA = faceMap["diffuse_color"].AsColor4();

                        int textureNum = faceMap["image"].AsInteger();
                        float imagerot = faceMap["imagerot"].AsInteger();
                        float offsets = (float) faceMap["offsets"].AsReal();
                        float offsett = (float) faceMap["offsett"].AsReal();
                        float scales = (float) faceMap["scales"].AsReal();
                        float scalet = (float) faceMap["scalet"].AsReal();

                        if (imagerot != 0)
                            f.Rotation = imagerot;
                        if (offsets != 0)
                            f.OffsetU = offsets;
                        if (offsett != 0)
                            f.OffsetV = offsett;
                        if (scales != 0)
                            f.RepeatU = scales;
                        if (scalet != 0)
                            f.RepeatV = scalet;
                        f.TextureID = textures.Count > textureNum ? textures[textureNum] : Primitive.TextureEntry.WHITE_TEXTURE;
                        textureEntry.FaceTextures[face] = f;
                    }
                    pbs.TextureEntry = textureEntry.GetBytes();

                    AssetBase meshAsset = new AssetBase(UUID.Random(), assetName, AssetType.Mesh, m_service.AgentID)
                                              {Data = mesh_list[i].AsBinary()};
                    meshAsset.ID = m_assetService.Store(meshAsset);

                    if (meshFolder == null)
                    {
                        m_inventoryService.CreateUserInventory(m_service.AgentID, false);
                        meshFolder = m_inventoryService.GetFolderForType(m_service.AgentID, InventoryType.Mesh,
                                                                         AssetType.Mesh);
                    }

                    InventoryItemBase itemBase = new InventoryItemBase(UUID.Random(), m_service.AgentID)
                                                     {
                                                         AssetType = (sbyte) AssetType.Mesh,
                                                         AssetID = meshAsset.ID,
                                                         CreatorId = m_service.AgentID.ToString(),
                                                         Folder = meshFolder.ID,
                                                         InvType = (int) InventoryType.Texture,
                                                         Name = "(Mesh) - " + assetName,
                                                         CurrentPermissions = (uint) PermissionMask.All,
                                                         BasePermissions = (uint) PermissionMask.All,
                                                         EveryOnePermissions = everyone_mask,
                                                         GroupPermissions = group_mask,
                                                         NextPermissions = next_owner_mask
                                                     };
                    //Bad... but whatever
                    m_inventoryService.AddItem(itemBase);

                    pbs.SculptEntry = true;
                    pbs.SculptTexture = meshAsset.ID;
                    pbs.SculptType = (byte) SculptType.Mesh;
                    pbs.SculptData = meshAsset.Data;

                    Vector3 position = inner_instance_list["position"].AsVector3();
                    Vector3 scale = inner_instance_list["scale"].AsVector3();
                    Quaternion rotation = inner_instance_list["rotation"].AsQuaternion();

                    int physicsShapeType = inner_instance_list["physics_shape_type"].AsInteger();
                    int material = inner_instance_list["material"].AsInteger();
                    int mesh = inner_instance_list["mesh"].AsInteger();

                    UUID owner_id = m_service.AgentID;

                    IScene fakeScene = new Scene();
                    fakeScene.AddModuleInterfaces(m_service.Registry.GetInterfaces());

                    SceneObjectPart prim = new SceneObjectPart(owner_id, pbs, position, Quaternion.Identity,
                                                               Vector3.Zero, assetName, fakeScene)
                                               {Scale = scale, AbsolutePosition = position};

                    rotations.Add(rotation);
                    positions.Add(position);
                    prim.UUID = UUID.Random();
                    prim.CreatorID = owner_id;
                    prim.OwnerID = owner_id;
                    prim.GroupID = UUID.Zero;
                    prim.LastOwnerID = prim.OwnerID;
                    prim.CreationDate = Util.UnixTimeSinceEpoch();
                    prim.Name = assetName;
                    prim.Description = "";
                    prim.PhysicsType = (byte) physicsShapeType;

                    prim.BaseMask = (uint) PermissionMask.All;
                    prim.EveryoneMask = everyone_mask;
                    prim.NextOwnerMask = next_owner_mask;
                    prim.GroupMask = group_mask;
                    prim.OwnerMask = (uint) PermissionMask.All;

                    if (grp == null)
                        grp = new SceneObjectGroup(prim, fakeScene);
                    else
                        grp.AddChild(prim, i + 1);
                    grp.RootPart.IsAttachment = false;
                }
                if (grp.ChildrenList.Count > 1) //Fix first link #
                    grp.RootPart.LinkNum++;

                Vector3 rootPos = positions[0];
                grp.SetAbsolutePosition(false, rootPos);
                for (int i = 0; i < positions.Count; i++)
                {
                    Vector3 offset = positions[i] - rootPos;
                    grp.ChildrenList[i].SetOffsetPosition(offset);
                    Vector3 abs = grp.ChildrenList[i].AbsolutePosition;
                    Vector3 currentPos = positions[i];
                }
                //grp.Rotation = rotations[0];
                for (int i = 0; i < rotations.Count; i++)
                {
                    if (i != 0)
                        grp.ChildrenList[i].SetRotationOffset(false, rotations[i], false);
                }
                grp.UpdateGroupRotationR(rotations[0]);
                data = Encoding.ASCII.GetBytes(grp.ToXml2());
            }
            AssetBase asset = new AssetBase(assetID, assetName, (AssetType) assType, m_service.AgentID) {Data = data};
            asset.ID = m_assetService.Store(asset);
            assetID = asset.ID;

            InventoryItemBase item = new InventoryItemBase
                                         {
                                             Owner = m_service.AgentID,
                                             CreatorId = m_service.AgentID.ToString(),
                                             ID = inventoryItem,
                                             AssetID = asset.ID,
                                             Description = assetDescription,
                                             Name = assetName,
                                             AssetType = assType,
                                             InvType = inType,
                                             Folder = parentFolder,
                                             CurrentPermissions = (uint) PermissionMask.All,
                                             BasePermissions = (uint) PermissionMask.All,
                                             EveryOnePermissions = everyone_mask,
                                             NextPermissions = next_owner_mask,
                                             GroupPermissions = group_mask,
                                             CreationDate = Util.UnixTimeSinceEpoch()
                                         };

            m_inventoryService.AddItem(item);

            return assetID;
        }
Ejemplo n.º 24
0
        public object NullSafeGet(IDataReader rs, string[] names, object owner)
        {
            object texture = null;

            int ord = rs.GetOrdinal(names[0]);
            if (!rs.IsDBNull(ord))
            {
                byte[] bytes = (byte[])rs[ord];
                texture = new Primitive.TextureEntry(bytes, 0, bytes.Length);
            }

            return texture;
        }
Ejemplo n.º 25
0
        /// <summary>
        ///     Parses ad request
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        /// <param name="AgentId"></param>
        /// <returns></returns>
        public byte[] ProcessAdd(Stream request, OSHttpResponse response, UUID AgentId)
        {
            IScenePresence avatar;

            if (!m_scene.TryGetScenePresence(AgentId, out avatar))
                return MainServer.BlankResponse;

            OSDMap r = (OSDMap) OSDParser.Deserialize(HttpServerHandlerHelpers.ReadFully(request));
            UploadObjectAssetMessage message = new UploadObjectAssetMessage();
            try
            {
                message.Deserialize(r);
            }
            catch (Exception ex)
            {
                MainConsole.Instance.Error("[UploadObjectAssetModule]: Error deserializing message " + ex);
                message = null;
            }

            if (message == null)
            {
                response.StatusCode = 400; //501; //410; //404;
                return
                    Encoding.UTF8.GetBytes(
                        "<llsd><map><key>error</key><string>Error parsing Object</string></map></llsd>");
            }

            Vector3 pos = avatar.AbsolutePosition + (Vector3.UnitX*avatar.Rotation);
            Quaternion rot = Quaternion.Identity;
            Vector3 rootpos = Vector3.Zero;

            SceneObjectGroup rootGroup = null;
            SceneObjectGroup[] allparts = new SceneObjectGroup[message.Objects.Length];
            for (int i = 0; i < message.Objects.Length; i++)
            {
                UploadObjectAssetMessage.Object obj = message.Objects[i];
                PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox();

                if (i == 0)
                {
                    rootpos = obj.Position;
                }

                // Combine the extraparams data into it's ugly blob again....
                //int bytelength = 0;
                //for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++)
                //{
                //    bytelength += obj.ExtraParams[extparams].ExtraParamData.Length;
                //}
                //byte[] extraparams = new byte[bytelength];
                //int position = 0;

                //for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++)
                //{
                //    Buffer.BlockCopy(obj.ExtraParams[extparams].ExtraParamData, 0, extraparams, position,
                //                     obj.ExtraParams[extparams].ExtraParamData.Length);
                //
                //    position += obj.ExtraParams[extparams].ExtraParamData.Length;
                // }

                //pbs.ExtraParams = extraparams;
                foreach (UploadObjectAssetMessage.Object.ExtraParam extraParam in obj.ExtraParams)
                {
                    switch ((ushort) extraParam.Type)
                    {
                        case (ushort) ExtraParamType.Sculpt:
                            Primitive.SculptData sculpt = new Primitive.SculptData(extraParam.ExtraParamData, 0);

                            pbs.SculptEntry = true;

                            pbs.SculptTexture = obj.SculptID;
                            pbs.SculptType = (byte) sculpt.Type;

                            break;
                        case (ushort) ExtraParamType.Flexible:
                            Primitive.FlexibleData flex = new Primitive.FlexibleData(extraParam.ExtraParamData, 0);
                            pbs.FlexiEntry = true;
                            pbs.FlexiDrag = flex.Drag;
                            pbs.FlexiForceX = flex.Force.X;
                            pbs.FlexiForceY = flex.Force.Y;
                            pbs.FlexiForceZ = flex.Force.Z;
                            pbs.FlexiGravity = flex.Gravity;
                            pbs.FlexiSoftness = flex.Softness;
                            pbs.FlexiTension = flex.Tension;
                            pbs.FlexiWind = flex.Wind;
                            break;
                        case (ushort) ExtraParamType.Light:
                            Primitive.LightData light = new Primitive.LightData(extraParam.ExtraParamData, 0);
                            pbs.LightColorA = light.Color.A;
                            pbs.LightColorB = light.Color.B;
                            pbs.LightColorG = light.Color.G;
                            pbs.LightColorR = light.Color.R;
                            pbs.LightCutoff = light.Cutoff;
                            pbs.LightEntry = true;
                            pbs.LightFalloff = light.Falloff;
                            pbs.LightIntensity = light.Intensity;
                            pbs.LightRadius = light.Radius;
                            break;
                        case 0x40:
                            pbs.ReadProjectionData(extraParam.ExtraParamData, 0);
                            break;
                    }
                }
                pbs.PathBegin = (ushort) obj.PathBegin;
                pbs.PathCurve = (byte) obj.PathCurve;
                pbs.PathEnd = (ushort) obj.PathEnd;
                pbs.PathRadiusOffset = (sbyte) obj.RadiusOffset;
                pbs.PathRevolutions = (byte) obj.Revolutions;
                pbs.PathScaleX = (byte) obj.ScaleX;
                pbs.PathScaleY = (byte) obj.ScaleY;
                pbs.PathShearX = (byte) obj.ShearX;
                pbs.PathShearY = (byte) obj.ShearY;
                pbs.PathSkew = (sbyte) obj.Skew;
                pbs.PathTaperX = (sbyte) obj.TaperX;
                pbs.PathTaperY = (sbyte) obj.TaperY;
                pbs.PathTwist = (sbyte) obj.Twist;
                pbs.PathTwistBegin = (sbyte) obj.TwistBegin;
                pbs.HollowShape = (HollowShape) obj.ProfileHollow;
                pbs.PCode = (byte) PCode.Prim;
                pbs.ProfileBegin = (ushort) obj.ProfileBegin;
                pbs.ProfileCurve = (byte) obj.ProfileCurve;
                pbs.ProfileEnd = (ushort) obj.ProfileEnd;
                pbs.Scale = obj.Scale;
                pbs.State = 0;
                SceneObjectPart prim = new SceneObjectPart(AgentId, pbs, obj.Position, obj.Rotation,
                                                           Vector3.Zero, obj.Name)
                                           {
                                               UUID = UUID.Random(),
                                               CreatorID = AgentId,
                                               OwnerID = AgentId,
                                               GroupID = obj.GroupID
                                           };
                prim.LastOwnerID = prim.OwnerID;
                prim.CreationDate = Util.UnixTimeSinceEpoch();
                prim.Name = obj.Name;
                prim.Description = "";

                prim.PayPrice[0] = -2;
                prim.PayPrice[1] = -2;
                prim.PayPrice[2] = -2;
                prim.PayPrice[3] = -2;
                prim.PayPrice[4] = -2;
                Primitive.TextureEntry tmp =
                    new Primitive.TextureEntry(UUID.Parse("89556747-24cb-43ed-920b-47caed15465f"));

                for (int j = 0; j < obj.Faces.Length; j++)
                {
                    UploadObjectAssetMessage.Object.Face face = obj.Faces[j];

                    Primitive.TextureEntryFace primFace = tmp.CreateFace((uint) j);

                    primFace.Bump = face.Bump;
                    primFace.RGBA = face.Color;
                    primFace.Fullbright = face.Fullbright;
                    primFace.Glow = face.Glow;
                    primFace.TextureID = face.ImageID;
                    primFace.Rotation = face.ImageRot;
                    primFace.MediaFlags = ((face.MediaFlags & 1) != 0);

                    primFace.OffsetU = face.OffsetS;
                    primFace.OffsetV = face.OffsetT;
                    primFace.RepeatU = face.ScaleS;
                    primFace.RepeatV = face.ScaleT;
                    primFace.TexMapType = (MappingType) (face.MediaFlags & 6);
                }
                pbs.TextureEntry = tmp.GetBytes();
                prim.Shape = pbs;
                prim.Scale = obj.Scale;

                SceneObjectGroup grp = new SceneObjectGroup(prim, m_scene);

                prim.ParentID = 0;
                if (i == 0)
                    rootGroup = grp;

                grp.AbsolutePosition = obj.Position;
                prim.SetRotationOffset(true, obj.Rotation, true);

                grp.RootPart.IsAttachment = false;

                string reason;
                if (m_scene.Permissions.CanRezObject(1, avatar.UUID, pos, out reason))
                {
                    m_scene.SceneGraph.AddPrimToScene(grp);
                    grp.AbsolutePosition = obj.Position;
                }
                else
                {
                    //Stop now then
                    avatar.ControllingClient.SendAlertMessage("You do not have permission to rez objects here: " +
                                                              reason);
                    return MainServer.BlankResponse;
                }
                allparts[i] = grp;
            }

            for (int j = 1; j < allparts.Length; j++)
            {
                rootGroup.LinkToGroup(allparts[j]);
            }

            rootGroup.ScheduleGroupUpdate(PrimUpdateFlags.ForcedFullUpdate);
            pos = m_scene.SceneGraph.GetNewRezLocation(Vector3.Zero, rootpos, UUID.Zero, rot, 1, 1, true,
                                                       allparts[0].GroupScale(), false);

            OSDMap map = new OSDMap();
            map["local_id"] = allparts[0].LocalId;
            return OSDParser.SerializeLLSDXmlBytes(map);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Convert raw uploaded data into the appropriate asset and item.
        /// </summary>
        /// <param name="assetID"></param>
        /// <param name="inventoryItem"></param>
        /// <param name="data"></param>
        public void UploadCompleteHandler(string assetName, string assetDescription, UUID assetID,
                                          UUID inventoryItem, UUID parentFolder, byte[] data, string inventoryType,
                                          string assetType)
        {
            m_log.DebugFormat(
                "Uploaded asset {0} for inventory item {1}, inv type {2}, asset type {3}",
                assetID, inventoryItem, inventoryType, assetType);

            sbyte assType = 0;
            sbyte inType = 0;

            if (inventoryType == "sound")
            {
                inType = 1;
                assType = 1;
            }
            else if (inventoryType == "animation")
            {
                inType = 19;
                assType = 20;
            }
            else if (inventoryType == "wearable")
            {
                inType = 18;
                switch (assetType)
                {
                    case "bodypart":
                        assType = 13;
                        break;
                    case "clothing":
                        assType = 5;
                        break;
                }
            }
            else if (inventoryType == "object")
            {
                inType = (sbyte)InventoryType.Object;
                assType = (sbyte)AssetType.Object;

                List<Vector3> positions = new List<Vector3>();
                List<Quaternion> rotations = new List<Quaternion>();
                OSDMap request = (OSDMap)OSDParser.DeserializeLLSDXml(data);
                OSDArray instance_list = (OSDArray)request["instance_list"];
                OSDArray mesh_list = (OSDArray)request["mesh_list"];
                OSDArray texture_list = (OSDArray)request["texture_list"];
                SceneObjectGroup grp = null;

                List<UUID> textures = new List<UUID>();
                for (int i = 0; i < texture_list.Count; i++)
                {
                    AssetBase textureAsset = new AssetBase(UUID.Random(), assetName, (sbyte)AssetType.Texture, "");
                    textureAsset.Data = texture_list[i].AsBinary();
                    m_assetService.Store(textureAsset);
                    textures.Add(textureAsset.FullID);
                }

                for (int i = 0; i < mesh_list.Count; i++)
                {
                    PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox();

                    Primitive.TextureEntry textureEntry
                        = new Primitive.TextureEntry(Primitive.TextureEntry.WHITE_TEXTURE);
                    OSDMap inner_instance_list = (OSDMap)instance_list[i];

                    OSDArray face_list = (OSDArray)inner_instance_list["face_list"];
                    for (uint face = 0; face < face_list.Count; face++)
                    {
                        OSDMap faceMap = (OSDMap)face_list[(int)face];
                        Primitive.TextureEntryFace f = pbs.Textures.CreateFace(face);
                        if(faceMap.ContainsKey("fullbright"))
                            f.Fullbright = faceMap["fullbright"].AsBoolean();
                        if (faceMap.ContainsKey ("diffuse_color"))
                            f.RGBA = faceMap["diffuse_color"].AsColor4();

                        int textureNum = faceMap["image"].AsInteger();
                        float imagerot = faceMap["imagerot"].AsInteger();
                        float offsets = (float)faceMap["offsets"].AsReal();
                        float offsett = (float)faceMap["offsett"].AsReal();
                        float scales = (float)faceMap["scales"].AsReal();
                        float scalet = (float)faceMap["scalet"].AsReal();

                        if(imagerot != 0)
                            f.Rotation = imagerot;

                        if(offsets != 0)
                            f.OffsetU = offsets;

                        if (offsett != 0)
                            f.OffsetV = offsett;

                        if (scales != 0)
                            f.RepeatU = scales;

                        if (scalet != 0)
                            f.RepeatV = scalet;

                        if (textures.Count > textureNum)
                            f.TextureID = textures[textureNum];
                        else
                            f.TextureID = Primitive.TextureEntry.WHITE_TEXTURE;

                        textureEntry.FaceTextures[face] = f;
                    }

                    pbs.TextureEntry = textureEntry.GetBytes();

                    AssetBase meshAsset = new AssetBase(UUID.Random(), assetName, (sbyte)AssetType.Mesh, "");
                    meshAsset.Data = mesh_list[i].AsBinary();
                    m_assetService.Store(meshAsset);

                    pbs.SculptEntry = true;
                    pbs.SculptTexture = meshAsset.FullID;
                    pbs.SculptType = (byte)SculptType.Mesh;
                    pbs.SculptData = meshAsset.Data;

                    Vector3 position = inner_instance_list["position"].AsVector3();
                    Vector3 scale = inner_instance_list["scale"].AsVector3();
                    Quaternion rotation = inner_instance_list["rotation"].AsQuaternion();

//                    int physicsShapeType = inner_instance_list["physics_shape_type"].AsInteger();
//                    int material = inner_instance_list["material"].AsInteger();
//                    int mesh = inner_instance_list["mesh"].AsInteger();

                    OSDMap permissions = (OSDMap)inner_instance_list["permissions"];
                    int base_mask = permissions["base_mask"].AsInteger();
                    int everyone_mask = permissions["everyone_mask"].AsInteger();
                    UUID creator_id = permissions["creator_id"].AsUUID();
                    UUID group_id = permissions["group_id"].AsUUID();
                    int group_mask = permissions["group_mask"].AsInteger();
//                    bool is_owner_group = permissions["is_owner_group"].AsBoolean();
//                    UUID last_owner_id = permissions["last_owner_id"].AsUUID();
                    int next_owner_mask = permissions["next_owner_mask"].AsInteger();
                    UUID owner_id = permissions["owner_id"].AsUUID();
                    int owner_mask = permissions["owner_mask"].AsInteger();

                    SceneObjectPart prim
                        = new SceneObjectPart(owner_id, pbs, position, Quaternion.Identity, Vector3.Zero);

                    prim.Scale = scale;
                    prim.OffsetPosition = position;
                    rotations.Add(rotation);
                    positions.Add(position);
                    prim.UUID = UUID.Random();
                    prim.CreatorID = creator_id;
                    prim.OwnerID = owner_id;
                    prim.GroupID = group_id;
                    prim.LastOwnerID = prim.OwnerID;
                    prim.CreationDate = Util.UnixTimeSinceEpoch();
                    prim.Name = assetName;
                    prim.Description = "";

                    prim.BaseMask = (uint)base_mask;
                    prim.EveryoneMask = (uint)everyone_mask;
                    prim.GroupMask = (uint)group_mask;
                    prim.NextOwnerMask = (uint)next_owner_mask;
                    prim.OwnerMask = (uint)owner_mask;

                    if (grp == null)
                        grp = new SceneObjectGroup(prim);
                    else
                        grp.AddPart(prim);
                }

                // Fix first link number
                if (grp.Parts.Length > 1)
                    grp.RootPart.LinkNum++;

                Vector3 rootPos = positions[0];
                grp.AbsolutePosition = rootPos;
                for (int i = 0; i < positions.Count; i++)
                {
                    Vector3 offset = positions[i] - rootPos;
                    grp.Parts[i].OffsetPosition = offset;
                }

                for (int i = 0; i < rotations.Count; i++)
                {
                    if (i != 0)
                        grp.Parts[i].RotationOffset = rotations[i];
                }

                grp.UpdateGroupRotationR(rotations[0]);
                data = ASCIIEncoding.ASCII.GetBytes(SceneObjectSerializer.ToOriginalXmlFormat(grp));
            }

            AssetBase asset;
            asset = new AssetBase(assetID, assetName, assType, m_HostCapsObj.AgentID.ToString());
            asset.Data = data;
            if (AddNewAsset != null)
                AddNewAsset(asset);
            else if (m_assetService != null)
                m_assetService.Store(asset);

            InventoryItemBase item = new InventoryItemBase();
            item.Owner = m_HostCapsObj.AgentID;
            item.CreatorId = m_HostCapsObj.AgentID.ToString();
            item.CreatorData = String.Empty;
            item.ID = inventoryItem;
            item.AssetID = asset.FullID;
            item.Description = assetDescription;
            item.Name = assetName;
            item.AssetType = assType;
            item.InvType = inType;
            item.Folder = parentFolder;
            item.CurrentPermissions = (uint)PermissionMask.All;
            item.BasePermissions = (uint)PermissionMask.All;
            item.EveryOnePermissions = 0;
            item.NextPermissions = (uint)(PermissionMask.Move | PermissionMask.Modify | PermissionMask.Transfer);
            item.CreationDate = Util.UnixTimeSinceEpoch();

            if (AddNewInventoryItem != null)
            {
                AddNewInventoryItem(m_HostCapsObj.AgentID, item);
            }
        }
Ejemplo n.º 27
0
        public AvatarAppearance(AvatarAppearance appearance, bool copyWearables)
        {
            //            m_log.WarnFormat("[AVATAR APPEARANCE] create from an existing appearance");

            if (appearance == null)
            {
                m_serial = 1;
                m_owner = UUID.Zero;

                SetDefaultWearables();
                SetDefaultTexture();
                SetDefaultParams();
                SetHeight();

                m_attachments = new Dictionary<int, List<AvatarAttachment>>();

                return;
            }

            m_serial = appearance.Serial;
            m_owner = appearance.Owner;

            m_wearables = new AvatarWearable[AvatarWearable.MAX_WEARABLES];
            for (int i = 0; i < AvatarWearable.MAX_WEARABLES; i++)
                m_wearables[i] = new AvatarWearable();
            if (copyWearables && (appearance.Wearables != null))
            {
                for (int i = 0; i < AvatarWearable.MAX_WEARABLES; i++)
                    SetWearable(i, appearance.Wearables[i]);
            }

            m_texture = null;
            if (appearance.Texture != null)
            {
                byte[] tbytes = appearance.Texture.GetBytes();
                m_texture = new Primitive.TextureEntry(tbytes, 0, tbytes.Length);
            }

            m_visualparams = null;
            if (appearance.VisualParams != null)
                m_visualparams = (byte[])appearance.VisualParams.Clone();

            // Copy the attachment, force append mode since that ensures consistency
            m_attachments = new Dictionary<int, List<AvatarAttachment>>();
            foreach (AvatarAttachment attachment in appearance.GetAttachments())
                AppendAttachment(new AvatarAttachment(attachment));
        }
Ejemplo n.º 28
0
        public AgentSetAppearancePacket MakeAppearancePacket()
        {
            AgentSetAppearancePacket set = new AgentSetAppearancePacket();
            set.AgentData.AgentID = Client.Self.AgentID;
            set.AgentData.SessionID = Client.Self.SessionID;
            set.AgentData.SerialNum = (uint)Interlocked.Increment(ref SetAppearanceSerialNum);

            // Visual params used in the agent height calculation
            float agentSizeVPHeight = 0.0f;
            float agentSizeVPHeelHeight = 0.0f;
            float agentSizeVPPlatformHeight = 0.0f;
            float agentSizeVPHeadSize = 0.5f;
            float agentSizeVPLegLength = 0.0f;
            float agentSizeVPNeckLength = 0.0f;
            float agentSizeVPHipLength = 0.0f;

            lock (Wearables)
            {
                #region VisualParam

                int vpIndex = 0;
                int nrParams;
                bool wearingPhysics = false;

                foreach (WearableData wearable in Wearables.Values)
                {
                    if (wearable.WearableType == WearableType.Physics)
                    {
                        wearingPhysics = true;
                        break;
                    }
                }

                if (wearingPhysics)
                {
                    nrParams = 251;
                }
                else
                {
                    nrParams = 218;
                }

                set.VisualParam = new AgentSetAppearancePacket.VisualParamBlock[nrParams];

                foreach (KeyValuePair<int, VisualParam> kvp in VisualParams.Params)
                {
                    VisualParam vp = kvp.Value;
                    float paramValue = 0f;
                    bool found = false;

                    // Try and find this value in our collection of downloaded wearables
                    foreach (WearableData data in Wearables.Values)
                    {
                        if (data.Asset != null && data.Asset.Params.TryGetValue(vp.ParamID, out paramValue))
                        {
                            found = true;
                            break;
                        }
                    }

                    // Use a default value if we don't have one set for it
                    if (!found)
                        paramValue = vp.DefaultValue;

                    // Only Group-0 parameters are sent in AgentSetAppearance packets
                    if (kvp.Value.Group == 0)
                    {
                        set.VisualParam[vpIndex] = new AgentSetAppearancePacket.VisualParamBlock();
                        set.VisualParam[vpIndex].ParamValue = Utils.FloatToByte(paramValue, vp.MinValue, vp.MaxValue);
                        ++vpIndex;
                    }

                    // Check if this is one of the visual params used in the agent height calculation
                    switch (vp.ParamID)
                    {
                        case 33:
                            agentSizeVPHeight = paramValue;
                            break;
                        case 198:
                            agentSizeVPHeelHeight = paramValue;
                            break;
                        case 503:
                            agentSizeVPPlatformHeight = paramValue;
                            break;
                        case 682:
                            agentSizeVPHeadSize = paramValue;
                            break;
                        case 692:
                            agentSizeVPLegLength = paramValue;
                            break;
                        case 756:
                            agentSizeVPNeckLength = paramValue;
                            break;
                        case 842:
                            agentSizeVPHipLength = paramValue;
                            break;
                    }

                    if (vpIndex == nrParams) break;
                }

                MyVisualParameters = new byte[set.VisualParam.Length];
                for (int i = 0; i < set.VisualParam.Length; i++)
                {
                    MyVisualParameters[i] = set.VisualParam[i].ParamValue;
                }

                #endregion VisualParam

                #region TextureEntry

                Primitive.TextureEntry te = new Primitive.TextureEntry(DEFAULT_AVATAR_TEXTURE);

                for (uint i = 0; i < Textures.Length; i++)
                {
                    if ((i == 0 || i == 5 || i == 6) && Client.Settings.CLIENT_IDENTIFICATION_TAG != UUID.Zero)
                    {
                        Primitive.TextureEntryFace face = te.CreateFace(i);
                        face.TextureID = Client.Settings.CLIENT_IDENTIFICATION_TAG;
                        Logger.DebugLog("Sending client identification tag: " + Client.Settings.CLIENT_IDENTIFICATION_TAG, Client);
                    }
                    else if (Textures[i].TextureID != UUID.Zero)
                    {
                        Primitive.TextureEntryFace face = te.CreateFace(i);
                        face.TextureID = Textures[i].TextureID;
                        Logger.DebugLog("Sending texture entry for " + (AvatarTextureIndex)i + " to " + Textures[i].TextureID, Client);
                    }
                }

                set.ObjectData.TextureEntry = te.GetBytes();
                MyTextures = te;

                #endregion TextureEntry

                #region WearableData

                set.WearableData = new AgentSetAppearancePacket.WearableDataBlock[BAKED_TEXTURE_COUNT];

                // Build hashes for each of the bake layers from the individual components
                for (int bakedIndex = 0; bakedIndex < BAKED_TEXTURE_COUNT; bakedIndex++)
                {
                    UUID hash = UUID.Zero;

                    for (int wearableIndex = 0; wearableIndex < WEARABLES_PER_LAYER; wearableIndex++)
                    {
                        WearableType type = WEARABLE_BAKE_MAP[bakedIndex][wearableIndex];

                        WearableData wearable;
                        if (type != WearableType.Invalid && Wearables.TryGetValue(type, out wearable))
                            hash ^= wearable.AssetID;
                    }

                    if (hash != UUID.Zero)
                    {
                        // Hash with our magic value for this baked layer
                        hash ^= BAKED_TEXTURE_HASH[bakedIndex];
                    }

                    // Tell the server what cached texture assetID to use for each bake layer
                    set.WearableData[bakedIndex] = new AgentSetAppearancePacket.WearableDataBlock();
                    set.WearableData[bakedIndex].TextureIndex = BakeIndexToTextureIndex[bakedIndex];
                    set.WearableData[bakedIndex].CacheID = hash;
                    Logger.DebugLog("Sending TextureIndex " + (BakeType)bakedIndex + " with CacheID " + hash, Client);
                }

                #endregion WearableData

                #region Agent Size

                // Takes into account the Shoe Heel/Platform offsets but not the HeadSize offset. Seems to work.
                double agentSizeBase = 1.706;

                // The calculation for the HeadSize scalar may be incorrect, but it seems to work
                double agentHeight = agentSizeBase + (agentSizeVPLegLength * .1918) + (agentSizeVPHipLength * .0375) +
                    (agentSizeVPHeight * .12022) + (agentSizeVPHeadSize * .01117) + (agentSizeVPNeckLength * .038) +
                    (agentSizeVPHeelHeight * .08) + (agentSizeVPPlatformHeight * .07);

                set.AgentData.Size = new Vector3(0.45f, 0.6f, (float)agentHeight);

                #endregion Agent Size

                if (Client.Settings.AVATAR_TRACKING)
                {
                    Avatar me;
                    if (Client.Network.CurrentSim.ObjectsAvatars.TryGetValue(Client.Self.LocalID, out me))
                    {
                        me.Textures = MyTextures;
                        me.VisualParameters = MyVisualParameters;
                    }
                }
            }
            return set;
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Set up appearance textures.
        /// Returns boolean that indicates whether the new entries actually change the
        /// existing values.
        /// </summary>
        public virtual bool SetTextureEntries(Primitive.TextureEntry textureEntry, out List<UUID> ChangedTextures)
        {
            ChangedTextures = new List<UUID>();
            if (textureEntry == null)
                return false;

            // There are much simpler versions of this copy that could be
            // made. We determine if any of the textures actually
            // changed to know if the appearance should be saved later
            bool changed = false;
            for (uint i = 0; i < AvatarAppearance.TEXTURE_COUNT; i++)
            {
                Primitive.TextureEntryFace newface = textureEntry.FaceTextures[i];
                Primitive.TextureEntryFace oldface = m_texture.FaceTextures[i];

                if (newface == null)
                {
                    if (oldface == null) continue;
                }
                else
                {
                    if (oldface != null && oldface.TextureID == newface.TextureID) continue;
                }

                //Ignore the 0 based one... as its always null and causes issues
                if (i > 0)
                {
                    changed = true;
                    if (oldface != null)
                        if (!ChangedTextures.Contains(oldface.TextureID))
                            ChangedTextures.Add(oldface.TextureID);

                    //                if (newface != null)
                    //                    m_log.WarnFormat("[AVATAR APPEARANCE]: index {0}, new texture id {1}",i,newface.TextureID);
                }
            }

            if (changed)
            {
                Serial++;
                m_log.Debug("[Appearance]: Incrementing Serial (Textures) to " + Serial);
            }

            m_texture = textureEntry;
            return changed;
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Set the color & alpha of prim faces
        /// </summary>
        /// <param name="face"></param>
        /// <param name="color"></param>
        /// <param name="alpha"></param>
        public void SetFaceColorAlpha(int face, Vector3 color, double ?alpha)
        {
            Vector3 clippedColor = Util.Clip(color, 0.0f, 1.0f);
            float clippedAlpha = alpha.HasValue ?
                Util.Clip((float)alpha.Value, 0.0f, 1.0f) : 0;

            // The only way to get a deep copy/ If we don't do this, we can
            // never detect color changes further down.
            Byte[] buf = Shape.Textures.GetBytes();
            Primitive.TextureEntry tex = new Primitive.TextureEntry(buf, 0, buf.Length);
            Color4 texcolor;
            if (face >= 0 && face < GetNumberOfSides())
            {
                texcolor = tex.CreateFace((uint)face).RGBA;
                texcolor.R = clippedColor.X;
                texcolor.G = clippedColor.Y;
                texcolor.B = clippedColor.Z;
                if (alpha.HasValue)
                {
                    texcolor.A = clippedAlpha;
                }
                tex.FaceTextures[face].RGBA = texcolor;
                UpdateTextureEntry(tex.GetBytes());
                return;
            }
            else if (face == ALL_SIDES)
            {
                for (uint i = 0; i < GetNumberOfSides(); i++)
                {
                    if (tex.FaceTextures[i] != null)
                    {
                        texcolor = tex.FaceTextures[i].RGBA;
                        texcolor.R = clippedColor.X;
                        texcolor.G = clippedColor.Y;
                        texcolor.B = clippedColor.Z;
                        if (alpha.HasValue)
                        {
                            texcolor.A = clippedAlpha;
                        }
                        tex.FaceTextures[i].RGBA = texcolor;
                    }
                    texcolor = tex.DefaultTexture.RGBA;
                    texcolor.R = clippedColor.X;
                    texcolor.G = clippedColor.Y;
                    texcolor.B = clippedColor.Z;
                    if (alpha.HasValue)
                    {
                        texcolor.A = clippedAlpha;
                    }
                    tex.DefaultTexture.RGBA = texcolor;
                }
                UpdateTextureEntry(tex.GetBytes());
                return;
            }
        }