public LayerGraphicsControl()
        {
            ControlInitialized += GraphicsDeviceControlInitialized;

            _textureCache = new TextureCache();
            _geometry = new LayerGraphicsControlGeometry(this);

            ClearColor = Color.LightGray;
        }
Beispiel #2
0
        protected void CheckAsyncResources()
        {
            DownloadedItem item;

            if (game.AsyncDownloader.TryGetItem("terrain", out item))
            {
                if (item.Data != null)
                {
                    Bitmap bmp = (Bitmap)item.Data;
                    if (!FastBitmap.CheckFormat(bmp.PixelFormat))
                    {
                        Utils.LogDebug("Converting terrain atlas to 32bpp image");
                        game.Drawer2D.ConvertTo32Bpp(ref bmp);
                    }
                    game.ChangeTerrainAtlas(bmp);
                    TextureCache.AddToCache(item.Url, bmp);
                    game.Map.TextureUrl = item.Url;
                }
                else if (Is304Status(item.WebEx))
                {
                    Bitmap bmp = TextureCache.GetBitmapFromCache(item.Url);
                    if (bmp == null)                      // Should never happen, but handle anyways.
                    {
                        ExtractDefault();
                    }
                    else
                    {
                        game.ChangeTerrainAtlas(bmp);
                    }
                    game.Map.TextureUrl = item.Url;
                }
                else
                {
                    ExtractDefault();
                    game.Map.TextureUrl = null;
                }
            }

            if (game.AsyncDownloader.TryGetItem("texturePack", out item))
            {
                if (item.Data != null)
                {
                    TexturePackExtractor extractor = new TexturePackExtractor();
                    extractor.Extract((byte[])item.Data, game);
                    TextureCache.AddToCache(item.Url, (byte[])item.Data);
                    game.Map.TextureUrl = item.Url;
                }
                else if (Is304Status(item.WebEx))
                {
                    byte[] data = TextureCache.GetDataFromCache(item.Url);
                    if (data == null)                        // Should never happen, but handle anyways.
                    {
                        ExtractDefault();
                    }
                    else
                    {
                        TexturePackExtractor extractor = new TexturePackExtractor();
                        extractor.Extract(data, game);
                    }
                    game.Map.TextureUrl = item.Url;
                }
                else
                {
                    ExtractDefault();
                    game.Map.TextureUrl = null;
                }
            }
        }
Beispiel #3
0
    public static void BuildAtlas(tmTextureCollectionPlatform collectionPlatform)
    {
        string collectionPath      = AssetDatabase.GetAssetPath(collectionPlatform);
        string collectionDirectory = System.IO.Path.GetDirectoryName(collectionPath);
        string collectionFileName  = System.IO.Path.GetFileNameWithoutExtension(collectionPath);
        string atlasName           = collectionFileName + "_atlas.png";

        string collectionAtlasPath;

        if (collectionPlatform.useStreamingAssets)
        {
            collectionAtlasPath = "Assets/StreamingAssets/" + tmManager.stramingAssetsDirectory + "/" + atlasName;
        }
        else
        {
            collectionAtlasPath = collectionDirectory + "/" + atlasName;
        }

        Texture2D atlas = new Texture2D(4096, 4096, collectionPlatform.importSettings.format, collectionPlatform.importSettings.generateMipMaps);

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

        foreach (tmTextureDefenition td in collectionPlatform.textureDefenitions)
        {
            td.uv = new Rect();
            textures.Add(td.platformTexture);
        }

        Rect[] spritesRect = atlas.PackTextures(textures.ToArray(), collectionPlatform.importSettings.border, 4096, false);
        for (int i = 0; i < spritesRect.Length; i++)
        {
            collectionPlatform.textureDefenitions[i].uv = spritesRect[i];
            Rect offset = new Rect();
            offset.size   = collectionPlatform.textureDefenitions[i].offset.size * 1f / atlas.width;
            offset.center = collectionPlatform.textureDefenitions[i].offset.center * 1f / atlas.width;
            collectionPlatform.textureDefenitions[i].offset = offset;
        }

        collectionPlatform.AtlasAssetGUID = AssetDatabase.AssetPathToGUID(collectionAtlasPath);

        var bytes = atlas.EncodeToPNG();

        System.IO.File.WriteAllBytes(collectionAtlasPath, bytes);


        if (!collectionPlatform.useStreamingAssets)
        {
            int startIndex = collectionAtlasPath.IndexOf("Resources/", System.StringComparison.CurrentCulture) + 10;
            int lastIndex  = collectionAtlasPath.LastIndexOf('.');
            collectionPlatform.AssetPath = collectionAtlasPath.Substring(startIndex, lastIndex - startIndex);

            AssetDatabase.Refresh();

            TextureImporter tImporter = AssetImporter.GetAtPath(collectionAtlasPath) as TextureImporter;
            tImporter.textureType    = TextureImporterType.Default;
            tImporter.isReadable     = false;
            tImporter.maxTextureSize = 4096;
            tImporter.textureFormat  = collectionPlatform.importSettings.importFormat;
            tImporter.mipmapEnabled  = collectionPlatform.importSettings.generateMipMaps;
            AssetDatabase.ImportAsset(collectionAtlasPath, ImportAssetOptions.ForceUpdate);
        }
        else
        {
            collectionPlatform.AssetPath = atlasName;
        }

        if (collectionPlatform.Atlas != null)
        {
            TextureCache.UnloadTexture(collectionPlatform.Atlas);
            collectionPlatform.Atlas = null;
            collectionPlatform.LoadTexture();
        }

        Object.DestroyImmediate(atlas);

        EditorUtility.SetDirty(collectionPlatform);
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
    }
