예제 #1
0
 protected void Watch(NWN2GameConversation conversation)
 {
     if (conversation != null)
     {
         conversation.NameChanged += delegate(object oObject, NameChangedEventArgs eArgs) { OnConversationNameChanged(oObject, eArgs); };
     }
 }
예제 #2
0
        public void AddConditionToConversationLine(NWN2ConversationConnector line, NWN2GameConversation conversation)
        {
            if (line == null)
            {
                throw new ArgumentNullException("line");
            }
            if (conversation == null)
            {
                throw new ArgumentNullException("conversation");
            }
            if (!conversation.AllConnectors.Contains(line))
            {
                throw new ArgumentException("Line is not a part of the given conversation.", "line");
            }

            LaunchFlip();

            bool openingExistingScript = ScriptHelper.HasFlipScriptAttachedAsCondition(line);

            if (openingExistingScript && window.AskWhetherToSaveCurrentScript() == MessageBoxResult.Cancel)
            {
                return;
            }

            window.ConditionalFrame.Address = addressFactory.GetConversationAddress(conversation.Name, line.Line.LineGuid, ScriptType.Conditional).Value;

            if (openingExistingScript)
            {
                NWN2GameScript script = new NWN2GameScript(line.Conditions[0].Script);
                script.Demand();
                FlipScript flipScript = scriptHelper.GetFlipScript(script, Attachment.Ignore);

                window.OpenFlipScript(new ScriptTriggerTuple(flipScript, null));
                window.ConditionalFrame.Dialogue = Nwn2Strings.GetStringFromOEIString(line.Line.Text);

                //ActivityLog.Write(new Activity("OpenedScript","ScriptName",script.Name,"Event",String.Empty));
                Log.WriteAction(LogAction.opened, "script", script.Name + "(attached as condition to line '" + line.Line.Text.GetSafeString(OEIShared.Utils.BWLanguages.CurrentLanguage) + "')");
            }

            else
            {
                window.IsDirty = true;

                window.EnterConditionMode();
                window.ConditionalFrame.Dialogue = Nwn2Strings.GetStringFromOEIString(line.Line.Text);

                //ActivityLog.Write(new Activity("NewScript","CreatedVia","AddingConditionToConversationLine","Event",String.Empty));
                string lineText;
                try {
                    lineText = line.Line.Text.GetSafeString(OEIShared.Utils.BWLanguages.CurrentLanguage).Value;
                }
                catch (Exception) {
                    lineText = String.Empty;
                }
                Log.WriteAction(LogAction.added, "script", "as condition to a line of conversation ('" + lineText + "')");
            }
        }
예제 #3
0
        public void UseConversationLineAsTrigger(NWN2ConversationConnector line, NWN2GameConversation conversation)
        {
            if (line == null)
            {
                throw new ArgumentNullException("line");
            }
            if (conversation == null)
            {
                throw new ArgumentNullException("conversation");
            }
            if (!conversation.AllConnectors.Contains(line))
            {
                throw new ArgumentException("Line is not a part of the given conversation.", "line");
            }

            LaunchFlip();

            window.LeaveConditionMode();

            bool openingExistingScript = ScriptHelper.HasFlipScriptAttachedAsAction(line);

            if (openingExistingScript && window.AskWhetherToSaveCurrentScript() == MessageBoxResult.Cancel)
            {
                return;
            }

            TriggerControl trigger = triggers.GetTrigger(line, conversation);

            if (openingExistingScript)
            {
                NWN2GameScript script = new NWN2GameScript(line.Actions[0].Script);
                script.Demand();
                FlipScript flipScript = scriptHelper.GetFlipScript(script, Attachment.Ignore);

                window.OpenFlipScript(new ScriptTriggerTuple(flipScript, trigger));

                //ActivityLog.Write(new Activity("OpenedScript","ScriptName",script.Name,"Event",trigger.GetLogText()));
                Log.WriteAction(LogAction.opened, "script", script.Name + " (attached to line '" + line.Line.Text.GetSafeString(OEIShared.Utils.BWLanguages.CurrentLanguage) + "')");
            }

            else
            {
                window.SetTrigger(trigger);
                window.IsDirty = true;

                //ActivityLog.Write(new Activity("NewScript","CreatedVia","UsingConversationLineAsEvent","Event",trigger.GetLogText()));
                string lineText;
                try {
                    lineText = line.Line.Text.GetSafeString(OEIShared.Utils.BWLanguages.CurrentLanguage).Value;
                }
                catch (Exception) {
                    lineText = String.Empty;
                }
                Log.WriteAction(LogAction.added, "script", "to a line of conversation ('" + lineText + "')");
            }
        }
