private bool CollisionCheck(Module newModule, ModuleConnector exit)
    {
        var bounds = newModule.GetComponentInChildren <Collider>().bounds;
        //Make an overlap sphere to get all the nearby Modules
        var radius = Mathf.Max(bounds.size.x, bounds.size.z) * 4.0f;

        //var drawRadius = Mathf.Max(bounds.size.x, bounds.size.z) * 0.5f;
        //DebugDraw.DrawSphere(bounds.center, drawRadius, new Color(0f, .3f, .8f));
        Collider[] hitColliders = Physics.OverlapSphere(bounds.center, radius);

        var fatherObject = newModule.BaseModuleConnector.transform.parent.gameObject;

        //Debug.Log(newModule.gameObject + ": father: " + fatherObject);

        foreach (Collider c in hitColliders)
        {
            var possibleColliderObject = c.transform.parent.gameObject;
            if (possibleColliderObject.tag != "Module" || possibleColliderObject == fatherObject || possibleColliderObject == newModule.gameObject)
            {
                continue;
            }

            //Debug.Log(newModule.gameObject + ": possible collider: " + possibleColliderObject);
            if (bounds.Intersects(c.bounds))
            {
                //Debug.Log("Collision failed with : " + c.gameObject);
                return(false);
            }
        }

        return(true);
    }
Beispiel #2
0
    private GameObject GetRandomModuleExcluding(ModuleConnector _connector, List <string> _excludedCodes)
    {
        bool foundModule = false;

        if (_connector == null)
        {
        }
        int  useModId = 0;
        bool excluded = false;
        int  tries    = 1;

        for (int i = 0; i < generationRules.moduleRules.Count; i++)
        {
            if (_connector.parentModule.moduleCode == generationRules.moduleRules[i].moduleCode)
            {
                for (int c = 0; c < generationRules.moduleRules[i].bannedCodesArray.Length; c++)
                {
                    _excludedCodes.Add(generationRules.moduleRules[i].bannedCodesArray[c]);
                }
            }
        }
        while (!foundModule && tries <= _excludedCodes.Count)
        {
            int random = Random.Range(0, m_totalRarity);
            for (int i = 0; i < loadedModules.Length; i++)
            {
                excluded = false;
                if (!foundModule)
                {
                    foreach (string code in _excludedCodes)
                    {
                        if (loadedModules[i].moduleCode == code)
                        {
                            excluded = true;
                        }
                    }
                    if (excluded)
                    {
                    }
                    else if (loadedModules[i].unique)
                    {
                    }
                    else if (random >= loadedModules[i].GetMinRarity() && random <= loadedModules[i].GetMaxRarity())
                    {
                        useModId    = i;
                        foundModule = true;
                    }
                }
            }
            tries++;
        }
        if (!foundModule)
        {
            return(GetSpecificModule("straight"));
        }

        return(loadedModules[useModId].gameObject);
    }
Beispiel #3
0
    private void SetCloseBlock(ModuleConnector CloseConnector, int numberForName)
    {
        var CloseModule1 = (Module)Instantiate(_CloseModule, MainGameObject.transform);

        CloseModule1.name = CloseModule1.name + "_" + numberForName;
        var CloseModule1Exits = CloseModule1.GetExits();
        var Closeexit1ToMatch = CloseModule1Exits.FirstOrDefault(x => x.IsDefault) ?? GetRandom(CloseModule1Exits);

        MatchExits(CloseConnector, Closeexit1ToMatch);
    }
Beispiel #4
0
    private void MatchExits(ModuleConnector oldExit, ModuleConnector newExit)
    {
        var newModule            = newExit.transform.parent;
        var forwardVectorToMatch = -oldExit.transform.forward;
        var correctiveRotation   = Azimuth(forwardVectorToMatch) - Azimuth(newExit.transform.forward);

        newModule.RotateAround(newExit.transform.position, Vector3.up, correctiveRotation);
        var correctiveTranslation = oldExit.transform.position - newExit.transform.position;

        newModule.transform.position += correctiveTranslation;
    }
 private void DyeModule(ModuleConnector pendingExit, Module newModule)
 {
     if (pendingExit.transform.parent.gameObject.GetComponent <Module>().Tags[0] == "room")                     // if the module of the current pending exit is a room
     {
         newModule.GetComponent <SpriteRenderer>().color = new Color(1f, 0f, 0f);                               //set the new module corridor to red
     }
     else if (newModule.gameObject.GetComponent <Module>().Tags[0] == "room")                                   // if the new module is a room
     {
         pendingExit.transform.parent.gameObject.GetComponent <SpriteRenderer>().color = new Color(1f, 0f, 0f); //set current corridor to red
     }
 }