Beispiel #4
0
        public bool Update(ParameterList pl, SunflowAPI api)
        {
            updateBasis(pl.getVector("center", null), pl.getVector("up", null));
            numSamples    = pl.getInt("samples", numSamples);
            numLowSamples = pl.getInt("lowsamples", numLowSamples);

            string filename = pl.getstring("texture", null);

            if (filename != null)
            {
                texture = TextureCache.getTexture(api.resolveTextureFilename(filename), false);
            }

            // no texture provided
            if (texture == null)
            {
                return(false);
            }
            Bitmap b = texture.getBitmap();

            if (b == null)
            {
                return(false);
            }

            // rebuild histograms if this is a new texture
            if (filename != null)
            {
                imageHistogram = new float[b.getWidth()][];
                for (int i = 0; i < imageHistogram.Length; i++)
                {
                    imageHistogram[i] = new float[b.getHeight()];
                }
                colHistogram = new float[b.getWidth()];
                float du = 1.0f / b.getWidth();
                float dv = 1.0f / b.getHeight();
                for (int x = 0; x < b.getWidth(); x++)
                {
                    for (int y = 0; y < b.getHeight(); y++)
                    {
                        float u = (x + 0.5f) * du;
                        float v = (y + 0.5f) * dv;
                        Color c = texture.getPixel(u, v);
                        imageHistogram[x][y] = c.getLuminance() * (float)Math.Sin(Math.PI * v);
                        if (y > 0)
                        {
                            imageHistogram[x][y] += imageHistogram[x][y - 1];
                        }
                    }
                    colHistogram[x] = imageHistogram[x][b.getHeight() - 1];
                    if (x > 0)
                    {
                        colHistogram[x] += colHistogram[x - 1];
                    }
                    for (int y = 0; y < b.getHeight(); y++)
                    {
                        imageHistogram[x][y] /= imageHistogram[x][b.getHeight() - 1];
                    }
                }
                for (int x = 0; x < b.getWidth(); x++)
                {
                    colHistogram[x] /= colHistogram[b.getWidth() - 1];
                }
                jacobian = (float)(2 * Math.PI * Math.PI) / (b.getWidth() * b.getHeight());
            }
            // take fixed samples
            if (pl.getbool("fixed", samples != null))
            {
                // high density samples
                samples = new Vector3[numSamples];
                colors  = new Color[numSamples];
                generateFixedSamples(samples, colors);
                // low density samples
                lowSamples = new Vector3[numLowSamples];
                lowColors  = new Color[numLowSamples];
                generateFixedSamples(lowSamples, lowColors);
            }
            else
            {
                // turn off
                samples = lowSamples = null;
                colors  = lowColors = null;
            }
            return(true);
        }
        public static void HideCrossings0(Material material, Material segMaterial, NetInfo info, bool lod = false)
        {
            if (material == null)
            {
                throw new ArgumentNullException("material");
            }
            //if (segMaterial == null) throw new ArgumentNullException("segMaterial");
            if (info == null)
            {
                throw new ArgumentNullException("info");
            }

            Texture2D tex, tex2;
            bool      dump = false;

#if DEBUG
            dump = false;
#endif
            if (dump)
            {
                DumpUtils.Dump(info);
            }

            tex = material.TryGetTexture2D(ID_Defuse);
            Log.Debug($"material={material} tex={tex} h={tex?.height} w={tex?.width}");
            if (tex != null)
            {
                if (dump)
                {
                    DumpUtils.Dump(tex, info);
                }
                if (TextureCache.Contains(tex))
                {
                    tex = TextureCache[tex] as Texture2D;
                    Log.Info("Texture cache hit: " + tex.name);
                }
                else
                {
                    Log.Info("processing Defuse texture for " + tex.name);
                    tex = tex.GetReadableCopy();
                    tex.CropAndStrech(); if (dump)
                    {
                        DumpUtils.Dump(tex, info);
                    }
                    tex.Finalize(lod);
                    TextureCache[material.GetTexture(ID_Defuse)] = tex;
                }
                if (dump)
                {
                    DumpUtils.Dump(tex, info);
                }
                material.SetTexture(ID_Defuse, tex);
                //Log.Info($"material={material} tex={tex} h={tex.height} w={tex.width}");
                if (dump)
                {
                    DumpUtils.Dump(tex, DumpUtils.GetFilePath(ID_Defuse, "node-processed", info));
                }
            }

            tex = material.TryGetTexture2D(ID_APRMap);

            if (tex != null && tex.name != "RoadSmallNode-default-apr" && tex.name != "BasicRoad2_Junction-apr")
            {
                segMaterial = segMaterial ?? GetSegmentMaterial(info, ID_APRMap);
                tex2        = segMaterial?.TryGetTexture2D(ID_APRMap);
                if (tex != null && tex2 != null)
                {
                    if (dump)
                    {
                        DumpUtils.Dump(tex, info);
                    }
                    if (dump)
                    {
                        DumpUtils.Dump(tex2, info);
                    }
                    if (TextureCache.Contains(tex))
                    {
                        tex = TextureCache[tex] as Texture2D;
                        Log.Info("Texture cache hit: " + tex.name);
                    }
                    else
                    {
                        Log.Info("processing APR texture for " + tex.name);
                        bool linear = lod && !info.IsNExt();
                        tex  = tex.GetReadableCopy(linear: linear);
                        tex2 = tex2.GetReadableCopy(linear: linear);
                        if (tex2.width == tex.width * 2)
                        {
                            tex2 = TextureUtils.CutToSize(tex2, tex.width, tex.height);
                            if (dump)
                            {
                                DumpUtils.Dump(tex2, info);
                            }
                        }

                        tex.CropAndStrech(); if (dump)
                        {
                            DumpUtils.Dump(tex, info);
                        }
                        if (info.m_netAI is RoadAI)
                        {
                            if (info.isAsym() && !info.isOneWay())
                            {
                                tex2.Mirror();
                                if (dump)
                                {
                                    DumpUtils.Dump(tex2, info);
                                }
                            }
                            tex2.Scale(info.ScaleRatio());
                            if (info.ScaleRatio() != 1f && dump)
                            {
                                DumpUtils.Dump(tex2, info);
                            }
                        }
                        tex.MeldDiff(tex2); if (dump)
                        {
                            DumpUtils.Dump(tex, info);
                        }

                        tex.Finalize(lod);
                        TextureCache[material.GetTexture(ID_APRMap)] = tex;
                    }
                    material.SetTexture(ID_APRMap, tex);
                    if (dump)
                    {
                        DumpUtils.Dump(tex, DumpUtils.GetFilePath(ID_APRMap, "node-processed", info));
                    }
                } // end if cache
            }     // end if tex
        }         // end if category
        public static TextureState Read(BundleEntry entry)
        {
            TextureState result = new TextureState();

            List <BundleDependency> dependencies = entry.GetDependencies();

            foreach (BundleDependency dependency in dependencies)
            {
                ulong id = dependency.EntryID;

                if (TextureCache.Contains(id))
                {
                    result.Texture = TextureCache.GetTexture(id);
                }
                else
                {
                    BundleEntry descEntry1 = entry.Archive.GetEntryByID(id);
                    if (descEntry1 == null)
                    {
                        string file = BundleCache.GetFileByEntryID(id);
                        if (!string.IsNullOrEmpty(file))
                        {
                            BundleArchive archive = BundleArchive.Read(file);
                            if (archive != null)
                            {
                                descEntry1 = archive.GetEntryByID(id);
                            }
                        }
                    }

                    if (descEntry1 != null && descEntry1.Type == EntryType.Texture)
                    {
                        if (entry.Console)
                        {
                            result.Texture = GameImage.GetImagePS3(descEntry1.EntryBlocks[0].Data, descEntry1.EntryBlocks[1].Data);
                        }
                        else
                        {
                            result.Texture = GameImage.GetImage(descEntry1.EntryBlocks[0].Data, descEntry1.EntryBlocks[1].Data);
                        }

                        if (result.Texture != null)
                        {
                            TextureCache.AddToCache(id, result.Texture);
                        }

                        break;
                    }
                }
            }

            MemoryStream  ms = entry.MakeStream();
            BinaryReader2 br = new BinaryReader2(ms);

            br.BigEndian = entry.Console;

            // TODO: Read Texture State

            br.Close();
            ms.Close();

            return(result);
        }
        void DrawFramePreview()
        {
            float pointScale = 0.025f;
            float lineScale  = 0.01f;

            ShowPreview = EditorGUILayout.BeginFoldoutHeaderGroup(ShowPreview, "Frame viewer");

            if (ShowPreview)
            {
                if (!EditorApplication.isPlaying)
                {
                    NuitrackSDKGUI.DrawMessage("RGB and depth frames will be displayed run time.", LogType.Log);
                }
                else
                {
                    if (rgbCache == null)
                    {
                        rgbCache = new TextureCache();
                    }

                    if (depthCache == null)
                    {
                        depthCache = new TextureCache();
                    }

                    List <Vector2> pointCoord = new List <Vector2>();

                    rgbTexture   = NuitrackManager.ColorFrame.ToRenderTexture(rgbCache);
                    depthTexture = NuitrackManager.DepthFrame.ToRenderTexture(textureCache: depthCache);

                    Rect rgbRect = NuitrackSDKGUI.DrawFrame(rgbTexture, "RGB frame");

                    Texture pointTexture = EditorGUIUtility.IconContent("sv_icon_dot0_pix16_gizmo").image;

                    float lineSize = rgbRect.size.magnitude * lineScale;

                    foreach (UserData user in NuitrackManager.Users)
                    {
                        if (user.Skeleton != null)
                        {
                            Color userColor = FrameUtils.SegmentToTexture.GetColorByID(user.ID);

                            foreach (nuitrack.JointType jointType in System.Enum.GetValues(typeof(nuitrack.JointType)))
                            {
                                nuitrack.JointType parentJointType = jointType.GetParent();

                                UserData.SkeletonData.Joint joint = user.Skeleton.GetJoint(jointType);

                                if (joint.Confidence > 0.1f)
                                {
                                    Vector2 startPoint = new Vector2(rgbRect.x + rgbRect.width * joint.Proj.x, rgbRect.y + rgbRect.height * (1 - joint.Proj.y));

                                    pointCoord.Add(startPoint);

                                    if (jointType.GetParent() != nuitrack.JointType.None)
                                    {
                                        UserData.SkeletonData.Joint parentJoint = user.Skeleton.GetJoint(parentJointType);

                                        if (parentJoint.Confidence > 0.1f)
                                        {
                                            Vector2 endPoint = new Vector2(rgbRect.x + rgbRect.width * parentJoint.Proj.x, rgbRect.y + rgbRect.height * (1 - parentJoint.Proj.y));
                                            Handles.DrawBezier(startPoint, endPoint, startPoint, endPoint, userColor, null, lineSize);
                                        }
                                    }
                                }
                            }

                            float pointSize = rgbRect.size.magnitude * pointScale;

                            foreach (Vector3 point in pointCoord)
                            {
                                Rect rect = new Rect(point.x - pointSize / 2, point.y - pointSize / 2, pointSize, pointSize);
                                GUI.DrawTexture(rect, pointTexture, ScaleMode.ScaleToFit);
                            }
                        }
                    }

                    NuitrackSDKGUI.DrawFrame(depthTexture, "Depth frame");

                    Repaint();
                }
            }
            EditorGUILayout.EndFoldoutHeaderGroup();
        }
Beispiel #8
0
 public TileProvider(MonoBehaviour behaviour, TextureCache cache)
 {
     this.behaviour = behaviour;
     this.cache     = cache;
 }
