Esempio n. 1
0
        private void Allocate(int capacityFactor)
        {
            if (hashmaps == null)
            {
                hashmaps = new NativeHashMap <TKey, int> [Capacities.Length];
            }
            if (blobHashmaps == null)
            {
                blobHashmaps = new BlobAssetReference <BlobHashMap <TKey, int> > [Capacities.Length];
            }
            if (keys == null)
            {
                keys = new NativeArray <TKey> [Capacities.Length];
            }

            hashMapResult     = new NativeArray <int>(1, Allocator.Persistent);
            blobHashMapResult = new NativeArray <int>(1, Allocator.Persistent);

            for (int i = 0; i < Capacities.Length; i++)
            {
                int capacity = Capacities[i];
                hashmaps[i] = new NativeHashMap <TKey, int>(capacity, Allocator.Persistent);

                BlobBuilder blobBuilder        = new BlobBuilder(Allocator.Temp);
                ref var     root               = ref blobBuilder.ConstructRoot <BlobHashMap <TKey, int> >();
                var         blobBuilderHashmap = blobBuilder.AllocateHashMap(ref root, capacity, capacityFactor);


                keys[i] = new NativeArray <TKey>(capacity * 2, Allocator.Persistent);
                Fill(keys[i], hashmaps[i], ref blobBuilderHashmap, capacity);

                // create the blob ref
                blobHashmaps[i] = blobBuilder.CreateBlobAssetReference <BlobHashMap <TKey, int> >(Allocator.Persistent);
            }
    public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
    {
        using (var builder = new BlobBuilder(Allocator.Temp)) {
            ref var root             = ref builder.ConstructRoot <BoardSetupBlobAsset>();
            var     tilePositions    = builder.Allocate(ref root.TilePositions, TilePositions.Length);
            var     dragonPositions  = builder.Allocate(ref root.DragonPositions, DragonPositions.Length);
            var     player1Positions = builder.Allocate(ref root.Player1Positions, Player1Positions.Length);
            var     player2Positions = builder.Allocate(ref root.Player2Positions, Player2Positions.Length);

            for (int i = 0; i < TilePositions.Length; i++)
            {
                tilePositions[i] = TilePositions[i];
            }
            for (int i = 0; i < DragonPositions.Length; i++)
            {
                dragonPositions[i] = DragonPositions[i];
            }
            for (int i = 0; i < Player1Positions.Length; i++)
            {
                player1Positions[i] = Player1Positions[i];
            }
            for (int i = 0; i < Player2Positions.Length; i++)
            {
                player2Positions[i] = Player2Positions[i];
            }

            dstManager.AddComponentData(entity, new BoardSetup {
                Reference = builder.CreateBlobAssetReference <BoardSetupBlobAsset>(Allocator.Persistent)
            });
        }
Esempio n. 3
0
    private unsafe BlobAssetReference <ControlPointsBlobData> CreateBlobData()
    {
        using (BlobBuilder builder = new BlobBuilder(Allocator.Temp))
        {
            //Allocate root
            ref ControlPointsBlobData blobRoot = ref builder.ConstructRoot <ControlPointsBlobData>();

            //Allocate array
            BlobBuilderArray <float3> controlPointArray = builder.Allocate(ref blobRoot.positions, m_serializedControlPoints.Length);

            //Fill in array values
            for (int i = 0; i < m_serializedControlPoints.Length; ++i)
            {
                controlPointArray[i] = m_serializedControlPoints[i].position;
            }

            //float3[] arr = new float3[4];

            //fixed (void* ptr = &arr[0])
            //{
            //    UnsafeUtility.MemCpy(controlPointArray.GetUnsafePtr(), ptr, arr.Length * sizeof(float3));
            //}

            return(builder.CreateBlobAssetReference <ControlPointsBlobData>(Allocator.Persistent));
        }
Esempio n. 4
0
        internal BlobAssetReference <LineBurst.Font> Convert()
        {
            using (var blobBuilder = new BlobBuilder(Allocator.Temp))
            {
                ref var a = ref blobBuilder.ConstructRoot <LineBurst.Font>();
                a.Width = Width;
                var ind = blobBuilder.Allocate(ref a.Indices, Glyphs.Length);
                var l   = blobBuilder.Allocate(ref a.Lines, TotalLines);

                var start     = 0;
                var lineIndex = 0;

                for (var i = 0; i < Glyphs.Length; i++)
                {
                    var glyph = Glyphs[i];
                    var end   = start + glyph.Lines.Length;
                    ind[i] = new int2(start, end);
                    start  = end;

                    for (var j = 0; j < glyph.Lines.Length; j++)
                    {
                        var line = glyph.Lines[j];
                        line.Org       = ToGlyphSpace(line.Org);
                        line.Dest      = ToGlyphSpace(line.Dest);
                        l[lineIndex++] = line;
                    }
                }

                return(blobBuilder.CreateBlobAssetReference <LineBurst.Font>(Allocator.Persistent));
            }
Esempio n. 5
0
        public unsafe void should_able_to_create_and_fetch_data_from_node_blob()
        {
            Debug.Log($"sizeof NodeA: {sizeof(NodeA.Data)}");
            Debug.Log($"sizeof NodeB: {sizeof(NodeB.Data)}");

            var size = sizeof(NodeA.Data) + sizeof(NodeB.Data);

            using (var blobBuilder = new BlobBuilder(Allocator.Temp))
            {
                ref var blob = ref blobBuilder.ConstructRoot <NodeBlob>();

                var endIndices = blobBuilder.Allocate(ref blob.EndIndices, 3);
                endIndices[0] = 3;
                endIndices[1] = 2;
                endIndices[2] = 3;

                var offsets   = blobBuilder.Allocate(ref blob.Offsets, 3);
                var unsafePtr = (byte *)blobBuilder.Allocate(ref blob.DefaultDataBlob, size).GetUnsafePtr();
                var offset    = 0;
                offsets[0] = offset;
                offsets[1] = offset;
                UnsafeUtilityEx.AsRef <NodeA.Data>(unsafePtr + offset).A = 111;
                offset    += sizeof(NodeA.Data);
                offsets[2] = offset;
                ref var local2 = ref UnsafeUtilityEx.AsRef <NodeB.Data>(unsafePtr + offset);
        internal static BlobAssetReference <FontData> ConvertFontData(TMPro.TMP_FontAsset font, Allocator allocatorType = Allocator.Persistent)
        {
            if (font.glyphLookupTable == null)
            {
                throw new InvalidOperationException("Reading font resulted in null glyph lookup table?");
            }

            using (var allocator = new BlobBuilder(Allocator.Temp))
            {
                ref var root = ref allocator.ConstructRoot <FontData>();

                root.Atlas.AtlasSize = new int2(font.atlasWidth, font.atlasHeight);

                root.Face.Ascent     = font.faceInfo.ascentLine;
                root.Face.Descent    = font.faceInfo.descentLine;
                root.Face.Baseline   = font.faceInfo.baseline;
                root.Face.Scale      = font.faceInfo.scale;
                root.Face.PointSize  = font.faceInfo.pointSize;
                root.Face.LineHeight = font.faceInfo.lineHeight;

                // TODO we are smooshing chars and glyphs; multiple chars can map to
                // the same glyph.  This might not be the best thing.
                int charCount = font.characterTable.Count;

                var glyphs = allocator.Allocate(ref root.Glyphs, charCount);

                // TODO why did I want a separate glyphRects?
                var glyphRects = allocator.Allocate(ref root.GlyphRects, charCount);

                var atlasSize = new float2(font.atlasWidth, font.atlasHeight);

                for (int i = 0; i < charCount; ++i)
                {
                    var c = font.characterTable[i];

                    glyphs[i] = new GlyphInfo
                    {
                        Unicode           = c.unicode,
                        Size              = new float2(c.glyph.metrics.width, c.glyph.metrics.height),
                        HorizontalBearing = new float2(c.glyph.metrics.horizontalBearingX, c.glyph.metrics.horizontalBearingY),
                        HorizontalAdvance = c.glyph.metrics.horizontalAdvance
                    };

                    // UVs in Tiny rendering are flipped from Unity's orientation.
                    // glyphPos is the top-left coord.
                    int2 glyphPos  = new int2(c.glyph.glyphRect.x, font.atlasHeight - (c.glyph.glyphRect.y + c.glyph.glyphRect.height));
                    int2 glyphSize = new int2(c.glyph.glyphRect.width, c.glyph.glyphRect.height);

                    glyphRects[i] = new GlyphRect
                    {
                        Position      = glyphPos,
                        Size          = glyphSize,
                        TopLeftUV     = glyphPos / atlasSize,
                        BottomRightUV = (glyphPos + glyphSize) / atlasSize,
                    };
                }

                return(allocator.CreateBlobAssetReference <FontData>(allocatorType));
            }
 public static BlobAssetReference <MarchingTables> CreateBlobAssetReference(Allocator allocator = Allocator.Persistent)
 {
     using (var builder = new BlobBuilder(Allocator.Temp))
     {
         Initialize(ref builder.ConstructRoot <MarchingTables>(), builder);
         return(builder.CreateBlobAssetReference <MarchingTables>(allocator));
     }
 }
Esempio n. 8
0
        Main(IReadOnlyDictionary <int, int> idIndex, NativeHashMap <int, int> stateLookup,
             IReadOnlyDictionary <int, Entity> provEntityLookup)
        {
            var slicedText = File.ReadLines(Path.Combine(Application.streamingAssetsPath, "map", "region.txt"),
                                            Encoding.GetEncoding(1252));

            var stateIdNames     = new List <string>();
            var stateLookupArray = new List <List <int> >();

            foreach (var rawLine in slicedText)
            {
                if (CommentDetector(rawLine, out var line))
                {
                    continue;
                }

                var stateProvinces = new List <int>();

                var choppedLine = line.Split(new[] { '{', '}' }, StringSplitOptions.RemoveEmptyEntries);
                // 0. StateId = | 1. Prov 1 Prov 2 Prov 3... | 2. #StateName

                var innerChopped = choppedLine[1].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var colorNum in innerChopped)
                {
                    if (!int.TryParse(colorNum, out var lookupNum))
                    {
                        throw new Exception("Invalid province ID. Must be int number.");
                    }

                    var provId = idIndex[lookupNum];
                    stateLookup.Add(provId, stateIdNames.Count);
                    stateProvinces.Add(provId);
                }

                stateLookupArray.Add(stateProvinces);

                stateIdNames.Add(Regex.Match(choppedLine[0], @"^.+?(?=\=)").Value.Trim());
            }

            // Creating state to prov blob lookup nested array
            BlobAssetReference <StateToProv> stateToProvReference;

            using (var stateToProv = new BlobBuilder(Allocator.Temp))
            {
                ref var lookupStruct = ref stateToProv.ConstructRoot <StateToProv>();

                var stateArray = stateToProv.Allocate(ref lookupStruct.Lookup, stateLookupArray.Count);
                for (var state = 0; state < stateLookupArray.Count; state++)
                {
                    var provArray = stateToProv.Allocate(ref stateArray[state], stateLookupArray[state].Count);
                    for (var i = 0; i < stateLookupArray[state].Count; i++)
                    {
                        provArray[i] = provEntityLookup[stateLookupArray[state][i]];
                    }
                }

                stateToProvReference = stateToProv.CreateBlobAssetReference <StateToProv>(Allocator.Persistent);
            }
Esempio n. 9
0
    // Update is called once per frame
    void Update()
    {
        if (!musicPlayer.isPlaying)
        {
            return;
        }

        int sampleValue = Mathf.ClosestPowerOfTwo((int)Mathf.Pow(SampleCount, 2f));

        if (sampleValue != lastSampleCount)
        {
            ShutdownVisuals();
            lastSampleCount = sampleValue;
            lastSampleData  = new float[lastSampleCount];
            SetUpVisuals(sampleValue * musicClip.channels, sampleValue);
        }

#if DOTS
        // if(!SampleData.IsCreated)
        // {
        //     Debug.Log("SampleData is Null");
        //     return;
        // }

        int arrayLength = SampleData.Value.sampleArray.Length;

        if (arrayLength != lastSampleCount * musicClip.channels)
        {
            //TODO: Resize the Blob array
            arrayLength = lastSampleCount * musicClip.channels;

            //Dispose of the old blob array
            SampleData.Dispose();

            using (BlobBuilder blobBuilder = new BlobBuilder(Allocator.Temp))
            {
                ref MusicDataBlobAsset musicDataBlobAsset = ref blobBuilder.ConstructRoot <MusicDataBlobAsset>();

                BlobBuilderArray <MusicSample> musicDataArray = blobBuilder.Allocate(ref musicDataBlobAsset.sampleArray, arrayLength);

                //Setup array data
                for (int i = 0; i < arrayLength; i++)
                {
                    musicDataArray[i] = new MusicSample {
                        Value = 0
                    };
                }

                SampleData = blobBuilder.CreateBlobAssetReference <MusicDataBlobAsset>(Allocator.Persistent);

                for (int i = 0; i < entityVisualizers.Length; i++)
                {
                    var viz = entityManager.GetComponentData <VisualizerData>(entityVisualizers[i]);
                    viz.MusicData = SampleData;
                    entityManager.SetComponentData <VisualizerData>(entityVisualizers[i], viz);
                }
            }
        }
Esempio n. 10
0
        public void should_build_complex_data_into_blob()
        {
            var builder = new BlobBuilder(Allocator.Temp);

            try
            {
                ref var variant = ref builder.ConstructRoot <BlobVariant>();
                variant.VariantId = 1;
                ref var blobPtr = ref UnsafeUtility.As <int, BlobPtr <Data> >(ref variant.MetaDataOffsetPtr);
Esempio n. 11
0
        public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
        {
            var builder = new BlobBuilder(Allocator.Temp);

            builder.ConstructRoot <int>() = Version;
            dstManager.AddComponentData(entity, new Component
            {
                BlobAssetRef = builder.CreateBlobAssetReference <int>(Allocator.Persistent)
            });
        }
Esempio n. 12
0
        public static BlobAssetReference <QuadTree> CreateBlobAssetReference()
        {
            using (var builder = new BlobBuilder(Allocator.Temp)) {
                ref var rootQuadTree = ref builder.ConstructRoot <QuadTree>();

                var colliders = builder.Allocate(ref rootQuadTree.Colliders, 2);
                LineCollider.Create(builder, ref colliders[0], new float2(1f, 20f), new float2(3f, 4f), 5f, 6f);
                PointCollider.Create(builder, ref colliders[1], new float3(7f, 8f, 9f));

                return(builder.CreateBlobAssetReference <QuadTree>(Allocator.Persistent));
            }
 private BlobAssetReference <Float3Array> SegmentPositions(Transform[] targets)
 {
     using (var builder = new BlobBuilder(Allocator.Temp))
     {
         ref var root  = ref builder.ConstructRoot <Float3Array>();
         var     array = builder.Allocate(ref root.Value, targets.Length);
         for (int i = 0; i < targets.Length; i++)
         {
             array[i] = targets[i].transform.localPosition;
         }
         return(builder.CreateBlobAssetReference <Float3Array>(Allocator.Persistent));
     }
 BlobAssetReference <IntArray> GeneratorIntArr(int[] baseData)
 {
     using (var builder = new BlobBuilder(Allocator.Temp))
     {
         ref var root   = ref builder.ConstructRoot <IntArray>();
         var     refArr = builder.Allocate(ref root.ArrayData, baseData.Length);
         for (int i = 0; i < baseData.Length; i++)
         {
             refArr[i] = baseData[i];
         }
         return(builder.CreateBlobAssetReference <IntArray>(Allocator.Persistent));
     }
Esempio n. 15
0
 public static BlobAssetReference <FloatArray> AllocateFloatArray(params float[] values)
 {
     using (var builder = new BlobBuilder(Allocator.Temp))
     {
         ref var root  = ref builder.ConstructRoot <FloatArray>();
         var     array = builder.Allocate(ref root.Value, values.Length);
         for (int i = 0; i < values.Length; i++)
         {
             array[i] = values[i];
         }
         return(builder.CreateBlobAssetReference <FloatArray>(Allocator.Persistent));
     }
 private BlobAssetReference <ItemDataSet> BuildItemDataSet(ItemData[] srcItemData)
 {
     using (var builder = new BlobBuilder(Allocator.Temp))
     {
         ref var root        = ref builder.ConstructRoot <ItemDataSet>();
         var     dstItemData = builder.Allocate(ref root.ItemDatas, srcItemData.Length);
         for (var i = 0; i < dstItemData.Length; i++)
         {
             dstItemData[i] = srcItemData[i];
         }
         return(builder.CreateBlobAssetReference <ItemDataSet>(Allocator.Persistent));
     }
Esempio n. 17
0
 public static BlobAssetReference <SampledAnimationCurve> ConstructBlobAssetReference(AnimationCurve curve, int samples = 255, float time = 1.0f)
 {
     using (var blobBuilder = new BlobBuilder(Allocator.Temp))
     {
         ref var root = ref blobBuilder.ConstructRoot <SampledAnimationCurve>();
         var     keys = blobBuilder.Allocate(ref root.keys, samples);
         var     step = time / (samples - 1);
         for (int i = 0; i < samples; ++i)
         {
             keys[i] = curve.Evaluate(i * step);
         }
         return(blobBuilder.CreateBlobAssetReference <SampledAnimationCurve>(Allocator.Persistent));
     }
Esempio n. 18
0
        static public BlobAssetReference <MotionBlobData> ConvertToBlobData(this MotionClip motionClip)
        {
            using (var builder = new BlobBuilder(Allocator.Temp))
            {
                var srcMotions = motionClip.MotionData.Motions;

                ref var dstRoot = ref builder.ConstructRoot <MotionBlobData>();
                copyMotionToBlob(ref motionClip.MotionData, ref dstRoot, builder);

                //makeBoneIds( motionClip.StreamPaths, ref dstRoot, builder );

                return(builder.CreateBlobAssetReference <MotionBlobData>(Allocator.Persistent));
            }
        public static BlobAssetReference <BakedAnimationClipSet> CreateClipSet(KeyframeTextureBaker.BakedData data)
        {
            using (var builder = new BlobBuilder(Allocator.Temp))
            {
                ref var root  = ref builder.ConstructRoot <BakedAnimationClipSet>();
                var     clips = builder.Allocate(data.Animations.Count, ref root.Clips);
                for (int i = 0; i != data.Animations.Count; i++)
                {
                    clips[i] = new BakedAnimationClip(data.AnimationTextures, data.Animations[i]);
                }

                return(builder.CreateBlobAssetReference <BakedAnimationClipSet>(Allocator.Persistent));
            }
Esempio n. 20
0
 public static BlobAssetReference <SampledGradient> ConstructBlobAssetReference(Gradient gradient, int samples = 255)
 {
     using (var blobBuilder = new BlobBuilder(Allocator.Temp))
     {
         ref var root = ref blobBuilder.ConstructRoot <SampledGradient>();
         var     keys = blobBuilder.Allocate(ref root.keys, samples);
         var     step = 1.0f / (samples - 1);
         for (int i = 0; i < samples; ++i)
         {
             keys[i] = graphx.rgba(gradient.Evaluate(i * step));
         }
         root.samples = samples;
         return(blobBuilder.CreateBlobAssetReference <SampledGradient>(Allocator.Persistent));
     }
Esempio n. 21
0
        public BlobAssetReference Build(ITreeNode <INodeDataBuilder>[] builders)
        {
            var minSize = UnsafeUtility.SizeOf <T>();

            if (minSize == 0)
            {
                return(BlobAssetReference.Null);
            }
            using (var blobBuilder = new BlobBuilder(Allocator.Temp, minSize))
            {
                ref var data = ref blobBuilder.ConstructRoot <T>();
                Build(blobBuilder, ref data, builders);
                return(blobBuilder.CreateReference <T>());
            }
        public static BlobAssetReference <WaypointBlobs> ConstructBlobdata()
        {
            using (var builder = new BlobBuilder(Allocator.Temp))
            {
                ref var root = ref builder.ConstructRoot <WaypointBlobs>();

                var nodearray = builder.Allocate(ref root.Waypoints, 3);

                nodearray[0] = new float3(0, 0, 0);
                nodearray[1] = new float3(100, 100, 100);
                nodearray[2] = new float3(200, 200, 200);

                return(builder.CreateBlobAssetReference <WaypointBlobs>(Allocator.Persistent));
            }
        public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
        {
            using (BlobBuilder blobBuilder = new BlobBuilder(Allocator.Temp))
            {
                ref BulletPrefabBlobAsset bulletBlob = ref blobBuilder.ConstructRoot <BulletPrefabBlobAsset>();
                BlobBuilderArray <Entity> bulletArr  = blobBuilder.Allocate(ref bulletBlob.bulletPrefab, bulletPrefab.Length);

                for (int i = 0; i < bulletPrefab.Length; i++)
                {
                    bulletArr[i] = conversionSystem.GetPrimaryEntity(bulletPrefab[i]);
                }

                dstManager.World.GetExistingSystem <BulletSpawnSystem>().bulletDataBlob = blobBuilder.CreateBlobAssetReference <BulletPrefabBlobAsset>(Allocator.Persistent);
            }
Esempio n. 24
0
        /// <summary>
        /// Replicate all keyframes of <paramref name="animationCurve"> into the struct,
        /// making this independent from the original reference type curve.
        /// </summary>
        public JobAnimationCurve(AnimationCurve animationCurve, Allocator allocator)
        {
            List <Keyframe> sortedKeyframes = new List <Keyframe>(animationCurve.keys);

            if (sortedKeyframes.Any(x => x.weightedMode != WeightedMode.None))
            {
                throw new NotSupportedException($"Found a keyframe in the curve that has a weighted node. This is not supported until I figured out where to put the weight.");
            }
            sortedKeyframes.Sort(KeyframeTimeSort);

            //Debug.Log(string.Join("\n", sortedKeyframes.Select(x => $"{x.time} {x.value} | {x.inTangent} {x.outTangent} | {x.inWeight} {x.outWeight} {x.weightedMode}")));

            var sortedTimes = sortedKeyframes.Select(x => x.time).ToArray();

            // The following (redundant) leading comments are the steps from BlobBuilder's
            // documentation https://docs.unity3d.com/Packages/[email protected]/api/Unity.Entities.BlobBuilder.html
            // Create a BlobBuilder object
            using (var builder = new BlobBuilder(allocator))
            {
                // Call the ConstructRoot<T>() method, where T is the struct definng the asset structure.
                // (Declare the structure of the blob asset as a struct.)
                ref var root = ref builder.ConstructRoot <AnimationData>();

                // Initialize primitive values defined at the root level of the asset.
                // Allocate memory for arrays, structs, and BlobString instances at the root.

                // Used to use the processor count to assume the max thread count, which is a fallacy
                // int processorCount = SystemInfo.processorCount + 1;
                int maxThreadCount = Unity.Jobs.LowLevel.Unsafe.JobsUtility.MaxJobThreadCount;
                var keyframes      = builder.Allocate(ref root.keyframes, sortedKeyframes.Count);
                var soaTimes       = builder.Allocate(ref root.soaTimes, sortedKeyframes.Count);
                var cachedIndex    = builder.Allocate(ref root.cachedIndex, maxThreadCount);

                // Initialize the values of those arrays, structs, and strings.
                for (int i = 0; i < sortedKeyframes.Count; i++)
                {
                    keyframes[i] = sortedKeyframes[i];
                    soaTimes[i]  = sortedTimes[i];
                }
                for (int i = 0; i < maxThreadCount; i++)
                {
                    cachedIndex[i] = 0;
                }
                // Continue allocating memory and initializing values until you have fully constructed the asset.

                // Call CreateBlobAssetReference<T>(Allocator) to create a reference to the blob asset in memory.
                bar = builder.CreateBlobAssetReference <AnimationData>(allocator);

                // Dispose the BlobBuilder object.
            }
        public static void Create(EntityManager entityManager, out NativeHashMap <Entity, bool> itemsColliding)
        {
            PerfMarkerTotal.Begin();

            var player             = Object.FindObjectOfType <Player>();
            var playfieldComponent = player.GetComponentInChildren <PlayfieldComponent>();
            var itemApis           = player.ColliderGenerators.ToArray();

            // 1. generate colliders
            PerfMarkerGenerateColliders.Begin();
            var colliderList = new List <ICollider>();

            var(playfieldCollider, glassCollider) = player.PlayfieldApi.CreateColliders();
            itemsColliding = new NativeHashMap <Entity, bool>(itemApis.Length, Allocator.Persistent);
            foreach (var itemApi in itemApis)
            {
                PerfMarkerCreateColliders.Begin();
                if (itemApi.ColliderEntity != Entity.Null)
                {
                    itemsColliding.Add(itemApi.ColliderEntity, itemApi.IsColliderEnabled);
                }
                itemApi.CreateColliders(colliderList, 0);
                PerfMarkerCreateColliders.End();
            }
            PerfMarkerGenerateColliders.End();

            // 2. allocate created colliders
            PerfMarkerCreateBlobAsset.Begin();
            var allocateColliderJob = new ColliderAllocationJob(colliderList, playfieldCollider, glassCollider);

            allocateColliderJob.Run();

            // retrieve result and dispose
            var colliderBlobAssetRef = allocateColliderJob.BlobAsset[0];

            allocateColliderJob.Dispose();
            PerfMarkerCreateBlobAsset.End();

            // 3. Create quadtree blob (BlobAssetReference<QuadTreeBlob>) from AABBs
            PerfMarkerCreateQuadTree.Begin();
            BlobAssetReference <QuadTreeBlob> quadTreeBlobAssetRef;

            using (var builder = new BlobBuilder(Allocator.Temp)) {
                ref var rootQuadTree = ref builder.ConstructRoot <QuadTreeBlob>();
                QuadTree.Create(builder, ref colliderBlobAssetRef.Value.Colliders, ref rootQuadTree.QuadTree,
                                playfieldComponent.BoundingBox.ToAabb());

                quadTreeBlobAssetRef = builder.CreateBlobAssetReference <QuadTreeBlob>(Allocator.Persistent);
            }
        private void Start()
        {
            using (var reader = new StringReader(m_iniContents))
            {
                var builder = new BlobBuilder(Allocator.Temp);
                BlobAssetReference <IniFile> configReference;

                try
                {
                    ref IniFile root = ref builder.ConstructRoot <IniFile>();

                    builder.AllocateString(ref root.Name, m_fileName);

                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        string[] pairStr = line.Split('=');
                        if (pairStr.Length != 2 || string.IsNullOrEmpty(pairStr[0]))
                        {
                            continue;
                        }

                        switch (pairStr[0])
                        {
                        case "foo":
                            int.TryParse(pairStr[1], out root.Foo);
                            break;

                        case "bar":
                            if (root.Bar.Length != 0)
                            {
                                continue;
                            }
                            builder.AllocateString(ref root.Bar, pairStr[1]);
                            break;

                        case "baz":
                            float.TryParse(pairStr[1], out root.Baz);
                            break;

                        case "qux":
                            Enum.TryParse(pairStr[1], true, out root.Qux);
                            break;
                        }
                    }

                    configReference = builder.CreateBlobAssetReference <IniFile>(Allocator.Persistent);
                }
        public static BlobAssetReference <ColliderBlob> CreateBlobAssetReference(List <HitObject> hitObjects, int playfieldColliderId, int glassColliderId)
        {
            using (var builder = new BlobBuilder(Allocator.Temp)) {
                ref var root      = ref builder.ConstructRoot <ColliderBlob>();
                var     colliders = builder.Allocate(ref root.Colliders, hitObjects.Count);

                foreach (var hitObject in hitObjects)
                {
                    Collider.Create(builder, hitObject, ref colliders[hitObject.Id]);
                }

                root.PlayfieldColliderId = playfieldColliderId;
                root.GlassColliderId     = glassColliderId;

                return(builder.CreateBlobAssetReference <ColliderBlob>(Allocator.Persistent));
            }
    public static AudioClipCache FromResources(AudioClip[] gameObjects)
    {
        BlobAssetReference <AudioClipCacheBlobAsset> reference;

        using (var builder = new BlobBuilder(Allocator.Temp)) {
            ref var root      = ref builder.ConstructRoot <AudioClipCacheBlobAsset>();
            var     clipPairs = builder.Allocate(ref root.AudioClipPairs, gameObjects.Length);

            for (int i = 0; i < gameObjects.Length; i++)
            {
                Debug.Log($"Adding Prefab {gameObjects[i].name} with ID {gameObjects[i].GetInstanceID()} to AudioClipCache.");
                clipPairs[i] = new AudioClipPair(gameObjects[i].Hash(), gameObjects[i]);
            }
            reference = builder.CreateBlobAssetReference <AudioClipCacheBlobAsset>(Allocator.Persistent);
            Debug.Log($"{clipPairs.Length} total items in cache");
        }
Esempio n. 29
0
        public static BlobAssetReference <QuadTreeBlob> CreateBlobAssetReference(HitQuadTree hitQuadTree, HitPlane playfield, HitPlane glass)
        {
            using (var builder = new BlobBuilder(Allocator.Temp)) {
                ref var rootQuadTree = ref builder.ConstructRoot <QuadTreeBlob>();
                QuadTree.Create(hitQuadTree, ref rootQuadTree.QuadTree, builder);

                if (playfield != null)
                {
                    PlaneCollider.Create(builder, playfield, ref rootQuadTree.PlayfieldCollider);
                }
                else
                {
                    ref var playfieldCollider = ref builder.Allocate(ref rootQuadTree.PlayfieldCollider);
                    playfieldCollider.Header = new ColliderHeader {
                        Type = ColliderType.None
                    };
                }
Esempio n. 30
0
 private static unsafe BlobAssetReference <PrecompiledShaderData> AddShaderData(EntityManager em, Entity e, ShaderType type, bgfx.RendererType[] types, string prefix)
 {
     using (var allocator = new BlobBuilder(Allocator.Temp))
     {
         ref var root = ref allocator.ConstructRoot <PrecompiledShaderData>();
         foreach (bgfx.RendererType sl in types)
         {
             string path       = Path.GetFullPath(kBinaryShaderFolderPath);
             string fsFileName = GetShaderFileName(prefix, type.ToString(), sl.ToString()).ToLower();
             using (var data = new NativeArray <byte>(File.ReadAllBytes(Path.Combine(path, fsFileName)), Allocator.Temp))
             {
                 byte *dest = (byte *)(allocator.Allocate(ref root.DataForBackend(sl), data.Length).GetUnsafePtr());
                 UnsafeUtility.MemCpy(dest, (byte *)data.GetUnsafePtr(), data.Length);
             }
         }
         return(allocator.CreateBlobAssetReference <PrecompiledShaderData>(Allocator.Persistent));
     }