예제 #4
0
        public TriggerControl GetTriggerFromAddress(Nwn2ConversationAddress address)
        {
            if (address == null)
            {
                throw new ArgumentNullException("address");
            }

            if (address.AttachedAs == Sussex.Flip.Core.ScriptType.Conditional)
            {
                return(null);
            }

            NWN2GameModule mod = NWN2Toolset.NWN2ToolsetMainForm.App.Module;

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

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

            if (conversation == null)
            {
                throw new ArgumentException("Could not find conversation '" + address.Conversation + "' in this module.", "conversation");
            }

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

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

            if (line == null)
            {
                throw new ArgumentException("Could not find a line with the given ID in conversation '" + address.Conversation + "'.", "conversation");
            }

            return(new DialogueWasSpoken(line.OwningConnector, conversation));
        }
예제 #5
0
 /// <summary>
 /// Constructs a new <see cref="Sussex.Flip.Games.NeverwinterNightsTwo.Utils.ConversationEventArgs"/> instance.
 /// </summary>
 /// <param name="conversation">The conversation relating to this event.</param>
 public ConversationEventArgs(NWN2GameConversation conversation)
 {
     this.conversation = conversation;
 }
예제 #6
0
 public DialogueWasSpoken(NWN2ConversationConnector line, NWN2GameConversation conversation) : this(line.Line.Text.GetSafeString(BWLanguages.CurrentLanguage).Value,
                                                                                                    conversation.Name,
                                                                                                    line.Line.LineGuid)
 {
 }
예제 #7
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);
        }
예제 #8
0
 public TriggerControl GetTrigger(NWN2ConversationConnector line, NWN2GameConversation conversation)
 {
     return(new DialogueWasSpoken(line, conversation));
 }
예제 #9
0
        /// <summary>
        /// If there already exists a conversation by the name in the module, then it is fetched, otherwise a new is created
        /// </summary>
        /// <param name="questName">The name of the quset</param>
        /// <param name="gender">The gender which will be used in the quest</param>
        /// <param name="lang">The spoken (real world) language</param>
        /// <returns>The conversation</returns>
        private NWN2GameConversation conversationFixer(string questName, BWLanguages.Gender gender, BWLanguages.BWLanguage lang)
        {
            String convName = String.Empty;
            NWN2GameConversation cConversation = null;

            /* If the actor is a creature and does not yet belong to a faction,
             * I set it to be a commoner.
             */
            #region factionSet
            if (actor.type == EnumTypes.actorType.Creature)
                {
                if (actor.boolInstance)
                    {
                    NWN2CreatureInstance inst = (NWN2CreatureInstance)actor.instance;
                    if (inst.FactionID < 0 || inst.FactionID > 12)
                        {
                        inst.FactionID = 2;
                        }
                    }
                else
                    {
                    NWN2CreatureBlueprint blue = (NWN2CreatureBlueprint)actor.blueprint;
                    if (blue.FactionID < 0 || blue.FactionID > 12)
                        {
                        blue.FactionID = 2;
                        }
                    }
                }
            #endregion

            #region getConversationName
            if (actor.Conversation != null && System.IO.Path.GetFileNameWithoutExtension(actor.Conversation.FullName) != String.Empty)
                {
                // I get the name of what the conversation is/should be called
                convName = System.IO.Path.GetFileNameWithoutExtension(actor.Conversation.FullName);
                }
            else if (trigger != null)
                {
                convName = trigger.ToString() + "Conv";
                }
            else
                {
                convName = questNamePrep(questName) + "_" + actor.ToString().Replace(" ", "");
                }
            cConversation = module.Conversations[convName];
            #endregion

            #region ensureConversation
            // If we still have no conversation, then we create one
            if (cConversation == null)
                {
                cConversation = new NWN2GameConversation(convName, module.Repository.DirectoryName, module.Repository);
                cConversation.Demand();
                }
            else
                {
                cConversation.Demand();
                // if we have a conversation, and we have not cleaned it yet - then we do so now, and makes
                // sure that no one else cleans it
                if (alreadyWiped[cConversation.Name] == null)
                    {
                    alreadyWiped[cConversation.Name] = true;

                    NWN2ConversationConnectorCollection connectors = cConversation.StartingList;
                    LinkedList<NWN2ConversationConnector> removeList = new LinkedList<NWN2ConversationConnector>();

                    foreach (NWN2ConversationConnector connnect in connectors)
                        {
                        if (connnect.Comment.Contains("pluginGenerated: " + questName + ":" + questId.ToString()))
                            {
                            removeList.AddLast(connnect);
                            }
                        }

                    debug("Number of convs to remove: " + removeList.Count);
                    foreach (NWN2ConversationConnector removeConnect in removeList)
                        {
                        debug("Removed conversation: " + removeConnect.Text[lang]);
                        cConversation.RemoveNode(removeConnect);
                        }
                    }
                }
            cConversation.OEISerialize(true);
            cConversation.NWN1StyleDialogue = true;
            #endregion
            cConversation = constructConv(cConversation, questName, gender, lang);
            #region FixDoorTalk
            if (actor.type == EnumTypes.actorType.Placeable || actor.type == EnumTypes.actorType.Door)
                {
                NWN2GameScript talkScript = module.Scripts["ga_door_talk"];
                if (talkScript == null)
                    {
                    talkScript = new NWN2GameScript("ga_door_talk", module.Repository.DirectoryName, module.Repository);
                    talkScript.Data = Properties.Resources.ga_door_talk;
                    talkScript.OEISerialize();
                    module.Scripts.Add(talkScript);
                    }
                actor.doorTalk = talkScript.Resource;
                }
            #endregion
            if (triggerHappens != convType.Explore)
                actor.Conversation = cConversation.Resource;
            return cConversation;
        }