Beispiel #9
0
        void DrawRuntimeWizard()
        {
            GUIContent wizardLabel = new GUIContent("Save runtime pose wizard", EditorGUIUtility.IconContent("AvatarSelector").image);

            ShowRuntimePoseWizard = EditorGUILayout.BeginFoldoutHeaderGroup(ShowRuntimePoseWizard, wizardLabel);

            if (ShowRuntimePoseWizard)
            {
                if (NuitrackManager == null)
                {
                    UnityAction fixNuitrack = delegate { NuitrackMenu.AddNuitrackToScene(); };
                    NuitrackSDKGUI.DrawMessage("The wizard requires NuitrackScripts on the scene.", LogType.Error, fixNuitrack, "Fix");

                    Selection.activeObject = target;
                }
                else
                {
                    if (!EditorApplication.isPlaying)
                    {
                        using (new VerticalGroup(EditorStyles.helpBox))
                            EditorGUILayout.LabelField("1) Play \n2) Stand in a pose \n3) Save pose", EditorStyles.wordWrappedLabel);

                        EditorGUILayout.Space();
                        SaveFolder = NuitrackSDKGUI.OpenFolderField(SaveFolder, "Save pose folder", true, DefaultPath);

                        GUIContent playScene = new GUIContent("Play", EditorGUIUtility.IconContent("PlayButton").image);

                        EditorGUILayout.Space();
                        if (GUILayout.Button(playScene))
                        {
                            EditorApplication.isPlaying = true;
                        }
                    }
                    else
                    {
                        UserData user = NuitrackManager.Users.Current;

                        bool disable = user == null || user.Skeleton == null;

                        Texture icon            = disable ? NuitrackSDKGUI.GetMessageIcon(LogType.Warning) : null;
                        Color   backgroundColor = disable ? Color.yellow : Color.green;

                        string message = "After saving a pose, playback will stop and the saved pose will open";

                        if (disable)
                        {
                            message = string.Format("{0}\n{1}", "The user was not found. Stand in front of the sensor to save a pose.", message);
                        }

                        GUIContent  messageGUI = new GUIContent(message, icon);
                        UnityAction savePose   = delegate { SaveRuntimePose(user.Skeleton); };

                        GUIContent iconAvatar = new GUIContent("Save runtime pose", EditorGUIUtility.IconContent("SaveAs").image);

                        EditorGUI.BeginDisabledGroup(disable);
                        NuitrackSDKGUI.DrawMessage(messageGUI, backgroundColor, savePose, iconAvatar);
                        EditorGUI.EndDisabledGroup();

                        Repaint();

                        if (rgbCache == null)
                        {
                            rgbCache = new TextureCache();
                        }

                        rgbTexture = NuitrackManager.ColorFrame.ToRenderTexture(rgbCache);

                        NuitrackSDKGUI.DrawFrame(rgbTexture, "RGB Preview");
                    }
                }
            }
            EditorGUILayout.EndFoldoutHeaderGroup();
        }
Beispiel #10
0
 public FigureRendererLoader(IArchiveDirectory dataDir, Device device, ShaderCache shaderCache, TextureCache textureCache)
 {
     this.dataDir      = dataDir;
     this.device       = device;
     this.shaderCache  = shaderCache;
     this.textureCache = textureCache;
 }
Beispiel #11
0
        public void LoadLandblock(uint landblockID, uint radius = 1)
        {
            if (PlayerMode)
            {
                ExitPlayerMode();
                InitPlayerMode = true;
            }

            Render.Buffer.ClearBuffer();
            Server.Init();
            TextureCache.Init();

            LScape.unload_landblocks_all();

            var landblock = LScape.get_landblock(landblockID);

            if (landblock.HasDungeon)
            {
                radius = 0;
            }

            DungeonMode = landblock.HasDungeon;

            var center_lbx = landblockID >> 24;
            var center_lby = landblockID >> 16 & 0xFF;

            //Landblocks = new Dictionary<uint, R_Landblock>();
            R_Landblock r_landblock = null;
            R_Landblock centerBlock = null;

            for (var lbx = (int)(center_lbx - radius); lbx <= center_lbx + radius; lbx++)
            {
                if (lbx < 0 || lbx > 254)
                {
                    continue;
                }

                for (var lby = (int)(center_lby - radius); lby <= center_lby + radius; lby++)
                {
                    if (lby < 0 || lby > 254)
                    {
                        continue;
                    }

                    var lbid = (uint)(lbx << 24 | lby << 16 | 0xFFFF);

                    var timer = Stopwatch.StartNew();
                    landblock = LScape.get_landblock(lbid);
                    timer.Stop();

                    r_landblock = new R_Landblock(landblock);
                    //LScape.unload_landblock(lbid);

                    if (landblockID == lbid)
                    {
                        centerBlock = r_landblock;
                    }

                    MainWindow.Status.WriteLine($"Loaded {lbid:X8} in {timer.Elapsed.TotalMilliseconds}ms");

                    //Landblocks.Add(lbid, new R_Landblock(landblock));
                }
            }

            Render.Buffer.BuildBuffers();
            Render.InitEmitters();

            if (FileExplorer.Instance.TeleportMode)
            {
                var zBump = DungeonMode ? 1.775f : 2.775f;

                if (InitPlayerMode)
                {
                    zBump = 0.0f;
                }

                Camera.InitTeleport(centerBlock, zBump);
                FileExplorer.Instance.TeleportMode = false;
            }
            else if (DungeonMode)
            {
                BoundingBox = new Model.BoundingBox(Render.Buffer.RB_EnvCell);
                Camera.InitDungeon(r_landblock, BoundingBox);
            }
            else
            {
                Camera.InitLandblock(r_landblock);
            }

            SingleBlock = landblock.ID;

            FreeResources();

            Server.OnLoadWorld();
        }
Beispiel #12
0
 public void FreeResources()
 {
     TextureCache.Init(false);
 }
Beispiel #13
0
        public async void LoadLandblocks(Vector2 startBlock, Vector2 endBlock)
        {
            //Console.WriteLine($"LoadLandblocks({startBlock}, {endBlock})");
            if (PlayerMode)
            {
                ExitPlayerMode();
                InitPlayerMode = true;
            }

            Render.Buffer.ClearBuffer();
            Server.Init();
            TextureCache.Init();

            LScape.unload_landblocks_all();

            DungeonMode = false;

            var dx        = (int)(endBlock.X - startBlock.X) + 1;
            var dy        = (int)(startBlock.Y - endBlock.Y) + 1;
            var numBlocks = dx * dy;

            var size        = endBlock - startBlock;
            var center      = startBlock + size / 2;
            var centerX     = (uint)Math.Round(center.X);
            var centerY     = (uint)Math.Round(center.Y);
            var landblockID = centerX << 24 | centerY << 16 | 0xFFFF;

            MainWindow.Status.WriteLine($"Loading {numBlocks} landblocks");
            await Task.Delay(1);

            //Landblocks = new Dictionary<uint, R_Landblock>();
            R_Landblock r_landblock = null;
            R_Landblock centerBlock = null;

            for (var lbx = (uint)startBlock.X; lbx <= endBlock.X; lbx++)
            {
                if (lbx < 0 || lbx > 254)
                {
                    continue;
                }

                for (var lby = (uint)endBlock.Y; lby <= startBlock.Y; lby++)
                {
                    if (lby < 0 || lby > 254)
                    {
                        continue;
                    }

                    var lbid = lbx << 24 | lby << 16 | 0xFFFF;

                    var timer     = Stopwatch.StartNew();
                    var landblock = LScape.get_landblock(lbid);
                    timer.Stop();

                    r_landblock = new R_Landblock(landblock);
                    //LScape.unload_landblock(lbid);

                    if (lbid == landblockID)
                    {
                        centerBlock = r_landblock;
                    }

                    MainWindow.Status.WriteLine($"Loaded {lbid:X8} in {timer.Elapsed.TotalMilliseconds}ms");

                    //Landblocks.Add(lbid, new R_Landblock(landblock));
                }
            }

            Render.Buffer.BuildBuffers();
            Render.InitEmitters();

            Camera.InitLandblock(centerBlock);
            GameView.ViewMode = ViewMode.World;

            SingleBlock = uint.MaxValue;

            FreeResources();

            Server.OnLoadWorld();
        }