Beispiel #6
0
    private void AlignConnectors(ModuleConnector oldExit, ModuleConnector newExit)
    {
        Transform newModule            = newExit.parentModule.gameObject.transform;
        var       forwardVectorToMatch = -oldExit.transformPoint.forward;
        var       correctiveRotation   = Azimuth(forwardVectorToMatch) - Azimuth(newExit.transformPoint.forward);

        newModule.RotateAround(newExit.transformPoint.position, Vector3.up, correctiveRotation);
        var correctiveTranslation = oldExit.transformPoint.position - newExit.transformPoint.position;

        newModule.transform.position += correctiveTranslation;
    }
    private void MatchExits(ModuleConnector oldExit, ModuleConnector newExit) //I did not change name of the variables, but I am using
                                                                              //right instead of forward
    {
        var newModule            = newExit.transform.parent;
        var forwardVectorToMatch = -oldExit.transform.right;                                         //get opposite as old exit's orientation
        var correctiveRotation   = Azimuth(forwardVectorToMatch) - Azimuth(newExit.transform.right); //use orientations to calculate angle needed

        newModule.RotateAround(newExit.transform.position, Vector3.forward, correctiveRotation);     //rotate
        var correctiveTranslation = oldExit.transform.position - newExit.transform.position;         //vector to move

        newModule.transform.position += correctiveTranslation;
    }
 private void MatchExits(ModuleConnector oldExit, ModuleConnector newExit)
 {
     try {
         var newModule            = newExit.transform.parent;
         var forwardVectorToMatch = -oldExit.transform.forward;
         var correctiveRotation   = Helper.Azimuth(forwardVectorToMatch) - Helper.Azimuth(newExit.transform.forward);
         newModule.RotateAround(newExit.transform.position, Vector3.up, correctiveRotation);
         var correctiveTranslation = oldExit.transform.position - newExit.transform.position;
         newModule.transform.position += correctiveTranslation;
     } catch (MissingReferenceException e) {
         Debug.LogError("Missing Ref catched: " + e.Message);
     }
 }
    private void SealExitWithADoor(ModuleConnector baseExit)
    {
        //Debug.Log("Couldn't find any possible combination. Sealing off the exit with a door");
        var newModule = ProBuilder.Instantiate(DoorPrefab.gameObject, Vector3.zero, Quaternion.identity).GetComponent <Module>();

        newModule.transform.parent = DungeonGameObject.transform;
        var doorExit = newModule.GetExits()[0];

        MatchExits(baseExit, doorExit);

        baseExit.ConnectWith(doorExit);
        doorExit.ConnectWith(baseExit);
    }
    private void MatchExits(ModuleConnector oldExit, ModuleConnector newExit)
    {
        var newModule            = newExit.transform.parent;
        var forwardVectorToMatch = -oldExit.transform.forward;
        //corr z & y axis rot
        var correctiveRotation = Azimuth(forwardVectorToMatch) - Azimuth(newExit.transform.forward);

        newModule.RotateAround(newExit.transform.position, Vector3.up, correctiveRotation);
        //get the trans required for exit to meet
        var correctiveTranslation = oldExit.transform.position - newExit.transform.position;

        //move it so they meet
        newModule.transform.position += correctiveTranslation;
    }
    private void buildDeadendOutOfCurrentRoom(ModuleConnector currentModuleConnector)
    {
        Module moduleToChange = currentModuleConnector.transform.parent.GetComponent <Module>();
        var    exitsToMatch   = moduleToChange.GetExits().Where(e => e.IsMatched()).ToArray();
        var    exitToMatch    = Helper.GetRandom <ModuleConnector>(exitsToMatch);
        bool   matched        = FindMatchingModuleWithExits(exitsToMatch.Count(), exitToMatch.getOtherSide(), moduleToChange);

        if (matched)
        {
            moduleToChange.gameObject.SetActive(false);
            //Destroy(moduleToChange.gameObject);
        }
        else
        {
            Debug.LogError("No DeadendMatch!");
        }
    }
