Ejemplo n.º 1
0
        public static GameBoard CreateGame(Guid guid, int complexityLevel)
        {
            int width, height, colorCount;

            switch (complexityLevel)
            {
            case 2:
                width      = 20;
                height     = 20;
                colorCount = 12;
                break;

            case 1:
                width      = 15;
                height     = 15;
                colorCount = 9;
                break;

            case 0:
            default:
                width      = 10;
                height     = 10;
                colorCount = 6;
                break;
            }

            var boardData = RandomFieldGenerator.Create(width, height, colorCount);

            return(new GameBoard(width, height, boardData, guid, ColorPaletteGenerator.CreateHexPalette(colorCount)));
        }
Ejemplo n.º 2
0
        public static int[,] ToIndexArray(this CellDto[] cells, String[] palette)
        {
            int axisX = cells.Select <CellDto, int>(x => x.Pos.X).Max();
            int axisY = cells.Select <CellDto, int>(y => y.Pos.Y).Max();

            int[,] indexArray = new int[axisX, axisY];

            foreach (CellDto cell in cells)
            {
                indexArray[cell.Pos.X, cell.Pos.Y] = ColorPaletteGenerator.IndexInPalette(palette, cell.Content);
            }

            return(indexArray);
        }
Ejemplo n.º 3
0
    public static void LoadIngredients(string recipePath)
    {
        Debug.Log("*****");
        Debug.Log("Loading scene: " + recipePath);

        var cellPackSceneJsonPath = recipePath;//Application.dataPath + "/../Data/HIV/cellPACK/BloodHIV1.0_mixed_fixed_nc1.json";

        if (!File.Exists(cellPackSceneJsonPath))
        {
            throw new Exception("No file found at: " + cellPackSceneJsonPath);
        }

        var resultData = Helper.ParseJson(cellPackSceneJsonPath);

        //we can traverse the json dictionary and gather ingredient source (PDB,center), sphereTree, instance.geometry if we want.
        //the recipe is optional as it will gave more information than just the result file.

        //idea: use secondary color scheme for compartments, and analogous color for ingredient from the recipe baseColor
        current_color = 0;
        //first grab the total number of object
        int nIngredients = 0;

        if (resultData["cytoplasme"] != null)
        {
            nIngredients += resultData["cytoplasme"]["ingredients"].Count;
        }
        for (int i = 0; i < resultData["compartments"].Count; i++)
        {
            nIngredients += resultData["compartments"][i]["interior"]["ingredients"].Count;
            nIngredients += resultData["compartments"][i]["surface"]["ingredients"].Count;
        }
        //generate the palette
        //ColorsPalette   = ColorGenerator.Generate(nIngredients).Skip(2).ToList();
        ColorsPalette = ColorGenerator.Generate(8).Skip(2).ToList();//.Skip(2).ToList();
        List <Vector3> startKmeans = new List <Vector3>(ColorsPalette);

        //paletteGenerator.initKmeans (startKmeans);

        usedColors     = new Dictionary <int, List <int> >();
        ColorsPalette2 = ColorPaletteGenerator.generate(
            6,     // Colors
            ColorPaletteGenerator.testfunction,
            false, // Using Force Vector instead of k-Means
            50     // Steps (quality)
            );
        // Sort colors by differenciation first
        //ColorsPalette2 = paletteGenerator.diffSort(ColorsPalette2);
        //check if cytoplasme present
        Color baseColor = new Color(1.0f, 107.0f / 255.0f, 66.0f / 255.0f);

        if (resultData["cytoplasme"] != null)
        {
            usedColors.Add(current_color, new List <int>());
            baseColor = new Color(1.0f, 107.0f / 255.0f, 66.0f / 255.0f);
            AddRecipeIngredients(resultData["cytoplasme"]["ingredients"], baseColor, "cytoplasme");
            current_color += 1;
        }

        for (int i = 0; i < resultData["compartments"].Count; i++)
        {
            baseColor = new Color(148.0f / 255.0f, 66.0f / 255.0f, 255.0f / 255.0f);
            usedColors.Add(current_color, new List <int>());
            AddRecipeIngredients(resultData["compartments"][i]["interior"]["ingredients"], baseColor, "interior" + i.ToString());
            current_color += 1;
            baseColor      = new Color(173.0f / 255.0f, 255.0f / 255.0f, 66.0f / 255.0f);
            usedColors.Add(current_color, new List <int>());
            AddRecipeIngredients(resultData["compartments"][i]["surface"]["ingredients"], baseColor, "surface" + i.ToString());
            current_color += 1;
        }
    }
