Ejemplo n.º 1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="blueprint"></param>
        /// <returns></returns>
        /// <remarks>For use with Narrative Threads.</remarks>
        public InstanceBehaviour CreateInstanceBehaviourFromBlueprint(INWN2Blueprint blueprint)
        {
            if (blueprint == null)
            {
                throw new ArgumentNullException("blueprint");
            }

            string tag = ((INWN2Object)blueprint).Tag;

            string displayName = GetDisplayName(blueprint);

            if (displayName == String.Empty)
            {
                displayName = tag;
            }

            string areaTag = String.Empty;

            string resRef = blueprint.ResourceName.Value;

            string icon;

            if (blueprint is NWN2ItemBlueprint)
            {
                icon = ((NWN2ItemBlueprint)blueprint).Icon.ToString();
            }
            else
            {
                icon = String.Empty;
            }

            return(new InstanceBehaviour(tag, displayName, blueprint.ObjectType, areaTag, resRef, icon));
        }
Ejemplo n.º 2
0
        public void CreateNarrativeThreadsBlock(INWN2Blueprint blueprint)
        {
            if (blueprint == null)
            {
                throw new ArgumentNullException("blueprint");
            }

            // Wait for up to 3 seconds for the image to appear:
            WaitForNarrativeThreadsImage(blueprint.Resource.ResRef.Value, 3000);

            Action action = new Action
                            (
                delegate()
            {
                string bag = String.Format(InstanceBagNamingFormat, blueprint.ObjectType.ToString());

                if (manager.HasBag(bag))
                {
                    ObjectBlock block = blocks.CreateInstanceBlockFromBlueprint(blueprint);
                    manager.AddMoveable(bag, block);
                }
            }
                            );

            uiThreadAccess.Dispatcher.Invoke(DispatcherPriority.Normal, action);
        }