Beispiel #14
0
        public static async Task <int> Cache(CacheOptions options)
        {
            if (options.dump || options.extract)
            {
                // initial checks
                var inputFileInfo = new FileInfo(options.path);
                if (!inputFileInfo.Exists)
                {
                    return(0);
                }
                var outDir = inputFileInfo.Directory;
                if (outDir == null)
                {
                    return(0);
                }
                if (!outDir.Exists)
                {
                    Directory.CreateDirectory(outDir.FullName);
                }
                if (inputFileInfo.Extension != ".cache")
                {
                    return(0);
                }
                if (inputFileInfo.Name != "texture.cache")
                {
                    System.Console.WriteLine($@"Only texture caches currently suported.");
                    return(0);
                }

                // load texture cache
                // switch chache types
                var txc = new TextureCache(inputFileInfo.FullName);

                if (options.dump)
                {
                    txc.DumpInfo();
                    System.Console.WriteLine($@"Finished dumping {options.path}.");
                }

                if (options.extract)
                {
                    foreach (var x in txc.Files)
                    {
                        string fullpath = Path.Combine(outDir.FullName, x.Name);
                        x.Extract(new BundleFileExtractArgs(fullpath, EUncookExtension.dds));
                        System.Console.WriteLine($@"Finished extracting {x.Name}.");
                    }
                    System.Console.WriteLine($@"Finished extracting {options.path}.");
                }
            }

            if (options.create)
            {
                if (!Directory.Exists(options.path))
                {
                    return(0);
                }
                var txc = new TextureCache();
                txc.LoadFiles(options.path);
                txc.Write(Path.Combine(options.path, "texture.cache"));

                System.Console.WriteLine($@"Finished creating {options.path}.");
            }


            return(1);
        }
Beispiel #15
0
        /// <summary>
        /// Default constructor
        /// </summary>
        /// <param name="client">A reference to the GridClient object</param>
#if USE_SMART_THREAD_POOL
        public AssetManager(GridClient client, SmartThreadPool threadPool)
        {
            ThreadPool = threadPool;
            Cache = new TextureCache(client, ThreadPool);
    void Awake()
    {
        msInst = this;

        mTextureCache = this.gameObject.AddComponent<TextureCache> ();
    }
 public TextureSamplerManager(OptixSession session)
 {
     texCache = TextureCache.Instance;
     this.session = session;
 }
Beispiel #18
0
        private static async Task <int> DumpCache(CacheOptions options)
        {
            bool WHITELIST    = true;
            var  whitelistExt = new[]
            {
                "w2cube",
            };
            bool EXTRACT = true;


            // Texture
            //using (var of = new OpenFileDialog() { Filter = "Texture caches | texture.cache" })
            {
                //if (of.ShowDialog() == DialogResult.OK)
                {
                    var    dt  = DateTime.Now;
                    string idx = RED.CRC32.Crc32Algorithm.Compute(Encoding.ASCII.GetBytes($"{dt.Year}{dt.Month}{dt.Day}{dt.Hour}{dt.Minute}{dt.Second}")).ToString();
                    //var txc = new TextureCache(of.FileName);
                    var txc    = new TextureCache(options.path);
                    var outDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "TXTTest", $"ExtractedFiles_{idx}");
                    if (!Directory.Exists(outDir))
                    {
                        Directory.CreateDirectory(outDir);
                    }

                    // Dump
                    using (StreamWriter writer = File.CreateText(Path.Combine(outDir, $"__txtdump_{idx}.txt")))
                    {
                        string head = "Format\t" +
                                      "Format2\t" +
                                      "BPP\t" +
                                      "Width\t" +
                                      "Height\t" +
                                      "Size\t" +
                                      "Mips\t" +
                                      "Slices\t" +
                                      "Cube\t" +
                                      "Unk1\t" +
                                      //"Hash\t" +
                                      "Name";
                        writer.WriteLine(head);

                        foreach (var x in txc.Files)
                        {
                            string ext = x.Name.Split('.').Last();
                            if (!whitelistExt.Contains(ext) && WHITELIST)
                            {
                                continue;
                            }

                            string info = $"{x.Type1:X2}\t" +
                                          $"{x.Type2:X2}\t" +
                                          $"{x.BaseAlignment}\t" +
                                          $"{x.BaseWidth}\t" +
                                          $"{x.BaseHeight}\t" +
                                          $"{x.Size}\t" +
                                          $"{x.Mipcount}\t" +
                                          $"{x.SliceCount}\t" +
                                          $"{x.IsCube.ToString("X2")}\t" +
                                          $"{x.Unk1.ToString()}/{x.Unk1.ToString("X2")}\t" +
                                          //$"{x.Hash}\t" +
                                          $"{x.Name}\t"
                            ;

                            info += "<";
                            foreach (var y in x.MipMapInfo)
                            {
                                info += $"<{y.Item1},{y.Item2}>";
                            }
                            info += ">";

                            //Console.WriteLine(info);
                            writer.WriteLine(info);

                            if (EXTRACT)
                            {
                                string fullpath = Path.Combine(outDir, x.Name);
                                string filename = Path.GetFileName(fullpath);
                                string newpath  = Path.Combine(outDir, filename);
                                x.Extract(new BundleFileExtractArgs(newpath));
                                System.Console.WriteLine($"Finished extracting {x.Name}");
                            }
                        }
                        System.Console.WriteLine($"Finished dumping texture cache. {options.path}");
                    }
                    System.Console.WriteLine($"Finished extracting.");
                    System.Console.ReadLine();
                }
            }


            // Collision

            /*
             * using (var of = new OpenFileDialog(){Filter = "Collision caches | collision.cache"})
             * {
             *  if (of.ShowDialog() == DialogResult.OK)
             *  {
             *      var ccf = new CollisionCache(of.FileName);
             *      var fd = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),"CCTest");
             *      ccf.Files.ForEach(x=> x.Extract(Path.Combine(fd,x.Name)));
             *      CollisionCache.Write(Directory.GetFiles(fd,"*",SearchOption.AllDirectories).ToList().OrderByDescending(x=> new FileInfo(x).CreationTime).ToList(),of.FileName + "_regenerated");
             *      //IntenseTest(of.FileNames.ToList());
             *      Console.ReadLine();
             *  }
             * }
             */

            return(1);
        }
Beispiel #19
0
        public void LoadModel(uint wcid)
        {
            Server.Initting = true;

            Buffer.ClearBuffer();
            TextureCache.Init();

            LScape.unload_landblocks_all();

            Console.WriteLine($"Loading {wcid}");
            GfxObjMode = false;

            var wo = WorldObjectFactory.CreateNewWorldObject(wcid);

            if (wo == null)
            {
                return;
            }

            wo.InitPhysicsObj();

            var location = new Position();

            location.ObjCellID    = 0x00000001;
            location.Frame.Origin = new System.Numerics.Vector3(12, 12, 0);

            var success = wo.PhysicsObj.enter_world(location);

            if (!success || wo.PhysicsObj.CurCell == null)
            {
                wo.PhysicsObj.DestroyObject();
                wo.PhysicsObj = null;
                Console.WriteLine($"WorldObjectViewer.LoadModel({wcid}).AddPhysicsObj({wo.Name}, {location}) - failed to spawn");
                return;
            }

            Console.WriteLine($"Spawned {wcid} - {wo.Name} @ {location}");

            var objDesc = new ObjDesc(wo.SetupTableId, wo.ClothingBase ?? 0, (PaletteTemplate)(wo.PaletteTemplate ?? 0), (float)(wo.Shade ?? 0.0));

            if (wo is Creature creature)
            {
                objDesc.AddBaseModelData(wo);

                var equippedObjects = creature.EquippedObjects.Values.OrderBy(i => (int)(i.ClothingPriority ?? 0)).ToList();

                foreach (var equippedObject in equippedObjects)
                {
                    if ((equippedObject.CurrentWieldedLocation & EquipMask.Selectable) != 0)
                    {
                        continue;
                    }

                    objDesc.Add(equippedObject.ClothingBase ?? 0, (PaletteTemplate)(equippedObject.PaletteTemplate ?? 0), (float)(equippedObject.Shade ?? 0.0));
                }
            }

            wo.PhysicsObj.UpdateObjDesc(objDesc);

            var r_PhysicsObj = new R_PhysicsObj(wo.PhysicsObj);

            Buffer.AddInstance(r_PhysicsObj, objDesc);

            if (!LoadedOnce)
            {
                //Camera.Position = Vector3.Zero;
                //Camera.Dir = Vector3.Normalize(new Vector3(1, 1, 0));

                Camera.Position = new Vector3(11.782367f, 12.763985f, 1.6514041f);
                Camera.Dir      = new Vector3(0.30761153f, -0.94673103f, 0.093334414f);
                Camera.Up       = Vector3.UnitZ;

                Camera.CreateLookAt();

                Camera.Speed = Camera.Model_Speed;
            }

            Buffer.BuildTextureAtlases(Buffer.InstanceTextureAtlasChains);
            Buffer.BuildBuffer(Buffer.RB_Instances);
            Server.InstancesLoaded = true;
            Server.Initting        = false;

            LoadedOnce = true;
        }