Beispiel #12
0
 private void LinkModules(ModuleConnector _a, ModuleConnector _b)
 {
     if (_a != null && _b != null)
     {
         _a.UniqueId       = StaticMethods.GetUniqueInt();
         _b.UniqueId       = StaticMethods.GetUniqueInt();
         _a.linkedModule   = _b.parentModule;
         _b.linkedModule   = _a.parentModule;
         _a.LinkedUniqueId = _b.UniqueId;
         _b.LinkedUniqueId = _a.UniqueId;
         Debug.LogWarning("LINKED MODULES : " + _a.UniqueId + ", " + _b.UniqueId);
     }
     else
     {
         Debug.LogWarning("COULD NOT LINK MODULES : " + _a.UniqueId + ", " + _b.UniqueId);
     }
 }
    private bool checkIfExitsFitDirectly(ModuleConnector currentModuleConnector, Module collidingModule)
    {
        var possibleExits = collidingModule.GetExits();

        foreach (ModuleConnector exit in possibleExits)
        {
            if (exit.transform.position.Equals(currentModuleConnector.transform.position))
            {
                exit.setOtherSide(currentModuleConnector);
                currentModuleConnector.setOtherSide(exit);
                exit.SetMatched(true);
                currentModuleConnector.SetMatched(true);
                return(true);
            }
        }
        return(false);
    }
    private void BuildPathEndings()
    {
        while (pendingExits.Count() > 0)
        {
            var pendingExit = pendingExits.First();
            if (pendingExit.gameObject.activeSelf && pendingExit.transform.parent.gameObject.activeSelf)
            {
                Module newModulePrefab = GetRandomMatchingTile(pendingExit, true);
                var    newModule       = (Module)Instantiate(newModulePrefab);
                newModule.gameObject.name = "Endroom " + CurrentRooms;
                ModuleConnector exitToMatch = GetRandomExitWithTag(newModule, pendingExit.GetComponentInParent <Module>().tags);
                MatchExits(pendingExit, exitToMatch);

                EndRoomCollisionHandling(newModule, pendingExit);
            }
            pendingExits = pendingExits.Where(e => (!e.IsMatched() || e.getOtherSide() == null) && e.transform.parent.gameObject.activeSelf).ToList();
        }
    }
    private Module GetRandomMatchingTile(ModuleConnector mainExit, bool deadendNeeded)
    {
        //module tags match at least one exittag and have an exit that matches the current module and modules that match deadendneeded
        Debug.Log("MainExit " + mainExit.tag + " of tile " + mainExit.transform.parent.name);
        var possibleModules = Modules.Where(e => e.hasTag(mainExit.tags) &&
                                            (e.tags & mainExit.tags) != TileTagsEnum.DeadEnd &&
                                            e.GetComponentsInChildren <ModuleConnector>().
                                            Where(d => d.hasTag(mainExit.GetComponentInParent <Module>().tags) && (d.tags & mainExit.GetComponentInParent <Module>().tags) != TileTagsEnum.DeadEnd).Count() > 0 &&
                                            e.hasTag(TileTagsEnum.DeadEnd) == deadendNeeded);

        if (possibleModules.Count() > 0)
        {
            return(Helper.GetRandom <Module>(possibleModules.ToArray()));
        }
        else
        {
            return(Helper.GetRandom <Module>(Modules.Where(e => e.hasTag(FALLBACK_TAG) && !e.hasTag(TileTagsEnum.DeadEnd)).ToArray()));
        }
    }
    private void BuildBridgeForFinal(Module finalMain)
    {
        var finalMainExit = Helper.GetRandom(finalMain.GetExits().Where(e => !e.IsMatched()).ToArray());

        ModuleConnector bridgeConnector = Instantiate(finalMainExit);

        bridgeConnector.name             = "BridgeConnector";
        bridgeConnector.transform.parent = finalMainExit.transform.parent;
        bridgeConnector.transform.SetPositionAndRotation(finalMainExit.transform.position, finalMainExit.transform.rotation);
        bridgeConnector.tags = TileTagsEnum.Entrance;

        var bridgePrefab = GetRandomMatchingTile(bridgeConnector, false);
        var bridgeModule = (Module)Instantiate(bridgePrefab);

        bridgeModule.gameObject.name = "FinalBridge";
        bridgeConnector.gameObject.SetActive(false);
        var bridgeModuleExitToMatch = GetRandomExitWithTag(bridgeModule, finalMainExit.GetComponentInParent <Module>().tags);

        MatchExits(finalMainExit, bridgeModuleExitToMatch);

        if (CollisionDetection(bridgeModule, finalMainExit.GetComponentInParent <Module>()))
        {
            bridgeModule.gameObject.SetActive(false);
            Debug.Log("Gameobject " + bridgeModule.name + " disabled");
            Destroy(bridgeModule.gameObject);
            bridgeModule = null;

            Destroy(bridgeConnector.gameObject);
            BuildBridgeForFinal(finalMain);
        }
        else
        {
            finalMainExit.SetMatched(true);
            finalMainExit.setOtherSide(bridgeModuleExitToMatch);
            bridgeModuleExitToMatch.SetMatched(true);
            bridgeModuleExitToMatch.setOtherSide(finalMainExit);
            mainPath.Add(bridgeModule);
            bridgeModule.transform.parent = moduleHolder.transform;
            pendingExits.AddRange(finalMain.GetExits().Where(e => !e.IsMatched()));
            CurrentRooms++;
        }
    }