Ejemplo n.º 3
0
        public BlueprintBehaviour CreateBlueprintBehaviour(INWN2Blueprint blueprint)
        {
            if (blueprint == null)
            {
                throw new ArgumentNullException("blueprint");
            }

            string objectTypeString = blueprint.ObjectType.ToString();
            string resRef           = blueprint.ResourceName.Value;
            string baseResRef       = blueprint.TemplateResRef.Value;

            string displayName = GetDisplayName(blueprint);

            if (displayName == String.Empty)
            {
                displayName = blueprint.Name;
            }

            string icon;

            if (blueprint is NWN2ItemTemplate)
            {
                icon = ((NWN2ItemTemplate)blueprint).Icon.ToString();
            }
            else
            {
                icon = String.Empty;
            }

            return(new BlueprintBehaviour(resRef, displayName, baseResRef, icon, blueprint.ObjectType));
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Checks whether a given blueprint
 /// appears to have been created by Narrative Threads.
 /// </summary>
 /// <param name="behaviour">The blueprint to check.</param>
 /// <returns>True if the blueprint appears to have
 /// been created by Narrative Threads; false otherwise.</returns>
 public bool CreatedByNarrativeThreads(INWN2Blueprint blueprint)
 {
     if (blueprint == null)
     {
         throw new ArgumentNullException("blueprint");
     }
     return(CreatedByNarrativeThreads(Nwn2ScriptSlot.GetNwn2Type(blueprint.ObjectType), blueprint.Resource.ResRef.Value));
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Saves the currently selected instance in the Area viewer to a
        /// user-labeled file.
        /// @note Check that instance is valid before call.
        /// </summary>
        /// <param name="iinstance"></param>
        /// <param name="repo"></param>
        internal static void SaveInstanceToFile(INWN2Instance iinstance, DirectoryResourceRepository repo = null)
        {
            INWN2Blueprint iblueprint = CreateBlueprint(iinstance, repo);

            if (iblueprint != null)
            {
                SaveBlueprintToFile(iblueprint, repo);
            }
        }
Ejemplo n.º 6
0
        public ObjectBlock GetBlock(Nwn2Address address)
        {
            if (address == null)
            {
                throw new ArgumentNullException("address");
            }

            if (session.GetModule() == null)
            {
                throw new InvalidOperationException("No module is open.");
            }

            if (address.TargetType == Nwn2Type.Module)
            {
                return(blocks.CreateModuleBlock());
            }

            else if (address.TargetType == Nwn2Type.Area)
            {
                NWN2GameArea area = session.GetArea(address.AreaTag);

                if (area == null)
                {
                    throw new ArgumentException("No such area in the current module.", "area");
                }
                else
                {
                    return(blocks.CreateAreaBlock(area));
                }
            }

            else
            {
                NWN2ObjectType type = Nwn2ScriptSlot.GetObjectType(address.TargetType).Value;

                INWN2Blueprint blueprint = session.GetBlueprint(address.InstanceTag, type);
                if (blueprint != null)
                {
                    return(blocks.CreateInstanceBlockFromBlueprint(blueprint));
                }

                foreach (NWN2AreaViewer viewer in NWN2Toolset.NWN2ToolsetMainForm.App.GetAllAreaViewers())
                {
                    NWN2InstanceCollection instances = session.GetObjectsByAddressInArea(address, viewer.Area.Tag);

                    if (instances.Count > 0)
                    {
                        INWN2Instance instance = instances[0];
                        return(blocks.CreateInstanceBlock(instance));
                    }
                }

                return(null);
            }
        }
Ejemplo n.º 7
0
        public ObjectBlock CreateInstanceBlockFromBlueprint(INWN2Blueprint blueprint)
        {
            if (blueprint == null)
            {
                throw new ArgumentNullException("blueprint");
            }

            InstanceBehaviour behaviour = CreateInstanceBehaviourFromBlueprint(blueprint);

            ObjectBlock block = CreateInstanceBlock(behaviour);

            return(block);
        }
Ejemplo n.º 8
0
        public void CreateNarrativeThreadsBlock(object blueprint)
        {
            if (blueprint == null)
            {
                throw new ArgumentNullException("blueprint");
            }
            INWN2Blueprint bp = blueprint as INWN2Blueprint;

            if (bp == null)
            {
                throw new ArgumentException("blueprint must implement interface INWN2Blueprint.", "blueprint");
            }
            CreateNarrativeThreadsBlock(bp);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Creates an instance of a blueprint and adds it to the area.
        /// </summary>
        /// <param name="blueprint">The blueprint to create the game
        /// object from.</param>
        /// <param name="tag">The tag to give the newly-created object.
        /// Pass null to use the default tag.</param>
        /// <returns>The newly-created game object.</returns>
        public override INWN2Instance AddGameObject(INWN2Blueprint blueprint, string tag)
        {
            if (blueprint == null)
            {
                throw new ArgumentNullException("blueprint", "Need a blueprint to create object from.");
            }

            INWN2Instance instance = NWN2GlobalBlueprintManager.CreateInstanceFromBlueprint(blueprint);

            if (tag != null)
            {
                ((INWN2Object)instance).Tag = tag;
            }

            nwn2Area.AddInstance(instance);

            return(instance);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Creates an instance of a blueprint and adds it to the area.
        /// </summary>
        /// <param name="type">The type of object to add.</param>
        /// <param name="resref">The resref of the blueprint to create the object from.</param>
        /// <param name="tag">The tag to give the newly-created object.
        /// Pass null to use the default tag.</param>
        /// <param name="position">The position within the area to place
        /// the object.</param>
        /// <returns>The newly-created game object.</returns>
        public override INWN2Instance AddGameObject(NWN2ObjectType type, string resref, string tag, Vector3?position)
        {
            if (resref == null)
            {
                throw new ArgumentNullException("resref");
            }
            if (resref == String.Empty)
            {
                throw new ArgumentException("resref cannot be an empty string.", "resref");
            }

            INWN2Blueprint blueprint = NWN2GlobalBlueprintManager.FindBlueprint(type, new OEIResRef(resref), true, true, true);

            if (blueprint == null)
            {
                throw new ArgumentException("No blueprint with the given type and ResRef was found.", "resref");
            }

            return(AddGameObject(blueprint, tag, position));
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Creates an instance of a blueprint and adds it to the area.
        /// </summary>
        /// <param name="blueprint">The blueprint to create the game
        /// object from.</param>
        /// <param name="tag">The tag to give the newly-created object.
        /// Pass null to use the default tag.</param>
        /// <param name="position">The position within the area to place
        /// the object.</param>
        /// <returns>The newly-created game object.</returns>
        public override INWN2Instance AddGameObject(INWN2Blueprint blueprint, string tag, Vector3?position)
        {
            INWN2Instance instance = AddGameObject(blueprint, tag);

            if (position.HasValue)
            {
                INWN2SituatedInstance situated = instance as INWN2SituatedInstance;
                if (situated == null)
                {
                    throw new ArgumentException("Instances of the given blueprint have " +
                                                "no Position field - their position cannot be set.", "blueprint");
                }
                else
                {
                    situated.Position = position.Value;
                }
            }

            return(instance);
        }
Ejemplo n.º 12
0
 /// <summary>
 /// Creates an instance of a blueprint and adds it to the area.
 /// </summary>
 /// <param name="blueprint">The blueprint to create the game
 /// object from.</param>
 /// <param name="tag">The tag to give the newly-created object.
 /// Pass null to use the default tag.</param>
 /// <param name="position">The position within the area to place
 /// the object.</param>
 /// <returns>The newly-created game object.</returns>
 public abstract INWN2Instance AddGameObject(INWN2Blueprint blueprint, string tag, Vector3?position);
Ejemplo n.º 13
0
 /// <summary>
 /// Creates an instance of a blueprint and adds it to the area.
 /// </summary>
 /// <param name="blueprint">The blueprint to create the game
 /// object from.</param>
 /// <param name="tag">The tag to give the newly-created object.
 /// Pass null to use the default tag.</param>
 /// <returns>The newly-created game object.</returns>
 public abstract INWN2Instance AddGameObject(INWN2Blueprint blueprint, string tag);
Ejemplo n.º 14
0
 /// <summary>
 /// Creates an actor from a blueprint
 /// </summary>
 /// <param name="actor">The blueprint that the actor will contain</param>
 /// <param name="type">The type of the blueprint</param>
 public Actor(NWN2Toolset.NWN2.Data.Blueprints.INWN2Blueprint actor, EnumTypes.actorType type)
 {
     blueprint = actor;
     this.type = type;
     boolInstance = false;
 }
Ejemplo n.º 15
0
 /// <summary>
 /// A utility class that is used to create the blueprint
 /// </summary>
 /// <param name="blueprint">The blueprints that will be created</param>
 /// <param name="text">The tempoary blueprint name</param>
 /// <param name="repository">The repository that the blueprint is to be saved in</param>
 /// <param name="num">The file type (I think)</param>
 private static void createHelp(INWN2Blueprint blueprint, string text, IResourceRepository repository, ushort num)
 {
     blueprint.Resource = repository.CreateResource(new OEIResRef(text), num);
     blueprint.TemplateResRef = new OEIResRef(blueprint.Resource.ResRef.Value);
     GFFFile file = new GFFFile();
     file.FileHeader.FileType = BWResourceTypes.GetFileExtension(num);
     blueprint.SaveEverythingIntoGFFStruct(file.TopLevelStruct, true);
     using (Stream stream = blueprint.Resource.GetStream(true))
         {
         file.Save(stream);
         blueprint.Resource.Release();
         }
 }
Ejemplo n.º 16
0
        /// <summary>
        /// Translates Flip source into NWScript, compiles it,
        /// and attaches the results to a Neverwinter Nights 2 module.
        /// </summary>
        /// <param name="source">The Flip source to be compiled.</param>
        /// <param name="address">An address representing the location
        /// to attach this script to.</param>
        /// <returns>The name the script was saved under.</returns>
        public override string Attach(FlipScript source, string address)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (address == null)
            {
                throw new ArgumentNullException("address");
            }
            if (address == String.Empty)
            {
                throw new ArgumentException("Must provide a valid address for attaching script.", "address");
            }

            if (!Nwn2ToolsetFunctions.ToolsetIsOpen())
            {
                throw new InvalidOperationException("Toolset must be open to attach scripts.");
            }

            NWN2GameModule module = session.GetModule();

            if (module == null)
            {
                throw new InvalidOperationException("No module is currently open in the toolset.");
            }

            string name = GetUnusedName();

            try {
                if (name.Length > 32)
                {
                    throw new ApplicationException("Cannot attach script under the generated name ('" + name + "') " +
                                                   "because it is of length " + name.Length + ", and the maximum " +
                                                   "valid length of a resource name for NWN2 is 32.");
                }

                NWN2GameScript script = session.AddScript(name, source.Code);

                session.CompileScript(script);

                if (address.StartsWith("Conversation"))
                {
                    Nwn2ConversationAddress convAddress = new Nwn2ConversationAddress(address);

                    NWN2GameConversation conversation = session.GetConversation(convAddress.Conversation);

                    if (conversation == null)
                    {
                        throw new ArgumentException("Conversation '" + convAddress.Conversation + "' was not found in current module.", "address");
                    }

//					foreach (NWN2Toolset.NWN2.Views.INWN2Viewer v in NWN2Toolset.NWN2ToolsetMainForm.App.GetAllViewers()) {
//						NWN2Toolset.NWN2.Views.NWN2ConversationViewer cv = v as NWN2Toolset.NWN2.Views.NWN2ConversationViewer;
//						if (cv != null) {
//							System.Windows.MessageBox.Show("From viewer...\n" + cv.Conversation.Name +
//							                               "\nConnectors: " + cv.Conversation.AllConnectors.Count + "\n" +
//							                               "Entries: " + cv.Conversation.Entries.Count + "\n" +
//							                               "Replies: " + cv.Conversation.Replies.Count + "\n" +
//							                               "Loaded: " + conversation.Loaded);
//						}
//					}
//
//
//							System.Windows.MessageBox.Show("From module, before insisting on load...\n" + conversation.Name +
//							                               "\nConnectors: " + conversation.AllConnectors.Count + "\n" +
//							                               "Entries: " + conversation.Entries.Count + "\n" +
//							                               "Replies: " + conversation.Replies.Count + "\n" +
//							                               "Loaded: " + conversation.Loaded);
//
//
//
//					if (!conversation.Loaded) conversation.Demand();
//
//
//							System.Windows.MessageBox.Show("From module, after insisting on load...\n" + conversation.Name +
//							                               "\nConnectors: " + conversation.AllConnectors.Count + "\n" +
//							                               "Entries: " + conversation.Entries.Count + "\n" +
//							                               "Replies: " + conversation.Replies.Count + "\n" +
//							                               "Loaded: " + conversation.Loaded);



                    NWN2ConversationLine line = session.GetConversationLine(conversation, convAddress.LineID);

                    if (line == null)
                    {
                        throw new ArgumentException("Line with ID " + convAddress.LineID + " was not found in current module.", "address");
                    }

                    if (convAddress.AttachedAs == ScriptType.Conditional)
                    {
                        session.AttachScriptToConversationAsCondition(script, line, conversation);
                    }

                    else
                    {
                        session.AttachScriptToConversation(script, line, conversation);
                    }
                }

                else
                {
                    Nwn2Address nwn2Address = new Nwn2Address(address);

                    if (!Scripts.IsEventRaiser(nwn2Address.TargetType))
                    {
                        throw new ArgumentException("Cannot attach scripts to a " + nwn2Address.TargetType + ".");
                    }

                    if (nwn2Address.TargetType == Nwn2Type.Module)
                    {
                        session.AttachScriptToModule(script, nwn2Address.TargetSlot);
                    }

                    else if (nwn2Address.TargetType == Nwn2Type.Area)
                    {
                        NWN2GameArea area = session.GetArea(nwn2Address.AreaTag);
                        if (area == null)
                        {
                            throw new ArgumentException("Area '" + nwn2Address.AreaTag + "' was not found in current module.", "address");
                        }

                        session.AttachScriptToArea(script, area, nwn2Address.TargetSlot);
                    }

                    else
                    {
                        /*
                         * We want to attach to ALL instances matching the address in ALL OPEN areas, ignoring AreaTag and UseIndex.
                         */

                        NWN2ObjectType nwn2ObjectType = Nwn2ScriptSlot.GetObjectType(nwn2Address.TargetType).Value;

                        bool attached = false;

                        foreach (NWN2GameArea a in module.Areas.Values)
                        {
                            if (!session.AreaIsOpen(a))
                            {
                                continue;
                            }

                            NWN2InstanceCollection instances = session.GetObjectsByTag(a, nwn2ObjectType, nwn2Address.InstanceTag);

                            foreach (INWN2Instance instance in instances)
                            {
                                session.AttachScriptToObject(script, instance, nwn2Address.TargetSlot);
                                attached = true;
                            }
                        }

                        /*
                         * We also want to attach to any blueprints which use this tag as their resref.
                         */

                        // First check that if a blueprint which uses this tag as resref exists, it was created by Narrative Threads:
                        if (nt.CreatedByNarrativeThreads(Nwn2ScriptSlot.GetNwn2Type(nwn2ObjectType), nwn2Address.InstanceTag))
                        {
                            INWN2Blueprint blueprint = session.GetBlueprint(nwn2Address.InstanceTag.ToLower(), nwn2ObjectType);

                            if (blueprint != null)
                            {
                                session.AttachScriptToBlueprint(script, blueprint, nwn2Address.TargetSlot);
                                attached = true;
                            }
                        }

                        if (!attached)
                        {
                            string error;

                            if (nt.IsLoaded)
                            {
                                error = String.Format("There isn't a {0} with tag '{1}' in any of the areas that are open, or " +
                                                      "in the blueprints collection.",
                                                      nwn2Address.TargetType,
                                                      nwn2Address.InstanceTag);
                            }
                            else
                            {
                                error = String.Format("There isn't a {0} with tag '{1}' in any of the areas that are open.",
                                                      nwn2Address.TargetType,
                                                      nwn2Address.InstanceTag);
                            }

                            throw new MatchingInstanceNotFoundException(error, nwn2Address);
                        }
                    }
                }
            }
            catch (MatchingInstanceNotFoundException x) {
                throw x;
            }
            catch (Exception x) {
                throw new ApplicationException("Something went wrong while saving and attaching script.", x);
            }

            if (backups != null)
            {
                if (!Directory.Exists(backups))
                {
                    try {
                        Directory.CreateDirectory(backups);
                    }
                    catch (Exception) {
                        return(name);
                    }
                }

                string saveTo;

                if (createFoldersForUsers)
                {
                    try {
                        saveTo = Path.Combine(backups, Environment.UserName);
                        if (!Directory.Exists(saveTo))
                        {
                            Directory.CreateDirectory(saveTo);
                        }

                        saveTo = Path.Combine(saveTo, module.Name);
                        if (!Directory.Exists(saveTo))
                        {
                            Directory.CreateDirectory(saveTo);
                        }
                    }
                    catch (Exception) {
                        saveTo = backups;
                    }
                }
                else
                {
                    saveTo = backups;
                }

                try {
                    WriteBackup(name, saveTo, source.Code);
                }
                catch (Exception) {     }
            }

            return(name);
        }
Ejemplo n.º 17
0
 /// <summary>
 /// Constructs a new <see cref="Sussex.Flip.Games.NeverwinterNightsTwo.Utils.BlueprintEventArgs"/> instance.
 /// </summary>
 /// <param name="blueprint">The blueprint relating to this event.</param>
 public BlueprintEventArgs(INWN2Blueprint blueprint)
 {
     this.blueprint = blueprint;
 }
Ejemplo n.º 18
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="script"></param>
        /// <param name="attachment">Only return a script if it is attached
        /// in the manner indicated by this parameter.</param>
        /// <returns></returns>
        /// <remarks>This method expects that the NWN2GameScript is already Loaded
        /// (that is, the responsibility for calling Demand() falls to the client.)</remarks>
        public FlipScript GetFlipScript(NWN2GameScript script, Attachment attachment)
        {
            if (script == null)
            {
                throw new ArgumentNullException("script");
            }

            string code, address, naturalLanguage;

            ScriptWriter.ParseNWScript(script.Data, out code, out address, out naturalLanguage);

            ScriptType scriptType = GetScriptType(script);

            if (attachment == Attachment.Ignore)
            {
                return(new FlipScript(code, scriptType, script.Name));
            }

            NWN2GameModule mod = session.GetModule();

            if (mod == null)
            {
                throw new InvalidOperationException("No module is open.");
            }

            Nwn2Address             nwn2Address;
            Nwn2ConversationAddress nwn2ConversationAddress;

            switch (attachment)
            {
            case Attachment.Attached:
                nwn2Address             = Nwn2Address.TryCreate(address);
                nwn2ConversationAddress = Nwn2ConversationAddress.TryCreate(address);
                break;

            case Attachment.AttachedToConversation:
                nwn2Address             = null;
                nwn2ConversationAddress = Nwn2ConversationAddress.TryCreate(address);
                break;

            case Attachment.AttachedToScriptSlot:
                nwn2Address             = Nwn2Address.TryCreate(address);
                nwn2ConversationAddress = null;
                break;

            default:
                nwn2Address             = null;
                nwn2ConversationAddress = null;
                break;
            }

            if (nwn2Address != null)
            {
                try {
                    if (nwn2Address.TargetType == Nwn2Type.Module)
                    {
                        IResourceEntry resource = typeof(NWN2ModuleInformation).GetProperty(nwn2Address.TargetSlot).GetValue(mod.ModuleInfo, null) as IResourceEntry;
                        if (resource != null && resource.ResRef.Value == script.Name)
                        {
                            return(new FlipScript(code, scriptType, script.Name));
                        }
                    }

                    else if (nwn2Address.TargetType == Nwn2Type.Area)
                    {
                        NWN2GameArea area = session.GetArea(nwn2Address.AreaTag);

                        if (area != null)
                        {
                            IResourceEntry resource = typeof(NWN2GameArea).GetProperty(nwn2Address.TargetSlot).GetValue(area, null) as IResourceEntry;
                            if (resource != null && resource.ResRef.Value == script.Name)
                            {
                                return(new FlipScript(code, scriptType, script.Name));
                            }
                        }
                    }

                    else
                    {
                        /*
                         * The script might be attached to a Narrative Threads blueprint:
                         */

                        // First check that if a blueprint which uses this tag as resref exists, it was created by Narrative Threads:

                        if (nt.CreatedByNarrativeThreads(nwn2Address.TargetType, nwn2Address.InstanceTag))
                        {
                            NWN2ObjectType objectType = Nwn2ScriptSlot.GetObjectType(nwn2Address.TargetType).Value;
                            INWN2Blueprint blueprint  = session.GetBlueprint(nwn2Address.InstanceTag.ToLower(), objectType);

                            if (blueprint != null)
                            {
                                IResourceEntry resource = blueprint.GetType().GetProperty(nwn2Address.TargetSlot).GetValue(blueprint, null) as IResourceEntry;
                                if (resource != null && resource.ResRef.Value == script.Name)
                                {
                                    return(new FlipScript(code, scriptType, script.Name));
                                }
                            }
                        }

                        // Check through all OPEN areas.
                        foreach (NWN2GameArea area in mod.Areas.Values)
                        {
                            if (!session.AreaIsOpen(area))
                            {
                                continue;
                            }

                            NWN2InstanceCollection instances = session.GetObjectsByAddressInArea(nwn2Address, area.Tag);

                            if (instances != null)
                            {
                                // Check the script is still attached to the target object in the slot it claims to be,
                                // in at least one instance, and if so add it to the set of scripts to be opened:

                                foreach (INWN2Instance instance in instances)
                                {
                                    IResourceEntry resource = instance.GetType().GetProperty(nwn2Address.TargetSlot).GetValue(instance, null) as IResourceEntry;
                                    if (resource != null && resource.ResRef.Value == script.Name)
                                    {
                                        return(new FlipScript(code, scriptType, script.Name));
                                    }
                                }
                            }
                        }
                    }
                }

                catch (Exception x) {
                    throw new ApplicationException(String.Format("Failed to handle script + '{0}' properly.", script.Name), x);
                }
            }

            else if (nwn2ConversationAddress != null)               // Check through all conversations, regardless of whether they're open.

            {
                NWN2GameConversation conversation = session.GetConversation(nwn2ConversationAddress.Conversation);

                if (conversation == null)
                {
                    return(null);
                }

                if (NWN2Toolset.NWN2ToolsetMainForm.App.GetViewerForResource(conversation) == null)
                {
                    conversation.Demand();
                }

                NWN2ConversationLine line = conversation.GetLineFromGUID(nwn2ConversationAddress.LineID);

                if (line == null)
                {
                    return(null);
                }

                if (line.Actions.Count == 0)
                {
                    return(null);
                }

                IResourceEntry resource = line.Actions[0].Script;
                if (resource != null && resource.ResRef.Value == script.Name)
                {
                    return(new FlipScript(code, scriptType, script.Name));
                }
            }

            return(null);
        }
Ejemplo n.º 19
0
        // NWN2Toolset.NWN2.Views.NWN2BlueprintView.ᐌ(object P_0, EventArgs P_1)
        // yeah whatever. Those idiots were too clever for anybody's good.
        /// <summary>
        /// Saves a specified blueprint to a user-labeled file.
        /// IMPORTANT: Allow only creature-blueprints to be saved!
        /// - NWN2ObjectType.Creature
        /// - resourcetype #2027
        /// @note Check that blueprint is valid before call.
        /// </summary>
        /// <param name="iblueprint">ElectronPanel_.Blueprint or .Instance
        /// converted to a blueprint</param>
        /// <param name="repo">null if Override</param>
        internal static void SaveBlueprintToFile(INWN2Blueprint iblueprint, DirectoryResourceRepository repo = null)
        {
            string fil = iblueprint.Resource.ResRef.Value;
            string ext = BWResourceTypes.GetFileExtension(iblueprint.Resource.ResourceType);

            var sfd = new SaveFileDialog();

            sfd.Title    = "Save blueprint as ...";
            sfd.FileName = fil + "." + ext;               // iblueprint.Resource.FullName
            sfd.Filter   = "blueprints (*." + ext + ")|*." + ext + "|all files (*.*)|*.*";
//			sfd.DefaultExt = ext;

            string dir;

            if (repo != null)
            {
                dir = repo.DirectoryName;
            }
            else
            {
                dir = String.Empty;
            }

            if (!String.IsNullOrEmpty(dir))
            {
                if (Directory.Exists(dir))
                {
                    sfd.InitialDirectory = dir;
                    sfd.RestoreDirectory = true;
                }
            }
            else if (!String.IsNullOrEmpty(CreatureVisualizerPreferences.that.LastSaveDirectory) &&
                     Directory.Exists(CreatureVisualizerPreferences.that.LastSaveDirectory))
            {
                sfd.InitialDirectory = CreatureVisualizerPreferences.that.LastSaveDirectory;
            }
            // else TODO: use NWN2ResourceManager.Instance.UserOverrideDirectory
            // else TODO: get BlueprintLocation dir if exists


            if (sfd.ShowDialog() == DialogResult.OK)
            {
                if (String.IsNullOrEmpty(dir))
                {
                    CreatureVisualizerPreferences.that.LastSaveDirectory = Path.GetDirectoryName(sfd.FileName);
                }


                // NOTE: Add 'AppearanceSEF' back in from the original blueprint
                // since it was removed when the original was duplicated by
                // ElectronPanel_.DuplicateBlueprint().
                (iblueprint as NWN2CreatureTemplate).AppearanceSEF = AppearanceSEF;


                IOEISerializable iserializable = iblueprint;
                if (iserializable != null)
                {
                    iserializable.OEISerialize(sfd.FileName);

                    if (File.Exists(sfd.FileName))                     // test that file exists before proceeding
                    {
                        INWN2BlueprintSet blueprintset;

                        dir = Path.GetDirectoryName(sfd.FileName).ToLower();
                        if (dir == NWN2ToolsetMainForm.App.Module.Repository.DirectoryName.ToLower())
                        {
                            repo         = NWN2ToolsetMainForm.App.Module.Repository;
                            blueprintset = NWN2ToolsetMainForm.App.Module as INWN2BlueprintSet;

                            iblueprint.BlueprintLocation = NWN2BlueprintLocationType.Module;
                        }
                        else if (NWN2CampaignManager.Instance.ActiveCampaign != null &&
                                 dir == NWN2CampaignManager.Instance.ActiveCampaign.Repository.DirectoryName.ToLower())
                        {
                            repo         = NWN2CampaignManager.Instance.ActiveCampaign.Repository;
                            blueprintset = NWN2CampaignManager.Instance.ActiveCampaign as INWN2BlueprintSet;

                            iblueprint.BlueprintLocation = NWN2BlueprintLocationType.Campaign;
                        }
                        else if (IsOverride(dir))
                        {
                            repo         = NWN2ResourceManager.Instance.UserOverrideDirectory;
                            blueprintset = NWN2GlobalBlueprintManager.Instance as INWN2BlueprintSet;

                            iblueprint.BlueprintLocation = NWN2BlueprintLocationType.Global;
                        }
                        else
                        {
                            return;
                        }


                        // so, which should be tested for first: resource or blueprint?
                        // and is there even any point in having one w/out the other?

                        string filelabel = Path.GetFileNameWithoutExtension(sfd.FileName);

                        NWN2BlueprintCollection collection = blueprintset.GetBlueprintCollectionForType(NWN2ObjectType.Creature);

                        INWN2Blueprint extantblueprint = NWN2GlobalBlueprintManager.FindBlueprint(NWN2ObjectType.Creature,
                                                                                                  new OEIResRef(filelabel),
                                                                                                  iblueprint.BlueprintLocation == NWN2BlueprintLocationType.Global,
                                                                                                  iblueprint.BlueprintLocation == NWN2BlueprintLocationType.Module,
                                                                                                  iblueprint.BlueprintLocation == NWN2BlueprintLocationType.Campaign);

                        if (extantblueprint != null && extantblueprint.Resource.Repository is DirectoryResourceRepository) // ie. exclude Data\Templates*.zip
                        {
                            collection.Remove(extantblueprint);                                                            // so, does removing a blueprint also remove its resource? no.
                        }

                        IResourceEntry extantresource = repo.FindResource(new OEIResRef(filelabel), 2027);                         // it's maaaaaagick
                        if (extantresource != null)
                        {
                            repo.Resources.Remove(extantresource);                             // so, does removing a resource also remove its blueprint? no.
                        }


                        iblueprint.Resource = repo.CreateResource(iblueprint.Resource.ResRef, iblueprint.Resource.ResourceType);
                        collection.Add(iblueprint);

                        var viewer = NWN2ToolsetMainForm.App.BlueprintView;
                        var list   = viewer.GetFocusedList();
                        list.Resort();

                        var objects = new object[1] {
                            iblueprint as INWN2Object
                        };
                        viewer.Selection = objects;
                    }
                }
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="dict"></param>
        /// <param name="attachment"></param>
        /// <returns></returns>
        /// <remarks>Note that this automatically opens and closes areas/conversations etc. - it is only
        /// for use with analysis methods, not for users.</remarks>
        public List <ScriptTriggerTuple> GetAllScriptsFromModule(Attachment attachment)
        {
            NWN2GameModule mod = session.GetModule();

            if (mod == null)
            {
                throw new InvalidOperationException("No module is open.");
            }

            NWN2GameScriptDictionary dict = mod.Scripts;

            if (attachment == Attachment.Ignore)
            {
                return(GetTuples(dict));
            }

            Dictionary <Nwn2Address, FlipScript>             moduleScripts       = new Dictionary <Nwn2Address, FlipScript>();
            Dictionary <Nwn2Address, FlipScript>             areaScripts         = new Dictionary <Nwn2Address, FlipScript>();
            Dictionary <Nwn2ConversationAddress, FlipScript> conversationScripts = new Dictionary <Nwn2ConversationAddress, FlipScript>();

            foreach (NWN2GameScript nwn2Script in dict.Values)
            {
                try {
                    nwn2Script.Demand();

                    string code, address, naturalLanguage;
                    ScriptWriter.ParseNWScript(nwn2Script.Data, out code, out address, out naturalLanguage);

                    ScriptType scriptType = GetScriptType(nwn2Script);

                    FlipScript script = new FlipScript(code, scriptType, nwn2Script.Name);

                    Nwn2ConversationAddress ca = Nwn2ConversationAddress.TryCreate(address);
                    if (ca != null)
                    {
                        conversationScripts.Add(ca, script);
                    }

                    else
                    {
                        Nwn2Address a = Nwn2Address.TryCreate(address);

                        if (a != null)
                        {
                            if (a.TargetType == Nwn2Type.Module)
                            {
                                moduleScripts.Add(a, script);
                            }

                            else
                            {
                                areaScripts.Add(a, script);
                            }
                        }
                    }

                    nwn2Script.Release();
                }
                catch (Exception) {}
            }

            List <ScriptTriggerTuple> scripts = new List <ScriptTriggerTuple>(dict.Count);           // this is what we'll return

            if (attachment == Attachment.AttachedToConversation || attachment == Attachment.Attached)
            {
                // Index by conversation name, so we can check all the scripts for a conversation in one go.

                Dictionary <string, List <Nwn2ConversationAddress> > convNameIndex = new Dictionary <string, List <Nwn2ConversationAddress> >();

                foreach (Nwn2ConversationAddress address in conversationScripts.Keys)
                {
                    if (!convNameIndex.ContainsKey(address.Conversation))
                    {
                        convNameIndex.Add(address.Conversation, new List <Nwn2ConversationAddress>());
                    }

                    convNameIndex[address.Conversation].Add(address);
                }

                foreach (string convName in convNameIndex.Keys)
                {
                    NWN2GameConversation conv = mod.Conversations[convName];

                    if (conv == null)
                    {
                        continue;
                    }

                    conv.Demand();

                    foreach (Nwn2ConversationAddress address in convNameIndex[convName])
                    {
                        FlipScript script = conversationScripts[address];

                        NWN2ConversationLine line = conv.GetLineFromGUID(address.LineID);

                        if (line == null)
                        {
                            continue;
                        }

                        if (address.AttachedAs == ScriptType.Standard && line.Actions.Count > 0)
                        {
                            IResourceEntry resource = line.Actions[0].Script;
                            if (resource != null && resource.ResRef.Value == script.Name)
                            {
                                scripts.Add(new ScriptTriggerTuple(script, triggerFactory.GetTriggerFromAddress(address)));
                            }
                        }

                        else if (address.AttachedAs == ScriptType.Conditional && line.OwningConnector.Conditions.Count > 0)
                        {
                            IResourceEntry resource = line.OwningConnector.Conditions[0].Script;
                            if (resource != null && resource.ResRef.Value == script.Name)
                            {
                                scripts.Add(new ScriptTriggerTuple(script, triggerFactory.GetTriggerFromAddress(address)));
                            }
                        }
                    }

                    conv.Release();
                }
            }

            if (attachment == Attachment.AttachedToScriptSlot || attachment == Attachment.Attached)
            {
                // First, just check for scripts attached to the module - easy:

                foreach (Nwn2Address address in moduleScripts.Keys)
                {
                    FlipScript script = moduleScripts[address];

                    IResourceEntry resource = typeof(NWN2ModuleInformation).GetProperty(address.TargetSlot).GetValue(mod.ModuleInfo, null) as IResourceEntry;

                    if (resource != null && resource.ResRef.Value == script.Name)
                    {
                        scripts.Add(new ScriptTriggerTuple(script, triggerFactory.GetTriggerFromAddress(address)));
                    }
                }


                // Next, check whether any script is attached to a Narrative Threads blueprint, and
                // if you find one, add it to the collection and remove it from consideration:

                List <Nwn2Address> processed = new List <Nwn2Address>();

                foreach (Nwn2Address address in areaScripts.Keys)
                {
                    if (Nwn2ScriptSlot.GetObjectType(address.TargetType) == null)
                    {
                        continue;                                                                               // ignore area, module etc.
                    }
                    FlipScript script = areaScripts[address];

                    // First check that if a blueprint which uses this tag as resref exists, it was created by Narrative Threads:
                    if (nt.CreatedByNarrativeThreads(address.TargetType, address.InstanceTag))
                    {
                        NWN2ObjectType objectType = Nwn2ScriptSlot.GetObjectType(address.TargetType).Value;
                        INWN2Blueprint blueprint  = session.GetBlueprint(address.InstanceTag.ToLower(), objectType);

                        if (blueprint != null)
                        {
                            IResourceEntry resource = blueprint.GetType().GetProperty(address.TargetSlot).GetValue(blueprint, null) as IResourceEntry;

                            if (resource != null && resource.ResRef.Value == script.Name)
                            {
                                scripts.Add(new ScriptTriggerTuple(script, triggerFactory.GetTriggerFromAddress(address)));
                                processed.Add(address);
                            }
                        }
                    }
                }

                foreach (Nwn2Address p in processed)
                {
                    areaScripts.Remove(p);                                                  // has been added, so don't check for it more than once
                }
                // Then, open each area in turn, and see whether a script is attached to it. If it is, add
                // it to the collection and remove it from consideration:

                foreach (NWN2GameArea area in mod.Areas.Values)
                {
                    if (areaScripts.Count == 0)
                    {
                        break;
                    }

                    session.OpenArea(area);

                    processed = new List <Nwn2Address>();

                    foreach (Nwn2Address address in areaScripts.Keys)
                    {
                        FlipScript script = areaScripts[address];

                        if (address.TargetType == Nwn2Type.Area)
                        {
                            IResourceEntry resource = typeof(NWN2GameArea).GetProperty(address.TargetSlot).GetValue(area, null) as IResourceEntry;

                            if (resource != null && resource.ResRef.Value == script.Name)
                            {
                                scripts.Add(new ScriptTriggerTuple(script, triggerFactory.GetTriggerFromAddress(address)));
                                processed.Add(address);                                 // don't check whether to add it more than once
                            }
                        }

                        else
                        {
                            NWN2InstanceCollection instances = session.GetObjectsByAddressInArea(address, area.Tag);

                            if (instances != null)
                            {
                                // Check the script is still attached to the target object in the slot it claims to be,
                                // in at least one instance, and if so add it to the set of scripts to be opened:

                                foreach (INWN2Instance instance in instances)
                                {
                                    IResourceEntry resource = instance.GetType().GetProperty(address.TargetSlot).GetValue(instance, null) as IResourceEntry;

                                    if (resource != null && resource.ResRef.Value == script.Name)
                                    {
                                        scripts.Add(new ScriptTriggerTuple(script, triggerFactory.GetTriggerFromAddress(address)));
                                        processed.Add(address);
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    foreach (Nwn2Address p in processed)
                    {
                        areaScripts.Remove(p);                                                      // has been added, so don't check for it more than once
                    }
                    session.CloseArea(area);
                }
            }

            return(scripts);
        }