Beispiel #20
0
 protected override void CreateChildren()
 {
     texture = TextureCache.Get(Assets.BUFFS_SMALL);
     film    = new TextureFilm(texture, SIZE, SIZE);
 }
Beispiel #21
0
        internal void OnLoad()
        {
                        #if ANDROID
            Graphics = new OpenGLESApi();
                        #elif !USE_DX
            Graphics = new OpenGLApi(window);
                        #else
            Graphics = new Direct3D9Api(window);
                        #endif
            Graphics.MakeApiInfo();
            ErrorHandler.AdditionalInfo = Graphics.ApiInfo;

                        #if ANDROID
            Drawer2D = new CanvasDrawer2D(Graphics);
                        #else
            Drawer2D = new GdiPlusDrawer2D(Graphics);
                        #endif
            UpdateClientSize();

            Entities = new EntityList(this);
            TextureCache.Init();

                        #if SURVIVAL_TEST
            if (Options.GetBool(OptionsKey.SurvivalMode, false))
            {
                Mode = new SurvivalGameMode();
            }
            else
            {
                Mode = new CreativeGameMode();
            }
                        #endif

            Input           = new InputHandler(this);
            ParticleManager = new ParticleManager(); Components.Add(ParticleManager);
            TabList         = new TabList(); Components.Add(TabList);
            LoadOptions();
            LoadGuiOptions();
            Chat = new Chat(); Components.Add(Chat);

            WorldEvents.OnNewMap       += OnNewMapCore;
            WorldEvents.OnNewMapLoaded += OnNewMapLoadedCore;
            Events.TextureChanged      += TextureChangedCore;

            BlockInfo.Allocate(256);
            BlockInfo.Init();

            ModelCache = new ModelCache(this);
            ModelCache.InitCache();
            Downloader = new AsyncDownloader(Drawer2D); Components.Add(Downloader);
            Lighting   = new BasicLighting(); Components.Add(Lighting);

            Drawer2D.UseBitmappedChat = ClassicMode || !Options.GetBool(OptionsKey.UseChatFont, false);
            Drawer2D.BlackTextShadows = Options.GetBool(OptionsKey.BlackText, false);
            Graphics.Mipmaps          = Options.GetBool(OptionsKey.Mipmaps, false);

            Atlas1D.game  = this;
            Atlas2D.game  = this;
            Animations    = new Animations(); Components.Add(Animations);
            Inventory     = new Inventory(); Components.Add(Inventory);
            Inventory.Map = new BlockID[BlockInfo.Count];

            BlockInfo.SetDefaultPerms();
            World       = new World(this);
            LocalPlayer = new LocalPlayer(this); Components.Add(LocalPlayer);
            Entities.List[EntityList.SelfID] = LocalPlayer;

            MapRenderer        = new MapRenderer(this);
            ChunkUpdater       = new ChunkUpdater(this);
            EnvRenderer        = new EnvRenderer(); Components.Add(EnvRenderer);
            MapBordersRenderer = new MapBordersRenderer(); Components.Add(MapBordersRenderer);

            string renType = Options.Get(OptionsKey.RenderType, "normal");
            int    flags   = CalcRenderType(renType);
            if (flags == -1)
            {
                flags = 0;
            }

            MapBordersRenderer.legacy = (flags & 1) != 0;
            EnvRenderer.legacy        = (flags & 1) != 0;
            EnvRenderer.minimal       = (flags & 2) != 0;

            if (IPAddress == null)
            {
                Server = new Singleplayer.SinglePlayerServer(this);
            }
            else
            {
                Server = new Network.NetworkProcessor(this);
            }
            Components.Add(Server);
            Graphics.LostContextFunction = Server.Tick;

            Cameras.Add(new FirstPersonCamera(this));
            Cameras.Add(new ThirdPersonCamera(this, false));
            Cameras.Add(new ThirdPersonCamera(this, true));
            Camera = Cameras[0];
            UpdateProjection();

            Gui               = new GuiInterface(this); Components.Add(Gui);
            CommandList       = new CommandList(); Components.Add(CommandList);
            SelectionManager  = new SelectionManager(); Components.Add(SelectionManager);
            WeatherRenderer   = new WeatherRenderer(); Components.Add(WeatherRenderer);
            HeldBlockRenderer = new HeldBlockRenderer(); Components.Add(HeldBlockRenderer);

            Graphics.DepthTest = true;
            Graphics.DepthTestFunc(CompareFunc.LessEqual);
            //Graphics.DepthWrite = true;
            Graphics.AlphaBlendFunc(BlendFunc.SourceAlpha, BlendFunc.InvSourceAlpha);
            Graphics.AlphaTestFunc(CompareFunc.Greater, 0.5f);
            Culling           = new FrustumCulling();
            Picking           = new PickedPosRenderer(); Components.Add(Picking);
            AudioPlayer       = new AudioPlayer(); Components.Add(AudioPlayer);
            AxisLinesRenderer = new AxisLinesRenderer(); Components.Add(AxisLinesRenderer);
            SkyboxRenderer    = new SkyboxRenderer(); Components.Add(SkyboxRenderer);

            PluginLoader.game = this;
            List <string> nonLoaded = PluginLoader.LoadAll();

            for (int i = 0; i < Components.Count; i++)
            {
                Components[i].Init(this);
            }
            ExtractInitialTexturePack();
            for (int i = 0; i < Components.Count; i++)
            {
                Components[i].Ready(this);
            }
            InitScheduledTasks();

            if (nonLoaded != null)
            {
                for (int i = 0; i < nonLoaded.Count; i++)
                {
                    Overlay warning = new PluginOverlay(this, nonLoaded[i]);
                    Gui.ShowOverlay(warning, false);
                }
            }

            LoadIcon();
            string connectString = "Connecting to " + IPAddress + ":" + Port + "..";
            if (Graphics.WarnIfNecessary(Chat))
            {
                MapBordersRenderer.UseLegacyMode(true);
                EnvRenderer.UseLegacyMode(true);
            }
            Gui.SetNewScreen(new LoadingScreen(this, connectString, ""));
            Server.BeginConnect();
        }
Beispiel #22
0
        public void LoadModel(uint id, ClothingTable clothingBase, uint palTemplate, float shade)
        {
            TextureCache.Init();

            // can be either a gfxobj or setup id
            // if gfxobj, create a simple setup
            GfxObjMode = false;

            // create the objDesc, describing the "Changed" items to the base setup.
            // We won't bother loading the palette stuff, we'll just create that dictionary directly
            FileTypes.ObjDesc objDesc = new FileTypes.ObjDesc();

            var cbe = clothingBase.ClothingBaseEffects[id].CloObjectEffects;

            foreach (var objEffect in cbe)
            {
                ACE.DatLoader.Entity.AnimationPartChange apChange = new ACE.DatLoader.Entity.AnimationPartChange();
                apChange.PartID    = objEffect.ModelId;
                apChange.PartIndex = (byte)objEffect.Index;

                objDesc.AnimPartChanges.Add(apChange.PartIndex, apChange);

                foreach (var texEffect in objEffect.CloTextureEffects)
                {
                    ACE.DatLoader.Entity.TextureMapChange tmChange = new ACE.DatLoader.Entity.TextureMapChange();
                    tmChange.PartIndex  = apChange.PartIndex;
                    tmChange.OldTexture = texEffect.OldTexture;
                    tmChange.NewTexture = texEffect.NewTexture;

                    if (!objDesc.TextureChanges.TryGetValue(tmChange.PartIndex, out var tmChanges))
                    {
                        tmChanges = new List <ACE.DatLoader.Entity.TextureMapChange>();
                        objDesc.TextureChanges.Add(tmChange.PartIndex, tmChanges);
                    }
                    tmChanges.Add(tmChange);
                }
            }

            // To hold our Custom Palette (palette swaps)
            Dictionary <int, uint> customPaletteColors = new Dictionary <int, uint>();

            // Load all the custom palette colors...
            var subPalEffect = clothingBase.ClothingSubPalEffects[palTemplate];

            foreach (var subPals in subPalEffect.CloSubPalettes)
            {
                var  palSet = DatManager.PortalDat.ReadFromDat <PaletteSet>(subPals.PaletteSet);
                uint palId  = palSet.GetPaletteID(shade);
                // Load our palette dictated by the shade in the palset
                var palette = DatManager.PortalDat.ReadFromDat <Palette>(palId);
                foreach (var range in subPals.Ranges)
                {
                    int offset    = (int)(range.Offset);
                    int numColors = (int)(range.NumColors);
                    // add the appropriate colors to our custom palette
                    for (int i = 0; i < numColors; i++)
                    {
                        customPaletteColors.Add(i + offset, palette.Colors[i + offset]);
                    }
                }
            }

            Setup = new SetupInstance(id, objDesc, customPaletteColors);

            if (ViewObject == null || ViewObject.PhysicsObj.PartArray.Setup._dat.Id != id)
            {
                InitObject(id);

                Render.Camera.InitModel(Setup.Setup.BoundingBox);
            }
            else
            {
                ViewObject.PhysicsObj.destroy_particle_manager();
            }

            ModelType = ModelType.Setup;

            MainWindow.Status.WriteLine($"Loading {id:X8} with ClothingBase {clothingBase.Id:X8}, PaletteTemplate {palTemplate}, and Shade {shade}");
        }