Ejemplo n.º 4
0
    public static void AddProteinIngredient(JSONNode ingredientDictionary, string prefix)
    {
        var name    = prefix + "_" + ingredientDictionary["name"];
        var biomt   = (bool)ingredientDictionary["source"]["biomt"].AsBool;
        var center  = (bool)ingredientDictionary["source"]["transform"]["center"].AsBool;
        var pdbName = ingredientDictionary["source"]["pdb"].Value.Replace(".pdb", "");

        if (pdbName == "")
        {
            return;
        }
        if (pdbName == "null")
        {
            return;
        }
        if (pdbName == "None")
        {
            return;
        }
        if (pdbName.StartsWith("EMDB"))
        {
            return;
        }
        if (pdbName.Contains("1PI7_1vpu_biounit"))
        {
            return;
        }

        // Disable biomts until loading problem is resolved
        if (biomt)
        {
            return;
        }

        // Load atom set from pdb file
        var atomSet = PdbLoader.LoadAtomSet(pdbName);

        // If the set is empty return
        if (atomSet.Count == 0)
        {
            return;
        }

        var atomSpheres    = AtomHelper.GetAtomSpheres(atomSet);
        var centerPosition = AtomHelper.ComputeBounds(atomSpheres).center;

        var biomtTransforms = biomt ? PdbLoader.LoadBiomtTransforms(pdbName) : new List <Matrix4x4>();
        var biomtCenter     = AtomHelper.GetBiomtCenter(biomtTransforms);

        var containsACarbonOnly = AtomHelper.ContainsACarbonOnly(atomSet);

        // Center atoms
        AtomHelper.OffsetSpheres(ref atomSpheres, centerPosition);

        // Compute bounds
        var bounds = AtomHelper.ComputeBounds(atomSpheres);

        // Get ingredient color
        // TODO: Move color palette code into dedicated function
        var cid = ColorPaletteGenerator.GetRandomUniqFromSample(current_color, usedColors[current_color]);

        usedColors[current_color].Add(cid);
        var sample = ColorPaletteGenerator.colorSamples[cid];
        var c      = ColorPaletteGenerator.lab2rgb(sample) / 255.0f;
        var color  = new Color(c[0], c[1], c[2]);

        // Define cluster decimation levels
        var clusterLevels = (containsACarbonOnly)
            ? new List <float>()
        {
            0.85f, 0.25f, 0.1f
        }
            : new List <float>()
        {
            0.10f, 0.05f, 0.01f
        };

        // Add ingredient type
        //SceneManager.Instance.AddIngredient(name, bounds, atomSpheres, color);
        SceneManager.Instance.AddIngredient(name, bounds, atomSpheres, color, clusterLevels);

        int instanceCount = 0;

        for (int k = 0; k < ingredientDictionary["results"].Count; k++)
        {
            var p = ingredientDictionary["results"][k][0];
            var r = ingredientDictionary["results"][k][1];

            var position = new Vector3(-p[0].AsFloat, p[1].AsFloat, p[2].AsFloat);
            var rotation = new Quaternion(r[0].AsFloat, r[1].AsFloat, r[2].AsFloat, r[3].AsFloat);

            var mat   = Helper.quaternion_matrix(rotation);
            var euler = Helper.euler_from_matrix(mat);
            rotation = Helper.MayaRotationToUnity(euler);

            if (!biomt)
            {
                // Find centered position
                if (!center)
                {
                    position += Helper.QuaternionTransform(rotation, centerPosition);
                }
                SceneManager.Instance.AddIngredientInstance(name, position, rotation);
                instanceCount++;
            }
            else
            {
                foreach (var transform in biomtTransforms)
                {
                    var biomtOffset      = Helper.RotationMatrixToQuaternion(transform) * centerPosition;
                    var biomtInstanceRot = rotation * Helper.RotationMatrixToQuaternion(transform);
                    var biomtInstancePos = rotation * (new Vector3(transform.m03, transform.m13, transform.m23) + biomtOffset) + position - biomtCenter;

                    SceneManager.Instance.AddIngredientInstance(name, biomtInstancePos, biomtInstanceRot);
                    instanceCount++;
                }
            }
        }

        Debug.Log("*****");
        Debug.Log("Added ingredient: " + name);
        if (containsACarbonOnly)
        {
            Debug.Log("Alpha-carbons only");
        }
        Debug.Log("Pdb name: " + pdbName + " *** " + "Num atoms: " + atomSpheres.Count + " *** " + "Num instances: " + instanceCount + " *** " + "Total atom count: " + atomSpheres.Count * instanceCount);
    }