Beispiel #17
0
 private void EnforceSingleEntrance()
 {
     if (m_singleEntranceEnforced)
     {
         return;
     }
     for (int i = 0; i < connectors.Count; i++)
     {
         if (connectors[i].isEntrance)
         {
             if (!m_singleEntranceEnforced)
             {
                 m_entranceConnector = connectors[i];
             }
             else
             {
                 connectors[i].isEntrance = false;
             }
             m_singleEntranceEnforced = true;
         }
     }
     m_singleEntranceEnforced = true;
 }
    private void HandleMovement()
    {
        float h = CrossPlatformInputManager.GetAxis("Horizontal");
        float v = CrossPlatformInputManager.GetAxis("Vertical");

        if (h != 0 || v != 0 || voiceMovement)
        {
            var forwardVectorToMatch = currentModule.transform.forward;
            var camForward           = Vector3.Scale(Camera.main.transform.forward, new Vector3(1, 0, 1)).normalized;
            var correctiveRotation   = Helper.Azimuth(forwardVectorToMatch) - Helper.Azimuth(camForward);
            Debug.Log("RotationTile: " + forwardVectorToMatch + ", Rotation Cam: " + Camera.main.transform.forward + ",Correction: " + correctiveRotation);
            ModuleConnector agentDestinationModuleConnector = null;

            switch (Convert.ToInt32(correctiveRotation))
            {
            case 0:
                Debug.Log("Rotation 0 Case");
                if (h < 0 || voiceDirection == VoiceDirection.LEFT)
                {
                    agentDestinationModuleConnector = Helper.FindComponentInChildWithTag <ModuleConnector>(currentModule.gameObject, "left");
                }
                else if (h > 0 || voiceDirection == VoiceDirection.RIGHT)
                {
                    agentDestinationModuleConnector = Helper.FindComponentInChildWithTag <ModuleConnector>(currentModule.gameObject, "right");
                }
                else if (v < 0 || voiceDirection == VoiceDirection.BACKWARD)
                {
                    agentDestinationModuleConnector = Helper.FindComponentInChildWithTag <ModuleConnector>(currentModule.gameObject, "back");
                }
                else if (v > 0 || voiceDirection == VoiceDirection.FORWARD)
                {
                    agentDestinationModuleConnector = Helper.FindComponentInChildWithTag <ModuleConnector>(currentModule.gameObject, "front");
                }
                break;

            case 90:
                Debug.Log("Rotation 90 Case");
                if (h < 0 || voiceDirection == VoiceDirection.LEFT)
                {
                    agentDestinationModuleConnector = Helper.FindComponentInChildWithTag <ModuleConnector>(currentModule.gameObject, "back");
                }
                else if (h > 0 || voiceDirection == VoiceDirection.RIGHT)
                {
                    agentDestinationModuleConnector = Helper.FindComponentInChildWithTag <ModuleConnector>(currentModule.gameObject, "front");
                }
                else if (v < 0 || voiceDirection == VoiceDirection.BACKWARD)
                {
                    agentDestinationModuleConnector = Helper.FindComponentInChildWithTag <ModuleConnector>(currentModule.gameObject, "right");
                }
                else if (v > 0 || voiceDirection == VoiceDirection.FORWARD)
                {
                    agentDestinationModuleConnector = Helper.FindComponentInChildWithTag <ModuleConnector>(currentModule.gameObject, "left");
                }
                break;

            case -90:
                Debug.Log("Rotation -90 Case");
                if (h < 0 || voiceDirection == VoiceDirection.LEFT)
                {
                    agentDestinationModuleConnector = Helper.FindComponentInChildWithTag <ModuleConnector>(currentModule.gameObject, "front");
                }
                else if (h > 0 || voiceDirection == VoiceDirection.RIGHT)
                {
                    agentDestinationModuleConnector = Helper.FindComponentInChildWithTag <ModuleConnector>(currentModule.gameObject, "back");
                }
                else if (v < 0 || voiceDirection == VoiceDirection.BACKWARD)
                {
                    agentDestinationModuleConnector = Helper.FindComponentInChildWithTag <ModuleConnector>(currentModule.gameObject, "left");
                }
                else if (v > 0 || voiceDirection == VoiceDirection.FORWARD)
                {
                    agentDestinationModuleConnector = Helper.FindComponentInChildWithTag <ModuleConnector>(currentModule.gameObject, "right");
                }
                break;

            case 180:
                Debug.Log("Rotation 180 Case");
                if (h < 0 || voiceDirection == VoiceDirection.LEFT)
                {
                    agentDestinationModuleConnector = Helper.FindComponentInChildWithTag <ModuleConnector>(currentModule.gameObject, "right");
                }
                else if (h > 0 || voiceDirection == VoiceDirection.RIGHT)
                {
                    agentDestinationModuleConnector = Helper.FindComponentInChildWithTag <ModuleConnector>(currentModule.gameObject, "left");
                }
                else if (v < 0 || voiceDirection == VoiceDirection.BACKWARD)
                {
                    agentDestinationModuleConnector = Helper.FindComponentInChildWithTag <ModuleConnector>(currentModule.gameObject, "front");
                }
                else if (v > 0 || voiceDirection == VoiceDirection.FORWARD)
                {
                    agentDestinationModuleConnector = Helper.FindComponentInChildWithTag <ModuleConnector>(currentModule.gameObject, "back");
                }
                break;

            default:
                Debug.Log("no matching rotation for movement: " + Convert.ToInt32(correctiveRotation));
                break;
            }
            if (agentDestinationModuleConnector != null && agentDestinationModuleConnector.getOtherSide() != null || voiceMovement)
            {
                voiceMovement  = false;
                voiceDirection = VoiceDirection.NONE;
                agent.SetTarget(Helper.FindComponentInChildWithTag <Transform>(agentDestinationModuleConnector.getOtherSide().GetComponentInParent <Module>().gameObject, "movePoint").transform);
            }
        }
    }
    /**
     * The only scenario where CreateNewModule would return false, is if there was no way to generate a module, so we have to seal it off with a door
     */
    private bool CreateNewModule(ModuleConnector baseExit, List <GameObject> availableModulePrefabs, List <ModuleConnector> newExits, out GameObject moduleGameObject)
    {
        bool            foundExit     = false;
        bool            foundModule   = false;
        ModuleConnector newModuleExit = null;

        ModuleConnector[] newModuleExits = null;
        moduleGameObject = null;
        Module newModule = null;

        foreach (var newModulePrefab in availableModulePrefabs)
        {
            //Create the new module prefab
            newModule = ProBuilder.Instantiate(newModulePrefab, Vector3.zero, Quaternion.identity).GetComponent <Module>();
            newModule.transform.parent = DungeonGameObject.transform;
            newModuleExits             = newModule.GetExits();
            Util.ShuffleArray(newModuleExits);

            for (var i = 0; i < newModuleExits.Count(); i++)
            {
                newModuleExit = newModuleExits[i];

                //Match the exits
                MatchExits(baseExit, newModuleExit);

                //Letting a full frame go by so we can do a collision check
                if (CollisionCheck(newModule, baseExit))
                {
                    foundModule = true;
                    foundExit   = true;
                    break;
                }
            }

            //We've tried every exit combination with this module, get a new module
            if (!foundExit)
            {
                Destroy(newModule.gameObject);
                continue;
            }

            //if we've reached here, we have found a suitable exit with a suitable module, or we have not found anything suitable.
            break;
        }

        //We haven't found anything useful. Just make a door, and find another baseModuleExit
        if (!foundModule)
        {
            return(false);
        }

        //the new module was received. All is good. Connect with the base module exit. Find another baseModuleExit to connect with
        baseExit.ConnectWith(newModuleExit);
        newModuleExit.ConnectWith(baseExit);

        if (newExits != null)
        {
            newExits.AddRange(newModuleExits.Where(e => e != newModuleExit));
        }

        CameraPortal cameraPortal = (CameraPortal)newModule.gameObject.GetComponentInChildren(typeof(CameraPortal));

        if (cameraPortal != null)
        {
            Portals.Add(cameraPortal);
        }

        moduleGameObject = newModule.gameObject;
        return(true);
    }