Beispiel #23
0
        /// <summary>
        /// Default constructor
        /// </summary>
        /// <param name="client">A reference to the GridClient object</param>
        public AssetManager(LoggerInstance log, NetworkManager network)
        {
            Log = log;
            Network = network;
            Cache = new TextureCache(log, network, this);
            Texture = new TexturePipeline(log, network, this);

            // Transfer packets for downloading large assets
            Network.RegisterCallback(PacketType.TransferInfo, new NetworkManager.PacketCallback(TransferInfoHandler));
            Network.RegisterCallback(PacketType.TransferPacket, new NetworkManager.PacketCallback(TransferPacketHandler));

            // Xfer packets for uploading large assets
            Network.RegisterCallback(PacketType.RequestXfer, new NetworkManager.PacketCallback(RequestXferHandler));
            Network.RegisterCallback(PacketType.ConfirmXferPacket, new NetworkManager.PacketCallback(ConfirmXferPacketHandler));
            Network.RegisterCallback(PacketType.AssetUploadComplete, new NetworkManager.PacketCallback(AssetUploadCompleteHandler));

            // Xfer packet for downloading misc assets
            Network.RegisterCallback(PacketType.SendXferPacket, new NetworkManager.PacketCallback(SendXferPacketHandler));

            // Simulator is responding to a request to download a file
            Network.RegisterCallback(PacketType.InitiateDownload, new NetworkManager.PacketCallback(InitiateDownloadPacketHandler));

        }
Beispiel #24
0
 private void CacheInit()
 {
     imageCache = new ImageCache();
       textureCache = new TextureCache(imageCache, 0);
 }
Beispiel #25
0
        public bool update(ParameterList pl, SunflowAPI api)
        {
            updateBasis(pl.getVector("center", null), pl.getVector("up", null));
            numSamples = pl.getInt("samples", numSamples);

            string filename = pl.getstring("texture", null);

            if (filename != null)
            {
                texture = TextureCache.getTexture(api.resolveTextureFilename(filename), true);
            }

            // no texture provided
            if (texture == null)
            {
                return(false);
            }
            Bitmap b = texture.getBitmap();

            if (b == null)
            {
                return(false);
            }

            // rebuild histograms if this is a new texture
            if (filename != null)
            {
                imageHistogram = new float[b.Width][];
                for (int i = 0; i < imageHistogram.Length; i++)
                {
                    imageHistogram[i] = new float[b.Height];
                }
                colHistogram = new float[b.Width];
                float du = 1.0f / b.Width;
                float dv = 1.0f / b.Height;
                for (int x = 0; x < b.Width; x++)
                {
                    for (int y = 0; y < b.Height; y++)
                    {
                        float u = (x + 0.5f) * du;
                        float v = (y + 0.5f) * dv;
                        Color c = texture.getPixel(u, v);
                        // box filter the image
                        // c.add(texture.getPixel(u + du, v));
                        // c.add(texture.getPixel(u + du, v+ dv));
                        // c.add(texture.getPixel(u, v + dv));
                        // c.mul(0.25f);
                        imageHistogram[x][y] = c.getLuminance() * (float)Math.Sin(Math.PI * v);
                        if (y > 0)
                        {
                            imageHistogram[x][y] += imageHistogram[x][y - 1];
                        }
                    }
                    colHistogram[x] = imageHistogram[x][b.Height - 1];
                    if (x > 0)
                    {
                        colHistogram[x] += colHistogram[x - 1];
                    }
                    for (int y = 0; y < b.Height; y++)
                    {
                        imageHistogram[x][y] /= imageHistogram[x][b.Height - 1];
                    }
                }
                for (int x = 0; x < b.Width; x++)
                {
                    colHistogram[x] /= colHistogram[b.Width - 1];
                }
                jacobian = (float)(2 * Math.PI * Math.PI) / (b.Width * b.Height);
            }
            // take fixed samples
            if (pl.getbool("fixed", samples != null))
            {
                // Bitmap loc = new Bitmap(filename);
                samples = new Vector3[numSamples];
                colors  = new Color[numSamples];
                for (int i = 0; i < numSamples; i++)
                {
                    double randX = (double)i / (double)numSamples;
                    double randY = QMC.halton(0, i);
                    int    x     = 0;
                    while (randX >= colHistogram[x] && x < colHistogram.Length - 1)
                    {
                        x++;
                    }
                    float[] rowHistogram = imageHistogram[x];
                    int     y            = 0;
                    while (randY >= rowHistogram[y] && y < rowHistogram.Length - 1)
                    {
                        y++;
                    }
                    // sample from (x, y)
                    float u = (float)((x == 0) ? (randX / colHistogram[0]) : ((randX - colHistogram[x - 1]) / (colHistogram[x] - colHistogram[x - 1])));
                    float v = (float)((y == 0) ? (randY / rowHistogram[0]) : ((randY - rowHistogram[y - 1]) / (rowHistogram[y] - rowHistogram[y - 1])));

                    float px = ((x == 0) ? colHistogram[0] : (colHistogram[x] - colHistogram[x - 1]));
                    float py = ((y == 0) ? rowHistogram[0] : (rowHistogram[y] - rowHistogram[y - 1]));

                    float su = (x + u) / colHistogram.Length;
                    float sv = (y + v) / rowHistogram.Length;

                    float invP = (float)Math.Sin(sv * Math.PI) * jacobian / (numSamples * px * py);
                    samples[i] = getDirection(su, sv);
                    basis.transform(samples[i]);
                    colors[i] = texture.getPixel(su, sv).mul(invP);
                    // loc.setPixel(x, y, Color.YELLOW.copy().mul(1e6f));
                }
                // loc.save("samples.hdr");
            }
            else
            {
                // turn off
                samples = null;
                colors  = null;
            }
            return(true);
        }
Beispiel #26
0
 public FogTexture(int width2, int height2)
     : base(Android.Graphics.Bitmap.CreateBitmap(width2, height2, Android.Graphics.Bitmap.Config.Argb8888))
 {
     Filter(Linear, Linear);
     TextureCache.Add(typeof(FogOfWar), this);
 }