Ejemplo n.º 5
0
    public static void AddProteinIngredient(JSONNode ingredientDictionary, params string[] pathElements)
    {
        var name    = ingredientDictionary["name"];
        var path    = MyUtility.GetUrlPath(pathElements.ToList(), name);
        var biomt   = (bool)ingredientDictionary["source"]["biomt"].AsBool;
        var center  = (bool)ingredientDictionary["source"]["transform"]["center"].AsBool;
        var pdbName = ingredientDictionary["source"]["pdb"].Value.Replace(".pdb", "");

        List <Vector4>   atomSpheres;
        List <Matrix4x4> biomtTransforms     = new List <Matrix4x4>();
        Vector3          biomtCenter         = Vector3.zero;
        bool             containsACarbonOnly = false;
        bool             oneLOD = false;

        if ((pdbName == "") || (pdbName == "null") || (pdbName == "None") || pdbName.StartsWith("EMDB"))
        {
            return;

            ////check for sphere file//information in the file. if not in file is it on disk ? on repo ?
            ////possibly read the actuall recipe definition ?
            ////check if bin exist
            //var filePath = PdbLoader.DefaultPdbDirectory + ingredientDictionary["name"] + ".bin";
            //if (File.Exists(filePath)){
            //	atomSpheres = new List<Vector4>();
            //	var points = MyUtility.ReadBytesAsFloats(filePath);
            //	for (var i = 0; i < points.Length; i += 4) {
            //		var currentAtom = new Vector4 (points [i], points [i + 1], points [i + 2], points [i + 3]);
            //		atomSpheres.Add (currentAtom);
            //	}
            //	containsACarbonOnly = true;
            //	oneLOD = true;
            //}
            //else if (ingredientDictionary ["radii"] != null) {
            //	atomSpheres = MyUtility.gatherSphereTree(ingredientDictionary)[0];
            //	Debug.Log ("nbprim "+atomSpheres.Count.ToString());//one sphere
            //	oneLOD = true;
            //} else {
            //	float radius = 30.0f;
            //	if (name.Contains("dLDL"))
            //		radius = 108.08f;//or use the mesh? or make sphere from the mesh ?
            //	if (name.Contains("iLDL"))
            //		radius = 105.41f;//or use the mesh? or make sphere from the mesh ?
            //	atomSpheres = new List<Vector4>();
            //	atomSpheres.Add (new Vector4(0,0,0,radius));
            //	//No LOD since only one sphere
            //	oneLOD = true;
            //}
        }
        else
        {
            //if (pdbName.StartsWith("EMDB")) return;
            //if (pdbName.Contains("1PI7_1vpu_biounit")) return;//??
            // Load atom set from pdb file
            var atomSet = PdbLoader.LoadAtomSet(pdbName);

            // If the set is empty return
            if (atomSet.Count == 0)
            {
                return;
            }

            atomSpheres         = AtomHelper.GetAtomSpheres(atomSet);
            containsACarbonOnly = AtomHelper.ContainsCarbonAlphaOnly(atomSet);
        }
        var centerPosition = AtomHelper.ComputeBounds(atomSpheres).center;

        // Center atoms
        AtomHelper.OffsetSpheres(ref atomSpheres, centerPosition);

        // Compute bounds
        var bounds = AtomHelper.ComputeBounds(atomSpheres);

        biomtTransforms = biomt ? PdbLoader.LoadBiomtTransforms(pdbName) : new List <Matrix4x4>();
        biomtCenter     = AtomHelper.GetBiomtCenter(biomtTransforms, centerPosition);

        //if (!pdbName.Contains("1TWT_1TWV")) return;

        // Disable biomts until loading problem is resolved
        //if (!biomt) return;


        // Get ingredient color
        // TODO: Move color palette code into dedicated function
        var cid = ColorPaletteGenerator.GetRandomUniqFromSample(current_color, usedColors[current_color]);

        usedColors[current_color].Add(cid);
        var sample = ColorPaletteGenerator.colorSamples[cid];
        var c      = ColorPaletteGenerator.lab2rgb(sample) / 255.0f;
        var color  = new Color(c[0], c[1], c[2]);

        // Define cluster decimation levels
        var clusterLevels = (containsACarbonOnly)
                ? new List <float>()
        {
            0.85f, 0.25f, 0.1f
        }
            : new List <float>()
        {
            0.15f, 0.10f, 0.05f
        };

        if (oneLOD)
        {
            clusterLevels = new List <float> ()
            {
                1, 1, 1
            }
        }
        ;
        // Add ingredient type
        //SceneManager.Instance.AddIngredient(name, bounds, atomSpheres, color);

        SceneManager.Get.AddProteinIngredient(path, bounds, atomSpheres, color, clusterLevels, oneLOD);
        int instanceCount = 0;

        for (int k = 0; k < ingredientDictionary["results"].Count; k++)
        {
            var p = ingredientDictionary["results"][k][0];
            var r = ingredientDictionary["results"][k][1];

            var position = new Vector3(-p[0].AsFloat, p[1].AsFloat, p[2].AsFloat);
            var rotation = new Quaternion(r[0].AsFloat, r[1].AsFloat, r[2].AsFloat, r[3].AsFloat);

            var mat   = MyUtility.quaternion_matrix(rotation);
            var euler = MyUtility.euler_from_matrix(mat);
            rotation = MyUtility.MayaRotationToUnity(euler);

            if (!biomt)
            {
                // Find centered position
                if (!center)
                {
                    position += MyUtility.QuaternionTransform(rotation, centerPosition);
                }
                SceneManager.Get.AddProteinInstance(path, position, rotation);
                instanceCount++;
            }
            else
            {
                foreach (var transform in biomtTransforms)
                {
                    var biomteuler = MyUtility.euler_from_matrix(transform);
                    var rotBiomt   = MyUtility.MayaRotationToUnity(biomteuler);
                    var offset     = MyUtility.QuaternionTransform(rotBiomt, centerPosition);               //Helper.RotationMatrixToQuaternion(matBiomt), GetCenter());
                    var posBiomt   = new Vector3(-transform.m03, transform.m13, transform.m23) + offset - biomtCenter;

                    var biomtOffset      = MyUtility.RotationMatrixToQuaternion(transform) * centerPosition;
                    var biomtInstanceRot = rotation * rotBiomt;                    //Helper.RotationMatrixToQuaternion(transform);
                    var biomtInstancePos = rotation * posBiomt + position;

                    SceneManager.Get.AddProteinInstance(path, biomtInstancePos, biomtInstanceRot);
                    instanceCount++;
                }
            }
        }

        SceneManager.Get.AddIngredientProperties(atomSpheres.Count, instanceCount);

        Debug.Log("*****");
        Debug.Log("Added ingredient: " + path);

        //if (isCarbonAlphaOnly) Debug.Log("Alpha-carbons only");
        //Debug.Log("Pdb name: " + pdbName + " *** " + "Num atoms: " + atomSet.Count + " *** " + "Num instances: " + instanceCount + " *** " + "Total atom count: " + atomSet.Count * instanceCount);
    }