Beispiel #20
0
    private RoomModule TrySpawnRandomModule(ModuleConnector _connector)
    {
        m_roomTry = 0;
        List <string> excludedCodes = new List <string>();

        foreach (RoomModule mod in loadedModules)
        {
            bool excluded = true;
            foreach (string code in _connector.allowedCodesArray)
            {
                if (mod.moduleCode == code)
                {
                    excluded = false;
                }
            }
            if (excluded)
            {
                excludedCodes.Add(mod.moduleCode);
            }
        }
        List <string> remainingCodes = new List <string>(_connector.allowedCodesArray);

        RoomModule newModule = GameObject.Instantiate(GetRandomModuleExcluding(_connector, excludedCodes), transform).GetComponent <RoomModule>();

        bool ready = false;

        while (!ready && remainingCodes.Count >= 1 && m_roomTry <= loadedModules.Length)
        {
            if (newModule.gameObject != null)
            {
                Destroy(newModule.gameObject);
            }
            newModule = GameObject.Instantiate(GetRandomModuleExcluding(_connector, excludedCodes), transform).GetComponent <RoomModule>();
            AlignConnectors(_connector, newModule.GetEntrance());
            if (TestSafeBox(newModule))
            {
                //  MODULE IS GOOD TO GO, SET IT UP
                m_roomTry      = 0;
                remainingCodes = new List <string>();
                ready          = true;
            }
            else
            {
                //  MODULE DOESNT FIT, DESTROY IT
                remainingCodes.Remove(newModule.moduleCode);
                excludedCodes.Add(newModule.moduleCode);
                Destroy(newModule.gameObject);
                m_roomTry++;
            }
        }

        if (!ready)
        {
            newModule = GameObject.Instantiate(nullModule, transform).GetComponent <RoomModule>();
            AlignConnectors(_connector, newModule.GetEntrance());
        }
        LinkModules(_connector, newModule.GetEntrance());
        newModule.SetId(m_roomCount);
        newModule.gameObject.name = ("Room " + m_roomCount + " : " + newModule.moduleCode);

        newModule.gameObject.SetActive(true);
        m_spawnedModules.Add(newModule);
        m_roomCount++;

        m_pendingConnections.RemoveAt(0);

        foreach (ModuleConnector con in newModule.GetExits())
        {
            m_pendingConnections.Add(con);
        }
        m_pendingConnections.Remove(newModule.GetEntrance());

        return(newModule);
    }
Beispiel #21
0
 private GameObject GetRandomModule(ModuleConnector _connector)
 {
     return(GetRandomModuleExcluding(_connector, new List <string>()));
 }
 public void ConnectWith(ModuleConnector neighborConnection)
 {
     NeighborConnection = neighborConnection;
 }