Beispiel #27
0
 public static void OnAwake()
 {
     WayPointMarker = TextureCache.GetTexture(Globals.RADIATION_ICON);
     PathNodeMarker = TextureCache.GetTexture(Globals.CIRCLE_ICON);
 }
    public override Color GetColor(Raytracer raytracer, Ray ray, RaycastHit hit, TraceData traceData)
    {
        Vector2 texCoord;
        Vector3 surfaceNormal;
        Vector3 tangent, binormal;
        bool    texCoordAndTangentRequired = NormalMap != null || DiffuseTexture != null || SpecularMap != null || ReflectionMap != null;

        texCoordAndTangentRequired = true;              // DEBUG

        if (texCoordAndTangentRequired)
        {
            Vector3 localNormal;
            Vector3 localTangent;

            ColliderUtils.GetTexCoordAndTangent(
                hit,
                out texCoord, out localNormal, out localTangent
                );

            tangent       = hit.collider.transform.TransformDirection(localTangent);
            surfaceNormal = hit.collider.transform.TransformDirection(localNormal);
            binormal      = Vector3.Cross(tangent, surfaceNormal);

            #region Debug Visualisation
#if DEBUG_SHOW_TEX_COORDS
            return(new Color(texCoord.x, texCoord.y, 0, 1));
#endif

#if DEBUG_SHOW_BARYCENTRIC_COORDS
            Vector3 dbgBc = hit.barycentricCoordinate;

            return(new Color(dbgBc.x, dbgBc.y, dbgBc.z, 1));
#endif

#if DEBUG_SHOW_NORMALS
            Vector3 dbgLocalNormal = localNormal;
            //dbgLocalNormal = new Vector3 (
            //	Mathf.Abs ( dbgLocalNormal.x ),
            //	Mathf.Abs ( dbgLocalNormal.y ),
            //	Mathf.Abs ( dbgLocalNormal.z )
            //);
            dbgLocalNormal = (dbgLocalNormal + Vector3.one) * 0.5f;

            return(new Color(dbgLocalNormal.x, dbgLocalNormal.y, dbgLocalNormal.z, 1));
#endif

#if DEBUG_SHOW_TANGENTS
            Vector3 dbgLocalTangent = localTangent;

            if (false)
            {
                dbgLocalTangent = new Vector3(
                    Mathf.Abs(dbgLocalTangent.x),
                    Mathf.Abs(dbgLocalTangent.y),
                    Mathf.Abs(dbgLocalTangent.z)
                    );
            }
            else if (false)
            {
                dbgLocalTangent = new Vector3(
                    Mathf.Abs(dbgLocalTangent.x > 0 ? dbgLocalTangent.x : 0),
                    Mathf.Abs(dbgLocalTangent.y > 0 ? dbgLocalTangent.y : 0),
                    Mathf.Abs(dbgLocalTangent.z > 0 ? dbgLocalTangent.z : 0)
                    );
            }
            else
            {
                dbgLocalTangent = (dbgLocalTangent + Vector3.one) * 0.5f;
            }

            return(new Color(dbgLocalTangent.x, dbgLocalTangent.y, dbgLocalTangent.z, 1));
#endif

#if DEBUG_SHOW_BINORMALS
            Vector3 localBinormal = Vector3.Cross(localTangent, localNormal);
            Vector3 dbgBinormal   = localBinormal;
            dbgBinormal = new Vector3(
                Mathf.Abs(dbgBinormal.x),
                Mathf.Abs(dbgBinormal.y),
                Mathf.Abs(dbgBinormal.z)
                );

            return(new Color(dbgBinormal.x, dbgBinormal.y, dbgBinormal.z, 1));
#endif
            #endregion Debug Visualisation
        }
        else
        {
            texCoord      = Vector2.zero;
            surfaceNormal = hit.normal;
            tangent       = Vector3.zero;
            binormal      = Vector3.zero;
        }

        bool entering = Vector3.Dot(hit.normal, ray.direction) <= 0;
        surfaceNormal = entering ? surfaceNormal : -surfaceNormal;

        /* TODO: revise where "entering" calculated upon hit.normal should be replaced
         * with "entering" calculated upon surfaceNormal transformed with TBN. */

        if (NormalMap != null && NormalMapInfluence > 0)
        {
            var     normalMapRt    = TextureCache.FromUnityTexture(NormalMap);
            Color   normalMapColor = normalMapRt.GetFilteredPixel(texCoord.x, texCoord.y);
            Vector3 texNormal      = new Vector3(normalMapColor.r, normalMapColor.g, normalMapColor.b);
            texNormal = 2 * texNormal - Vector3.one;
            texNormal.Normalize();
            Vector3 texNormalWorld = Raytracer.TransformTbn(texNormal, tangent, binormal, surfaceNormal);

            float normalMapInfluence = Mathf.Clamp01(NormalMapInfluence);
            surfaceNormal = Vector3.Lerp(surfaceNormal, texNormalWorld, normalMapInfluence).normalized;

#if DEBUG_SHOW_SURFACE_NORMALS
            Vector3 dbgSurfaceNormal = surfaceNormal;
            //dbgSurfaceNormal = new Vector3 (
            //	Mathf.Abs ( dbgSurfaceNormal.x ),
            //	Mathf.Abs ( dbgSurfaceNormal.y ),
            //	Mathf.Abs ( dbgSurfaceNormal.z )
            //);
            dbgSurfaceNormal = (dbgSurfaceNormal + Vector3.one) * 0.5f;

            return(new Color(dbgSurfaceNormal.x, dbgSurfaceNormal.y, dbgSurfaceNormal.z, 1));
#endif
        }

        float specularIntensity = SpecularComponent;

        if (SpecularMap != null && SpecularMapInfluence > 0 && specularIntensity > 0)
        {
            var   specularMapRt    = TextureCache.FromUnityTexture(SpecularMap);
            Color specularMapColor = specularMapRt.GetFilteredPixel(texCoord.x, texCoord.y);
            specularIntensity *= specularMapColor.grayscale * specularMapColor.a;

            float specularMapInfluence = Mathf.Clamp01(SpecularMapInfluence);
            specularIntensity = Mathf.Lerp(SpecularComponent, specularIntensity, specularMapInfluence);
        }

        Color totalColor           = Color.black;
        Color diffuseLightSumColor = raytracer.OverrideAmbientLight ? raytracer.AmbientLight : RenderSettings.ambientLight;
        diffuseLightSumColor *= DiffuseComponent;
        Color specularLightSumColor = Color.black;

        var lights = Light.GetLights(LightType.Point, 0);

        foreach (var light in lights)
        {
            Vector3 vToLight          = light.transform.position - hit.point;
            float   lightVolumeRadius = light.range * 0.00625f;                 // Empirical coefficient.
            float   distance          = vToLight.magnitude - lightVolumeRadius;

            if (distance < 0)
            {
                distance = 0;
            }
            else if (distance >= light.range)
            {
                continue;
            }

            Vector3 dirToLight = vToLight.normalized;
            float   attenuation;
            attenuation = 1 - distance / light.range;
            attenuation = attenuation * attenuation;

            float lightIntensity = light.intensity * LightIntensityFactor;

            if (DiffuseComponent > 0)
            {
                float diffuseIntensity = Vector3.Dot(dirToLight, surfaceNormal);

                if (diffuseIntensity > 0)
                {
                    diffuseIntensity = Mathf.Pow(diffuseIntensity, DiffuseExponent);
                    Color diffuseLightColor = light.color * attenuation * diffuseIntensity * lightIntensity;
                    diffuseLightSumColor += diffuseLightColor;
                }
            }

            if (specularIntensity > 0)
            {
                Vector3 reflectionDir = Vector3.Reflect(-dirToLight, surfaceNormal);
                Vector3 vToView       = raytracer.Camera.transform.position - hit.point;
                Vector3 dirToView     = vToView.normalized;
                float   specularity   = Vector3.Dot(reflectionDir, dirToView);

                if (specularity > 0)
                {
                    specularity = Mathf.Pow(specularity, SpecularPower);
                    Color specularLightColor = light.color * attenuation * specularity * lightIntensity;
                    specularLightSumColor += specularLightColor;
                }
            }
        }

        Color diffuseColor;

        if (DiffuseTexture != null)
        {
            var diffuseTextureRt = TextureCache.FromUnityTexture(DiffuseTexture);
            // TODO: calculate miplevel, get the color according to its value.
            Color texColor = diffuseTextureRt.GetFilteredPixel(texCoord.x, texCoord.y);

            if (texColor.a < 1 && DiffuseColorIsBackground)
            {
                diffuseColor = Color.Lerp(this.DiffuseColor, texColor, texColor.a);
            }
            else
            {
                diffuseColor = Color.Lerp(Color.black, texColor, texColor.a);
            }

            diffuseColor.a = texColor.a;
        }
        else
        {
            diffuseColor = this.DiffuseColor;
        }

        totalColor = diffuseLightSumColor * diffuseColor * DiffuseComponent + specularLightSumColor * specularIntensity;

        if (raytracer.MustInterrupt(totalColor, traceData))
        {
            return(totalColor);
        }

        bool  willReflect;
        float reflectionIntensity;

        if (entering)
        {
            willReflect         = ReflectionComponent > 0 && traceData.NumReflections < raytracer.MaxReflections;
            reflectionIntensity = ReflectionComponent;
        }
        else
        {
            willReflect         = InnerReflectionComponent > 0 && traceData.NumInnerReflections < raytracer.MaxInnerReflections;
            reflectionIntensity = InnerReflectionComponent;
        }

        if (willReflect && ReflectionMap != null && ReflectionMapInfluence > 0)
        {
            var   reflectionMapRt        = TextureCache.FromUnityTexture(ReflectionMap);
            Color reflectionMapColor     = reflectionMapRt.GetFilteredPixel(texCoord.x, texCoord.y);
            float reflectionMapIntensity = reflectionMapColor.grayscale * reflectionMapColor.a;

            float reflectionMapInfluence = Mathf.Clamp01(ReflectionMapInfluence);
            reflectionIntensity = Mathf.Lerp(reflectionIntensity, reflectionMapIntensity * reflectionIntensity, reflectionMapInfluence);

            willReflect = reflectionIntensity > 0;
        }

        float refractionIntensity = RefractionComponent;

        if (RefractWhereTranslucent)
        {
            refractionIntensity *= 1 - diffuseColor.a * DiffuseComponent;
        }

        bool      willRefract     = refractionIntensity > 0 && traceData.NumRefractions < raytracer.MaxRefractions;
        bool      forkingRequired = willReflect && willRefract;
        TraceData tdForRefraction;

        if (forkingRequired)
        {
            tdForRefraction = traceData.Fork();
        }
        else
        {
            tdForRefraction = traceData;
        }

        if (willReflect)
        {
            if (entering)
            {
                traceData.NumReflections++;
                traceData.Counters.Reflections++;
            }
            else
            {
                traceData.NumInnerReflections++;
                traceData.Counters.InnerReflections++;
            }

            Vector3 reflectionDir   = Vector3.Reflect(ray.direction, surfaceNormal);
            Vector3 pushedOutPoint  = hit.point + reflectionDir * Raytracer.PushOutMagnitude;
            Color   reflectionColor = raytracer.Trace(new Ray(pushedOutPoint, reflectionDir), traceData);
            totalColor += reflectionColor * reflectionIntensity;

            if (raytracer.MustInterrupt(totalColor, traceData))
            {
                return(totalColor);
            }
        }

        if (willRefract)
        {
            tdForRefraction.NumRefractions++;
            tdForRefraction.Counters.Refractions++;
            CoefficientOut = RefractionIndex;
            CoefficientIn  = 1 / RefractionIndex;

            if (CoefficientOut > 1)
            {
                CriticalOutAngleCos = Mathf.Sqrt(1 - CoefficientIn * CoefficientIn);
                CriticalInAngleCos  = 0;
            }
            else
            {
                CriticalOutAngleCos = 0;
                CriticalInAngleCos  = Mathf.Sqrt(1 - CoefficientOut * CoefficientOut);
            }

            float   criticalAngleCos = entering ? CriticalInAngleCos : CriticalOutAngleCos;
            Vector3 refractionDir;
            float   nDotRay = Vector3.Dot(surfaceNormal, ray.direction);

            if (Mathf.Abs(nDotRay) >= criticalAngleCos)
            {
                if (entering)
                {
                    tdForRefraction.PenetrationStack.Push(hit);
                }
                else
                {
                    tdForRefraction.PenetrationStack.Pop();
                }

                float k = entering ? CoefficientIn : CoefficientOut;
                refractionDir = Raytracer.Refract(ray.direction, surfaceNormal, nDotRay, k);
                refractionDir.Normalize();
            }
            else                // Total internal reflection.
            {
                refractionDir = Vector3.Reflect(ray.direction, surfaceNormal);
            }

            Vector3 pushedOutPoint  = hit.point + refractionDir * Raytracer.PushOutMagnitude;
            Color   refractionColor = raytracer.Trace(new Ray(pushedOutPoint, refractionDir), tdForRefraction);

            if (ColorAberration != 0 && entering)
            {
                //float rDotRay = Vector3.Dot ( refractionDir, ray.direction );
                refractionColor = HsvColor.ChangeHue(refractionColor, (1 + nDotRay) * ColorAberration);
            }

            totalColor += refractionColor * refractionIntensity;

            if (raytracer.MustInterrupt(totalColor, tdForRefraction))
            {
                return(totalColor);
            }
        }

        return(totalColor);
    }