예제 #10
0
        /// <summary>
        /// The method that makes sure the correct scripts and conditionas are set on the conversation
        /// </summary>
        /// <param name="cConversation">The conversation</param>
        /// <param name="questName">The name of the quset</param>
        /// <param name="gender">The gender which will be used in the quest</param>
        /// <param name="lang">The spoken (real world) language</param>
        /// <returns>The conversation</returns>
        private NWN2GameConversation constructConv(NWN2GameConversation cConversation, String questName, BWLanguages.Gender gender, BWLanguages.BWLanguage lang)
        {
            // Done in order to avoid a side condition
            int value = (questId == 0) ? 1 : questId;
            /*
            if (happensEnum == EnumTypes.happens.Trigger && triggerHappens == convType.Explore)
                {
                var tempConv = cConversation.InsertChild(null);
                tempConv.Text.SetString(String.Empty, lang, gender);
                tempConv.Speaker = trigger.Tag;
                tempConv.Comment = "pluginGenerated:" + value;
                tempConv.ShowOnce = NWN2ConversationShowOnceType.OncePerModule;
            //                cConversation.InsertChild(tempConv);
                return cConversation;
                }
            */
            // I add it to null to indicate that this will be at the root
            NWN2ConversationConnector conv = cConversation.InsertChild(null);
            // I set the comments so that it later can be deleted (if you choose to recreate the quest)
            conv.Comment = "pluginGenerated: " + questName + ":" + questId.ToString();

            // I begin the conversation
            debug("Begin conversation");
            conv.Text.SetString(greeting, lang, gender);
            // I make sure it is only fired once if we are talking escort/exploration

            NWN2ConversationConnector accept;
            NWN2ConversationConnector quest;
            NWN2ConversationConnector reject;

            #region Conditions
            // if this requires a node to fire, then we add the requirement here
            if (// If there is a prerequisite
                preReq != EnumTypes.prereq.NoPrereq
                || // or if we are exploring or escorting
                happensEnum == EnumTypes.happens.Trigger
                //&& (convHappens == convType.Escort || convHappens == convType.Explore)
                )
                {
                debug("conditional");
                conv.Conditions.Add(conditional(questName));
                if (happensEnum == EnumTypes.happens.Trigger || convHappens != convType.None)
                    {
                    // It must be inserted as the first thing
                    conv.Conditions.Insert(0, node());
                    }
                }

            // Once the offer has been accepted it should not appear again
            debug("makeJournal");
            conv.Conditions.Add(makeJournalCheck(questName, "<" + value));
            #endregion

            // If this is only a single comment I add the journal entry - if there is one (or we are opening a door)
            if (happensEnum == EnumTypes.happens.Trigger || happensEnum == EnumTypes.happens.OpenDoor ||
                (convEnum == EnumTypes.conv.Single &&
                /* since I have made sure that the villian only can call this if he is actually talking,
                 we only need to make sure that we are doing something
                 */
                happensEnum != EnumTypes.happens.None))
                {
                debug("setConvValues");
                setConvValues(ref conv, ref conv, questName);
                /* If we are not dealing with a villain, then this
                 is needed to make quest updates fire otherwise any quest update will not fire */
                if (happensEnum != EnumTypes.happens.Conflict)
                    cConversation.InsertChild(conv);
                }
            else
                #region Quest
                if (convEnum == EnumTypes.conv.QuestInfo && happensEnum != EnumTypes.happens.Trigger && happensEnum != EnumTypes.happens.None)
                    {
                    // The player accepts
                    accept = cConversation.InsertChild(conv);
                    accept.Text.SetString(acceptence, lang, gender);

                    // The quest giver responce
                    quest = cConversation.InsertChild(accept);
                    quest.Text.SetString(action, lang, gender);

                    setConvValues(ref accept, ref quest, questName);

                    // The player declines
                    reject = cConversation.InsertChild(conv);
                    reject.Text.SetString(rejection, lang, gender);
                    }
                #endregion
            return cConversation;
        }