Beispiel #23
0
    private void StartCreate()
    {
        DataBoundsList = new List <DataStruct>();
        var startModule = (Module)Instantiate(_StartModule, transform.position, transform.rotation, MainGameObject.transform);

        AddBound(startModule.GetComponent <BoxCollider>().bounds, startModule.name);
        var pendingExits = new List <ModuleConnector>(startModule.GetExits());
        List <ModuleConnector> globalExits = new List <ModuleConnector>(pendingExits);

        int i = 0;

        for (int iteration = 0; iteration < _Iterations; iteration++)
        {
            var newExits = new List <ModuleConnector>();
            foreach (var pendingExit in pendingExits)
            {
                //ModuleConnector lastconnector = new ModuleConnector();
                bool          found           = false;
                List <string> pendingExitList = pendingExit.Tags.ToList();
                while (pendingExitList.Count > 0 && !found)
                {
                    found = false;
                    string        newTag        = GetRandom(pendingExitList);
                    List <Module> modulesForTag = _Modules.Where(m => m.Tags.Contains(newTag)).ToList();
                    while (modulesForTag.Count > 0 && !found)
                    {
                        Module newModulePref = GetRandom(modulesForTag);
                        Module newModule     = (Module)Instantiate(newModulePref, MainGameObject.transform);
                        newModule.name = newModule.name + "_" + ++i;
                        List <ModuleConnector> connectorsInModule = newModule.GetExits().ToList();
                        while (connectorsInModule.Count > 0 && !found)
                        {
                            ModuleConnector connector = connectorsInModule.FirstOrDefault(x => x.IsDefault) ?? GetRandom(connectorsInModule);
                            MatchExits(pendingExit, connector);
                            if (!checkBoundData(newModule.GetComponent <BoxCollider>().bounds, newModule.name))
                            {
                                Debug.Log("intersect");
                                //if setting fails remove block from random list. TODO :)
                                connectorsInModule.Remove(connector);
                                //when nothing found add to globalexits for block and smoothing
                                //lastconnector = connector;
                            }
                            else
                            {
                                connector.ConnectedConnector   = pendingExit;
                                pendingExit.ConnectedConnector = connector;
                                //remove  pendingExit from global one if fits
                                globalExits.Remove(pendingExit);
                                newExits.AddRange(newModule.GetExits().ToList().Where(e => e != connector));

                                found = true;
                            }
                        }
                        if (!found)
                        {
                            Destroy(newModule.gameObject);
                            modulesForTag.Remove(newModulePref);
                        }
                    }
                    if (!found)
                    {
                        pendingExitList.Remove(newTag);
                    }
                }
            }
            globalExits.AddRange(newExits);
            pendingExits = newExits;
        }


        var           BossModule      = (Module)Instantiate(_BossModule, MainGameObject.transform);
        string        BossModuleName  = BossModule.name;
        var           BossModuleExits = BossModule.GetExits();
        var           BossexitToMatch = BossModuleExits.FirstOrDefault(x => x.IsDefault) ?? GetRandom(BossModuleExits);
        bool          BossRoomSet     = false;
        List <string> SmoothList      = new List <string>(_SmoothModules.ToList());
        bool          removableLeft   = true;

        while (removableLeft)
        {
            removableLeft = false;
            for (int j = 0; j < globalExits.Count; j++)
            {
                ModuleConnector tryExit = globalExits[j];
                i++;
                //Set BossRoom
                if (!BossRoomSet)
                {
                    BossModule.name = BossModuleName + "_" + i;
                    MatchExits(tryExit, BossexitToMatch);
                    if (checkBoundData(BossModule.GetComponent <BoxCollider>().bounds, BossModule.name))
                    {
                        //RemoveGlobalExits.Add(tryExit);
                        BossexitToMatch.ConnectedConnector = tryExit;
                        tryExit.ConnectedConnector         = BossexitToMatch;
                        BossRoomSet = true;
                        globalExits.Remove(tryExit);
                        removableLeft = true;
                        break;
                    }
                }

                //Smooth Blocks
                GameObject    ParentGo         = tryExit.transform.parent.gameObject; //for destroy
                Module        ParentModule     = ParentGo.GetComponent <Module>();
                List <string> ParentModuleTags = ParentModule.Tags.ToList();
                if (ParentModuleTags.Except(SmoothList).ToList().Count <= 0)
                {
                    int                    connectedConnectors = 0;
                    ModuleConnector        newExit             = null;
                    List <ModuleConnector> connectors          = new List <ModuleConnector>(ParentModule.GetExits().ToList());
                    foreach (ModuleConnector mc in connectors)
                    {
                        if (mc != tryExit && mc.ConnectedConnector != null)
                        {
                            connectedConnectors++;
                            newExit = mc.ConnectedConnector;
                        }
                    }
                    if (connectedConnectors == 1)
                    {
                        removableLeft = true;
                        newExit.ConnectedConnector = null;
                        globalExits.RemoveAll(e => connectors.Contains(e));
                        globalExits.Add(newExit);
                        Destroy(ParentGo);
                        break;
                    }
                }
            }
        }

        //Set Close Blocks
        foreach (ModuleConnector tryExit in globalExits)
        {
            SetCloseBlock(tryExit, i++);
        }
    }
    //BUILD PATHS
    private void BuildMainPath()
    {
        while (mainPath.Count() < genParams.mainPathRooms)
        {
            if (LastCount == mainPath.Count())
            {
                timesSameIteration++;
            }
            else
            {
                timesSameIteration = 0;
            }

            if (timesSameIteration >= 5)
            {
                Backtrack(2);

                timesSameIteration = 0;
            }
            LastCount = mainPath.Count();

            var mainExits           = mainPath.Last().GetExits();
            var mainExitToMatch     = Helper.GetRandom(mainPath.Last().GetExits().Where(e => e.IsMatched() != true).ToArray());
            var newMainModulePrefab = GetRandomMatchingTile(mainExitToMatch, false);
            var newMainModule       = (Module)Instantiate(newMainModulePrefab);
            newMainModule.gameObject.name = CurrentRooms + "";
            var newModuleExitToMatch = GetRandomExitWithTag(newMainModule, mainExitToMatch.GetComponentInParent <Module>().tags);
            MatchExits(mainExitToMatch, newModuleExitToMatch);

            if (CollisionDetection(newMainModule, mainExitToMatch.GetComponentInParent <Module>()))
            {
                newMainModule.gameObject.SetActive(false);
                Debug.Log("Gameobject " + newMainModule.name + " disabled");
                Destroy(newMainModule.gameObject);
                newMainModule = null;
            }
            if (newMainModule != null)
            {
                mainExitToMatch.SetMatched(true);
                mainExitToMatch.setOtherSide(newModuleExitToMatch);
                newModuleExitToMatch.SetMatched(true);
                newModuleExitToMatch.setOtherSide(mainExitToMatch);
                mainPath.Add(newMainModule);
                newMainModule.transform.parent = moduleHolder.transform;
                pendingExits.AddRange(mainExits.Where(e => !e.IsMatched()));
                CurrentRooms++;
            }
        }

        var             endModulePrefab = Database.getEndRoom();
        var             endModule       = Instantiate(endModulePrefab);
        ModuleConnector finalMainExit   = null;

        try {
            finalMainExit = GetRandomExitWithTag(mainPath.Last(), endModule.tags);
        } catch (IndexOutOfRangeException e) {
            Debug.LogWarning(e);
            BuildBridgeForFinal(mainPath.Last());
            finalMainExit = GetRandomExitWithTag(mainPath.Last(), endModule.tags);
        }

        ModuleConnector finalExitToMatch = GetRandomExitWithTag(endModule, finalMainExit.GetComponentInParent <Module>().tags);

        MatchExits(finalMainExit, finalExitToMatch);

        endModule.gameObject.name = "Final";
        CurrentRooms++;
        mainPath.Add(endModule);

        if (CollisionDetection(endModule, finalMainExit.GetComponentInParent <Module>()))
        {
            Backtrack(3);
            BuildMainPath();
        }
        else
        {
            finalMainExit.SetMatched(true);
            finalMainExit.setOtherSide(finalExitToMatch);
            finalExitToMatch.SetMatched(true);
            finalExitToMatch.setOtherSide(finalMainExit);
            endModule.transform.parent = moduleHolder.transform;
            pendingExits.AddRange(finalMainExit.GetComponentInParent <Module>().GetExits().Where(e => e.IsMatched() != true));
            pendingExits.AddRange(endModule.GetExits().Where(e => e.IsMatched() != true));
        }
    }