Beispiel #29
0
 public PseudoPixel()
     : base(TextureCache.CreateSolid(Android.Graphics.Color.Argb(255, 255, 255, 255)))
 {
 }
Beispiel #30
0
 public virtual void Texture(object tx)
 {
     texture = tx is SmartTexture ? (SmartTexture)tx : TextureCache.Get(tx);
     Frame(new RectF(0, 0, 1, 1));
 }
Beispiel #31
0
 protected virtual void RenderCommands(SpriteBatch spriteBatch, TextureCache textureCache, IEnumerable<DrawCommand> drawList)
 {
     foreach (DrawCommand command in drawList) {
         Texture2D texture = textureCache.Resolve(command.Texture);
         if (texture != null)
             spriteBatch.Draw(texture, command.DestRect.ToXnaRectangle(), command.SourceRect.ToXnaRectangle(),
                 command.BlendColor.ToXnaColor(), command.Rotation, new Vector2(command.OriginX, command.OriginY),
                 SpriteEffects.None, 0f);
     }
 }
Beispiel #32
0
    //
    // Inheritance Methods
    //


    public void Init(MapController map, int layerId, TextureCache cache, MapboxRequestGenerator requestGenerator)
    {
        base.Init(map, layerId, cache);
        this.requestGenerator = requestGenerator;
    }
Beispiel #33
0
        /// <summary>
        /// Default constructor
        /// </summary>
        /// <param name="client">A reference to the GridClient object</param>
        public AssetManager(GridClient client)
        {
            Client = client;
            Cache = new TextureCache(client);

            // Transfer packets for downloading large assets
            Client.Network.RegisterCallback(PacketType.TransferInfo, new NetworkManager.PacketCallback(TransferInfoHandler));
            Client.Network.RegisterCallback(PacketType.TransferPacket, new NetworkManager.PacketCallback(TransferPacketHandler));

            // Image downloading packets
            Client.Network.RegisterCallback(PacketType.ImageData, new NetworkManager.PacketCallback(ImageDataHandler));
            Client.Network.RegisterCallback(PacketType.ImagePacket, new NetworkManager.PacketCallback(ImagePacketHandler));
            Client.Network.RegisterCallback(PacketType.ImageNotInDatabase, new NetworkManager.PacketCallback(ImageNotInDatabaseHandler));

            // Xfer packets for uploading large assets
            Client.Network.RegisterCallback(PacketType.RequestXfer, new NetworkManager.PacketCallback(RequestXferHandler));
            Client.Network.RegisterCallback(PacketType.ConfirmXferPacket, new NetworkManager.PacketCallback(ConfirmXferPacketHandler));
            Client.Network.RegisterCallback(PacketType.AssetUploadComplete, new NetworkManager.PacketCallback(AssetUploadCompleteHandler));

            // Xfer packet for downloading misc assets
            Client.Network.RegisterCallback(PacketType.SendXferPacket, new NetworkManager.PacketCallback(SendXferPacketHandler));

            // HACK: Re-request stale pending image downloads
            RefreshDownloadsTimer.Elapsed += new System.Timers.ElapsedEventHandler(RefreshDownloadsTimer_Elapsed);
            RefreshDownloadsTimer.Start();
        }
        public void EditEntry(int index, bool forceHex = false)
        {
            BundleEntry entry = GetEntry(index);

            if (EntryTypeRegistry.IsRegistered(entry.Type) && !forceHex)
            {
                IEntryData data = EntryTypeRegistry.GetHandler(entry.Type);

                TextureCache.ResetCache();
                LoadingDialog loader = new LoadingDialog();
                loader.Status = "Loading: " + entry.ID.ToString("X8");

                Thread loadInstanceThread = null;
                bool   failure            = false;

                loader.Done += (cancelled, value) =>
                {
                    if (cancelled)
                    {
                        loadInstanceThread?.Abort();
                    }
                    else
                    {
                        if (failure)
                        {
                            MessageBox.Show(this, "Failed to load Entry", "Error", MessageBoxButtons.OK,
                                            MessageBoxIcon.Error);
                        }
                        else
                        {
                            loader.Hide();

                            IEntryEditor editor = data.GetEditor(entry);
                            if (editor != null)
                            {
                                editor.ShowDialog(this);
                            }
                            else
                            {
                                DebugUtil.ShowDebug(this, data);
                            }
                            if (ForceOnlySpecificEntry)
                            {
                                Environment.Exit(0);
                            }
                        }
                    }
                    TextureCache.ResetCache();
                };

                loadInstanceThread = new Thread(() =>
                {
                    try
                    {
                        try
                        {
                            failure = !data.Read(entry, loader);
                        }
                        catch (ReadFailedError ex)
                        {
                            MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            failure = true;

                            throw;
                        }
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Failed to load Entry", "Error", MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                        failure = true;
                    }
                    loader.IsDone = true;
                });
                loadInstanceThread.Start();
                loader.ShowDialog(this);
            }
            else
            {
                EntryEditor editor = new EntryEditor();
                editor.ForceHex = forceHex;
                Task.Run(() => openEditor(editor, index));
                editor.ShowDialog(this);
            }
        }