예제 #11
0
        protected void WatchModule(NWN2GameModule mod)
        {
            /* Only tracking blueprints which are added to and removed from the module...
             * this is correct for our purposes! Narrative Threads only uses the module blueprint collections. */

            if (mod != null)
            {
                /* There seems to be a bug where the following events events fire at a later stage... they do
                * fire when they should, but when the paused test is allowed to complete, they fire again. */
                foreach (NWN2BlueprintCollection bc in mod.BlueprintCollections)
                {
                    bc.Inserted += delegate(OEICollectionWithEvents cList, int index, object value)
                    {
                        OnBlueprintAdded(bc, new BlueprintEventArgs((INWN2Blueprint)value));
                    };

                    bc.Removed += delegate(OEICollectionWithEvents cList, int index, object value)
                    {
                        OnBlueprintRemoved(bc, new BlueprintEventArgs((INWN2Blueprint)value));
                    };
                }

                List <OEIDictionaryWithEvents> dictionaries;
                dictionaries = new List <OEIDictionaryWithEvents> {
                    mod.Areas, mod.Conversations, mod.Scripts
                };

                OEIDictionaryWithEvents.ChangeHandler dAdded   = new OEIDictionaryWithEvents.ChangeHandler(ResourceInsertedIntoCollection);
                OEIDictionaryWithEvents.ChangeHandler dRemoved = new OEIDictionaryWithEvents.ChangeHandler(ResourceRemovedFromCollection);
                foreach (OEIDictionaryWithEvents dictionary in dictionaries)
                {
                    dictionary.Inserted += dAdded;
                    dictionary.Removed  += dRemoved;
                }

                // Watch for changes to the names of areas, conversations and scripts:
                foreach (NWN2GameArea area in mod.Areas)
                {
                    Watch(area);
                }
                foreach (NWN2GameConversation conversation in mod.Conversations)
                {
                    Watch(conversation);
                }
                foreach (NWN2GameScript script in mod.Scripts)
                {
                    Watch(script);
                }

                mod.Areas.Inserted += delegate(OEIDictionaryWithEvents cDictionary, object key, object value)
                {
                    NWN2GameArea area = value as NWN2GameArea;
                    if (area != null)
                    {
                        Watch(area);
                    }
                };

                mod.Conversations.Inserted += delegate(OEIDictionaryWithEvents cDictionary, object key, object value)
                {
                    NWN2GameConversation conversation = value as NWN2GameConversation;
                    if (conversation != null)
                    {
                        Watch(conversation);
                    }
                };

                mod.Scripts.Inserted += delegate(OEIDictionaryWithEvents cDictionary, object key, object value)
                {
                    NWN2GameScript script = value as NWN2GameScript;
                    if (script != null)
                    {
                        Watch(script);
                    }
                };
            }
        }
예제 #12
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);
        }
예제 #13
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);
        }