Beispiel #25
0
 public void setOtherSide(ModuleConnector other)
 {
     otherSide   = other;
     ExitMatched = other != null;
 }
Beispiel #26
0
 public void SetBaseModule(ModuleConnector baseModuleConnector)
 {
     BaseModuleConnector = baseModuleConnector;
 }
    private bool FindMatchingModuleWithExits(int exits, ModuleConnector exitToMatch, Module otherModule)
    {
        List <Collider> colliderList = new List <Collider> {
            exitToMatch.GetComponentInParent <Module>().GetComponent <BoxCollider>()
        };

        foreach (ModuleConnector exit in otherModule.GetExits().Where(e => e.IsMatched() && e.getOtherSide() != null))
        {
            var exitOfModuleToMatch = exit.getOtherSide();
            colliderList.Add(exitOfModuleToMatch.
                             GetComponentInParent <Module>().
                             GetComponent <BoxCollider>());
        }
        otherModule.gameObject.SetActive(false);
        var possibleModules = Modules.Where(e => e.GetExits().Count() == exits);
        List <ModuleConnector> exitsToMatch = new List <ModuleConnector>();

        exitsToMatch.Add(exitToMatch);
        foreach (ModuleConnector exit in otherModule.GetExits().Where(e => e.IsMatched() && e.getOtherSide() != null))
        {
            exitsToMatch.Add(exit.getOtherSide());
        }
        for (int i = 0; i < possibleModules.Count(); i++)
        {
            int rotations = 0;

            Module testedModulePrefab = possibleModules.ElementAt(i);
            Module testedModule       = Instantiate(testedModulePrefab);
            while (rotations < 4)
            {
                Debug.Log("Testing Module " + testedModule.name + " at " + (90 * rotations) + "°");
                var exitsLeftToMatch = exitsToMatch;
                foreach (ModuleConnector testedModuleExit in testedModule.GetExits())
                {
                    exitsLeftToMatch = exitsLeftToMatch.Except(exitsLeftToMatch.Where(e => e.transform.forward == -testedModuleExit.transform.forward &&
                                                                                      e.hasTag(testedModule.tags) &&
                                                                                      (e.GetComponentInParent <Module>().tags & testedModuleExit.tags) != TileTagsEnum.DeadEnd &&
                                                                                      (e.tags & testedModule.tags) != TileTagsEnum.DeadEnd &&
                                                                                      testedModuleExit.hasTag(e.GetComponentInParent <Module>().tags))).ToList();
                }
                if (exitsLeftToMatch.Count() > 0)
                {
                    //Debug.Log(exitsLeftToMatch.Count());
                    exitsLeftToMatch = exitsToMatch;
                    testedModule.transform.Rotate(Vector3.up, 90);
                    rotations++;
                }
                else
                {
                    var testedModuleExits = testedModule.GetExits();

                    testedModule.gameObject.transform.position -=
                        (testedModule.GetExits().First().transform.position -
                         exitsToMatch.Where(e => e.transform.forward == -testedModuleExits.First().transform.forward).First().transform.position);
                    exitsToMatch.ForEach(e => e.SetMatched(true));
                    exitsToMatch.ForEach(e => e.setOtherSide(testedModuleExits.Where(d => - d.transform.forward == e.transform.forward).First()));
                    testedModuleExits.ToList().
                    ForEach(e => e.setOtherSide(
                                exitsToMatch.Where(d => - d.transform.forward == e.transform.forward)
                                .First()));
                    testedModuleExits.ToList().ForEach(e => e.SetMatched(true));
                    allModules.Add(testedModule);
                    if (mainPath.Contains(otherModule))
                    {
                        int index = mainPath.IndexOf(otherModule);
                        mainPath.Insert(index, testedModule);
                    }
                    testedModule.gameObject.name             = "Endroom " + CurrentRooms + "(" + otherModule.gameObject.name + ")";
                    testedModule.gameObject.transform.parent = moduleHolder.transform;
                    Debug.Log("Matching suceess: " + testedModule.gameObject.name);
                    return(true);
                }
            }
            Destroy(testedModule.gameObject);
        }
        return(false);
    }
    private void EndRoomCollisionHandling(Module newModule, ModuleConnector currentModuleConnector)
    {
        var newModuleCollider     = newModule.GetComponent <BoxCollider>();
        var currentModuleCollider = currentModuleConnector.GetComponentInParent <Module>().GetComponent <BoxCollider>();
        var possibleCollisions    = Physics.OverlapSphere(newModuleCollider.bounds.center, newModuleCollider.bounds.extents.magnitude);
        var relevantCollisions    = possibleCollisions.Where(e => e != newModuleCollider && e != currentModuleCollider && e.GetComponent <Module>() != null).ToList();
        int intersects            = 0;

        foreach (var collision in relevantCollisions)
        {
            if (newModuleCollider.bounds.Intersects(collision.bounds))
            {
                intersects++;
                Debug.Log("Relevante Collision für Tile " + newModule.name + ":" + collision.gameObject.name);
            }
        }
        Debug.Log("Relevante Collisions für Anschluss an Tile " + currentModuleConnector.transform.parent.name + ":" + intersects);
        if (intersects > 0)
        {
            var outDistance = 0f;
            //float maxDistance = newModuleCollider.bounds.size.z+currentModuleCollider.bounds.extents.z;
            //Debug.Log("MaxRayDistance for " + currentModuleCollider.name + ": " + maxDistance);
            var modulesInExitDirection = relevantCollisions.Where(e => e.bounds.
                                                                  IntersectRay(new Ray(currentModuleCollider.bounds.center, currentModuleConnector.transform.forward), out outDistance) &&
                                                                  outDistance <= 6 &&
                                                                  newModuleCollider.bounds.Intersects(e.bounds)).ToList();

            if (modulesInExitDirection.Count() > 0)
            {
                if (modulesInExitDirection.Count() > 1)
                {
                    Debug.Log("Need to sort raycast intersects");
                    var currentModuleConnectorPosition = currentModuleConnector.transform.position;

                    modulesInExitDirection.ForEach(e => Debug.Log("Intersected Module: " + e.transform.name +
                                                                  " ; Distance: " + (e.ClosestPoint(currentModuleConnectorPosition) - currentModuleConnectorPosition).magnitude));

                    modulesInExitDirection
                    .Sort((e1, e2) => (e1.ClosestPoint(currentModuleConnectorPosition) - currentModuleConnectorPosition).magnitude
                          .CompareTo((e2.ClosestPoint(currentModuleConnectorPosition) - currentModuleConnectorPosition).magnitude));
                }
                Module adjacentModule = modulesInExitDirection.First().GetComponentInParent <Module>();
                Debug.Log("Colliding Module to work with: " + adjacentModule.name);


                int exits = adjacentModule.GetExits().Where(e => e.IsMatched()).Count();
                newModule.gameObject.SetActive(false);
                Debug.Log("DeadEnd " + newModule.name + " disabled");
                Destroy(newModule.gameObject);
                bool exitsFit = checkIfExitsFitDirectly(currentModuleConnector, adjacentModule);
                bool matched  = false;

                Debug.Log("Exits to find: " + (exits + 1));
                if (!exitsFit && adjacentModule.tag != "immutable")
                {
                    matched = FindMatchingModuleWithExits(exits + 1, currentModuleConnector, adjacentModule);
                }
                Debug.Log("Endroommatching: " + (matched | exitsFit));
                if (matched)
                {
                    adjacentModule.gameObject.SetActive(false);
                    //Destroy(adjacentModule.gameObject);
                }
                else
                {
                    Debug.Log("No Match Case");
                    buildDeadendOutOfCurrentRoom(currentModuleConnector);
                    adjacentModule.gameObject.SetActive(true);
                }
            }
            else
            {
                Debug.Log("No Frontal Collision");
                newModule.transform.parent = moduleHolder.transform;
                allModules.Add(newModule);
                currentModuleConnector.SetMatched(true);
                var matchedExit = newModule.GetExits().First();
                currentModuleConnector.setOtherSide(matchedExit);
                matchedExit.SetMatched(true);
                matchedExit.setOtherSide(currentModuleConnector);
            }
        }
        else
        {
            Debug.Log("No Collision");
            newModule.transform.parent = moduleHolder.transform;
            allModules.Add(newModule);
            currentModuleConnector.SetMatched(true);
            var matchedExit = newModule.GetExits().First();
            currentModuleConnector.setOtherSide(matchedExit);
            matchedExit.SetMatched(true);
            matchedExit.setOtherSide(currentModuleConnector);
        }
        //currentModuleConnector.gameObject.SetActive(false);
        pendingExits.Remove(currentModuleConnector);
        CurrentRooms++;
    }
    public void GenerateMap()
    {
        //_surface.UpdateNavMesh(null);

        foreach (Transform t in transform)
        {
            Destroy(t.gameObject);
        }

        CurrentRooms.Clear();

        Module baseRoom = Instantiate(Rooms.GetRandom(), transform);

        baseRoom.transform.localPosition = Vector3.zero;
        CurrentRooms.Add(baseRoom);

        List <Module> currentModules = new List <Module>();
        List <Module> nextModules    = new List <Module>();

        currentModules.Add(baseRoom);

        for (int i = 0; i < Iterations; ++i)
        {
            foreach (Module module in currentModules)
            {
                foreach (ModuleConnector connector in module.Connectors)
                {
                    if (connector.IsAlreadyUsed)
                    {
                        continue;
                    }

                    Module tempModule;

                    connector.IsAlreadyUsed = true;

                    if (connector.CanConnectTo == ModuleType.Room)
                    {
                        tempModule = Rooms.GetRandom();
                    }
                    else
                    {
                        tempModule = Halls.GetRandom();
                    }

                    tempModule = Instantiate(tempModule, transform);

                    ModuleConnector tempConnector = tempModule.Connectors.Where(x => !x.IsAlreadyUsed).First();
                    if (tempConnector != null)
                    {
                        tempConnector.IsAlreadyUsed = true;

                        //tempModule.transform.rotation = connector.EntryPoint.rotation;
                        tempModule.transform.position  = connector.EntryPoint.position;
                        tempModule.transform.position += connector.EntryPoint.position - tempConnector.EntryPoint.position;
                        float angle = Vector3.SignedAngle(
                            connector.EntryPoint.forward,
                            tempConnector.EntryPoint.forward,
                            Vector3.up
                            );
                        tempModule.transform.RotateAround(tempConnector.EntryPoint.position, Vector3.up, 180 - angle);
                    }
                    nextModules.Add(tempModule);
                }
            }

            currentModules = new List <Module>(nextModules);
            var query = currentModules.Where(x => x.ModuleType == ModuleType.Room).ToList();
            CurrentRooms.AddRange(query);
            nextModules.Clear();
        }

        StartCoroutine(WaitToRebuild());
    }