Beispiel #1
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));
            }
    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)
            });
        }
Beispiel #3
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));
            }
Beispiel #5
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);
            }
        public static void Create(HitQuadTree src, ref QuadTree dest, BlobBuilder builder)
        {
            var children = builder.Allocate(ref dest.Children, 4);

            for (var i = 0; i < 4; i++)
            {
                if (src.Children[i] != null)
                {
                    ref var child = ref builder.Allocate(ref children[i]);
                    Create(src.Children[i], ref child, builder);
                }
            }
Beispiel #7
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.
            }
Beispiel #8
0
        protected override void AllocateData(ref BlobBuilder builder, ref BlobVariable <T> blobVariable)
        {
            var data = Utility.GetTypeHashAndFieldOffset(ComponentValueName);

            if (data.Type != typeof(T) || data.Hash == 0)
            {
                Debug.LogError($"ComponentVariable({ComponentValueName}) is not valid, fallback to ConstantValue");
                builder.Allocate(ref blobVariable, FallbackValue);
                return;
            }
            builder.Allocate(ref blobVariable, new DynamicComponentData {
                StableHash = data.Hash, Offset = data.Offset
            });
        }
Beispiel #9
0
        public override void Allocate(ref BlobBuilder builder, ref BlobVariable <T> blobVariable, INodeDataBuilder self, ITreeNode <INodeDataBuilder>[] tree)
        {
            var index = Array.FindIndex(tree, node => ReferenceEquals(node.Value, NodeObject));

            if (!NodeObject || index < 0)
            {
                Debug.LogError($"Invalid `NodeObject` {NodeObject}", (UnityEngine.Object)self);
                throw new ArgumentException();
            }

            var nodeType = VirtualMachine.GetNodeType(NodeObject.NodeId);

            if (string.IsNullOrEmpty(ValueFieldName) && nodeType == typeof(T))
            {
                builder.Allocate(ref blobVariable, new DynamicNodeRefData {
                    Index = index, Offset = 0
                });
                return;
            }

            var fieldInfo = nodeType.GetField(ValueFieldName, FIELD_BINDING_FLAGS);

            if (fieldInfo == null)
            {
                Debug.LogError($"Invalid `ValueFieldName` {ValueFieldName}", (UnityEngine.Object)self);
                throw new ArgumentException();
            }

            var fieldOffset = Marshal.OffsetOf(nodeType, ValueFieldName).ToInt32();

            builder.Allocate(ref blobVariable, new DynamicNodeRefData {
                Index = index, Offset = fieldOffset
            });

            var fieldType = fieldInfo.FieldType;

            if (fieldType == typeof(T))
            {
                blobVariable.VariableId = AccessRuntimeData ? _ID_RUNTIME_NODE : _ID_DEFAULT_NODE;
            }
            else if (fieldType == typeof(BlobVariable <T>))
            {
                blobVariable.VariableId = AccessRuntimeData ? _ID_RUNTIME_NODE_VARIABLE : _ID_DEFAULT_NODE_VARIABLE;
            }
            else
            {
                Debug.LogError($"Invalid type of `ValueFieldName` {ValueFieldName} {fieldType}", (UnityEngine.Object)self);
                throw new ArgumentException();
            }
        }
            public IntPtr Allocate(ref BlobBuilder builder, ref BlobVariant blobVariant)
            {
                blobVariant.VariantId = GuidHashCode(GUID);
                var          type         = ScriptableObject.GetType();
                FieldInfo    fieldInfo    = null;
                PropertyInfo propertyInfo = null;

                if (ScriptableObject != null)
                {
                    fieldInfo = type.GetField(ScriptableObjectValueName, BindingFlags.Instance | BindingFlags.Public);
                }
                if (fieldInfo == null)
                {
                    propertyInfo = type.GetProperty(ScriptableObjectValueName, BindingFlags.Instance | BindingFlags.Public);
                }

                if ((fieldInfo == null || fieldInfo.FieldType != typeof(T)) &&
                    (propertyInfo == null || !propertyInfo.CanRead || propertyInfo.PropertyType != typeof(T)))
                {
                    Debug.LogError($"{ScriptableObject.name}.{ScriptableObjectValueName} is not valid");
                    throw new ArgumentException();
                }

                var value = fieldInfo?.GetValue(ScriptableObject) ?? propertyInfo?.GetValue(ScriptableObject);

                return(builder.Allocate(ref blobVariant, (T)value));
            }
Beispiel #11
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));
        }
        public static void Create(BlobBuilder builder, ref BlobArray <BlobPtr <Collider> > colliders, ref QuadTree dest, Aabb rootBounds)
        {
            var children = builder.Allocate(ref dest._children, 4);
            var aabbs    = new List <ColliderBounds>();
            var cs       = new List <Collider>();

            for (var i = 0; i < colliders.Length; i++)
            {
                if (colliders[i].Value.Type != ColliderType.Plane)
                {
                    var c      = colliders[i].Value;
                    var bounds = colliders[i].Value.Bounds();
                    //Debug.Log("Adding aabb " + aabb + " (" + colliders[i].Value.Type + ")");
                    if (bounds.ColliderEntity == Entity.Null)
                    {
                        throw new InvalidOperationException($"Entity of {bounds} must be set ({colliders[i].Value.ItemType}).");
                    }
                    if (bounds.ColliderId < 0)
                    {
                        throw new InvalidOperationException($"ColliderId of {bounds} must be set ({colliders[i].Value.ItemType}).");
                    }

                    aabbs.Add(bounds);
                    cs.Add(c);
                }
            }

            dest.CreateNextLevel(builder, rootBounds, 0, 0, aabbs, ref children);
        }
Beispiel #13
0
        public unsafe static void AllocateAddress(this BlobBuilder builder, ref BlobResourceAddress resourceAddress, string address)
        {
            var arr   = builder.Allocate <char>(ref resourceAddress.Data, address.Length);
            var bytes = Encoding.Unicode.GetBytes(address);

            Marshal.Copy(bytes, 0, (IntPtr)arr.GetUnsafePtr(), bytes.Length);
        }
Beispiel #14
0
        protected override void AllocateData(ref BlobBuilder builder, ref BlobVariable <T> blobVariable, INodeDataBuilder self, ITreeNode <INodeDataBuilder>[] tree)
        {
            var          type         = ScriptableObject.GetType();
            FieldInfo    fieldInfo    = null;
            PropertyInfo propertyInfo = null;

            if (ScriptableObject != null)
            {
                fieldInfo = type.GetField(ScriptableObjectValueName, FIELD_BINDING_FLAGS);
            }
            if (fieldInfo == null)
            {
                propertyInfo = type.GetProperty(ScriptableObjectValueName, FIELD_BINDING_FLAGS);
            }

            if ((fieldInfo == null || fieldInfo.FieldType != typeof(T)) &&
                (propertyInfo == null || !propertyInfo.CanRead || propertyInfo.PropertyType != typeof(T)))
            {
                Debug.LogError($"{ScriptableObject.name}.{ScriptableObjectValueName} is not valid");
                throw new ArgumentException();
            }

            var value = fieldInfo?.GetValue(ScriptableObject) ?? propertyInfo?.GetValue(ScriptableObject);

            builder.Allocate(ref blobVariable, (T)value);
        }
Beispiel #15
0
 public IntPtr Allocate(ref BlobBuilder builder, ref BlobVariant blobVariant, INodeDataBuilder self, ITreeNode <INodeDataBuilder>[] tree)
 {
     blobVariant.VariantId = GuidHashCode(ComponentVariant.GUID);
     return(builder.Allocate(ref blobVariant, new ComponentVariant.DynamicComponentData {
         StableHash = _stableHash, Offset = _offset
     }));
 }
 BlobAssetReference <NodeGraph> BuildNodeGraph(NodeAuthoring[] authoringNodes)
 {
     using (var builder = new BlobBuilder(Allocator.Temp))
     {
         ref var root      = ref builder.ConstructRoot <NodeGraph>();
         var     nodeArray = builder.Allocate(ref root.Nodes, authoringNodes.Length);
         for (int i = 0; i < nodeArray.Length; i++)
         {
             nodeArray[i].Position = authoringNodes[i].transform.position;
             var links = builder.Allocate(ref nodeArray[i].Links, authoringNodes[i].links.Length);
             for (int j = 0; j < authoringNodes[i].links.Length; j++)
             {
                 links[j] = Array.IndexOf(authoringNodes, authoringNodes[i].links[j]);
             }
         }
         return(builder.CreateBlobAssetReference <NodeGraph>(Allocator.Persistent));
     }
Beispiel #17
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);
                }
            }
        }
Beispiel #18
0
        public override void Build(BlobBuilder builder, ref BlobArray <T> data)
        {
            var arrayBuilder = builder.Allocate(ref data, Value.Length);

            for (var i = 0; i < Value.Length; i++)
            {
                ((Builder <T>)Value[i]).Build(builder, ref arrayBuilder[i]);
            }
        }
Beispiel #19
0
        protected override void AllocateData(ref BlobBuilder builder, ref BlobVariable <T> blobVariable)
        {
            FieldInfo fieldInfo = null;

            if (ScriptableObject != null)
            {
                fieldInfo = ScriptableObject.GetType().GetField(ScriptableObjectValueName, FIELD_BINDING_FLAGS);
            }

            if (fieldInfo == null || fieldInfo.FieldType != typeof(T))
            {
                Debug.LogError($"{ScriptableObject.name}.{ScriptableObjectValueName} is not valid, fallback to ConstantValue");
                builder.Allocate(ref blobVariable, FallbackValue);
                return;
            }

            builder.Allocate(ref blobVariable, (T)fieldInfo.GetValue(ScriptableObject));
        }
Beispiel #20
0
        public static void AllocateArray <T>(this BlobBuilder builder, ref BlobArray <T> blobArray, IList <T> sourceArray) where T : struct
        {
            var array = builder.Allocate(ref blobArray, sourceArray.Count);

            for (var i = 0; i < sourceArray.Count; i++)
            {
                array[i] = sourceArray[i];
            }
        }
Beispiel #21
0
        static void InitializeSkeletonNodes(ref BlobBuilder blobBuilder, SkeletonNode[] skeletonNodes, ref BlobArray <int> parentIndices, ref BlobArray <StringHash> skeletonIds, ref BlobArray <int> axisIndices)
        {
            if (skeletonNodes == null || skeletonNodes.Length == 0)
            {
                return;
            }

            var parentIndicesBuilder       = blobBuilder.Allocate(ref parentIndices, skeletonNodes.Length);
            var skeletonIdsBuilder         = blobBuilder.Allocate(ref skeletonIds, skeletonNodes.Length);
            var skeletonAxisIndicesBuilder = blobBuilder.Allocate(ref axisIndices, skeletonNodes.Length);

            for (int i = 0; i < skeletonNodes.Length; i++)
            {
                parentIndicesBuilder[i]       = skeletonNodes[i].ParentIndex;
                skeletonIdsBuilder[i]         = skeletonNodes[i].Id;
                skeletonAxisIndicesBuilder[i] = skeletonNodes[i].AxisIndex;
            }
        }
Beispiel #22
0
        public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
        {
            Convert(entity, dstManager);

            var table = gameObject.GetComponentInParent <TableAuthoring>().Item;

            Item.Init(table);

            dstManager.AddComponentData(entity, new KickerStaticData {
                Center      = Data.Center.ToUnityFloat2(),
                FallThrough = Data.FallThrough,
                HitAccuracy = Data.HitAccuracy,
                Scatter     = Data.Scatter,
                LegacyMode  = Data.LegacyMode,
                ZLow        = table.GetSurfaceHeight(Data.Surface, Data.Center.X, Data.Center.Y) * table.GetScaleZ()
            });
            dstManager.AddComponentData(entity, new KickerCollisionData {
                BallEntity             = Entity.Null,
                LastCapturedBallEntity = Entity.Null
            });

            if (!Data.LegacyMode)
            {
                using (var blobBuilder = new BlobBuilder(Allocator.Temp)) {
                    ref var blobAsset = ref blobBuilder.ConstructRoot <KickerMeshVertexBlobAsset>();
                    var     vertices  = blobBuilder.Allocate(ref blobAsset.Vertices, Item.KickerHit.HitMesh.Length);
                    var     normals   = blobBuilder.Allocate(ref blobAsset.Normals, Item.KickerHit.HitMesh.Length);
                    for (var i = 0; i < Item.KickerHit.HitMesh.Length; i++)
                    {
                        var v = Item.KickerHit.HitMesh[i];
                        vertices[i] = new KickerMeshVertex {
                            Vertex = v.ToUnityFloat3()
                        };
                        normals[i] = new KickerMeshVertex {
                            Vertex = new float3(KickerHitMesh.Vertices[i].Nx, KickerHitMesh.Vertices[i].Ny, KickerHitMesh.Vertices[i].Nz)
                        };
                    }

                    var blobAssetReference = blobBuilder.CreateBlobAssetReference <KickerMeshVertexBlobAsset>(Allocator.Persistent);
                    dstManager.AddComponentData(entity, new ColliderMeshData {
                        Value = blobAssetReference
                    });
                }
            }
        public static unsafe BlobBuilderArray <T> Construct <T>(this BlobBuilder builder, ref BlobArray <T> blobArray, T[] data, int length) where T : unmanaged
        {
            var blobBuilderArray = builder.Allocate(ref blobArray, length);

            for (int i = 0; i < length; i++)
            {
                blobBuilderArray[i] = data[i];
            }
            return(blobBuilderArray);
        }
Beispiel #24
0
        public static unsafe BlobBuilderArray <T> Construct <T>(this BlobBuilder builder, ref BlobArray <T> blobArray, List <T> data) where T : unmanaged
        {
            var blobBuilderArray = builder.Allocate(ref blobArray, data.Count);

            for (int i = 0; i < data.Count; i++)
            {
                blobBuilderArray[i] = data[i];
            }
            return(blobBuilderArray);
        }
Beispiel #25
0
        public static unsafe BlobBuilderArray <T> Construct <T>(this BlobBuilder builder, ref BlobArray <T> blobArray, HashedVertices data) where T : unmanaged
        {
            var blobBuilderArray = builder.Allocate(ref blobArray, data.Length);

            if (data.Length > 0)
            {
                UnsafeUtility.MemCpy(blobBuilderArray.GetUnsafePtr(), data.GetUnsafeReadOnlyPtr(), blobBuilderArray.Length * sizeof(T));
            }
            return(blobBuilderArray);
        }
Beispiel #26
0
        public static BlobBuilderArray <T> ConstructFromNativeArray <T>(this BlobBuilder builder, ref BlobArray <T> ptr, NativeArray <T> array) where T : struct
        {
            var result = builder.Allocate(ref ptr, array.Length);

            for (int i = 0; i < array.Length; i++)
            {
                result[i] = array[i];
            }
            return(result);
        }
Beispiel #27
0
        static public BlobAssetReference <LitMeshData> CreateDonutMesh(float innerR, int innerN, float outerR, int outerN)
        {
            Assert.IsTrue(innerN * outerN <= ushort.MaxValue);
            Assert.IsTrue(outerR >= innerR * 2.0f);
            using (var builder = new BlobBuilder(Allocator.Temp)) {
                ref var root = ref builder.ConstructRoot <LitMeshData>();
                // in x/y plane
                var vertices = builder.Allocate(ref root.Vertices, innerN * outerN);
                var indices  = builder.Allocate(ref root.Indices, (innerN - 1) * (outerN - 1) * 6);
                MakeDonut(ref vertices, ref indices, innerR, innerN, outerR, outerN);

                ComputeTangentAndBinormal(ref vertices, ref indices);

                // bounds
                float3 ext = new float3(outerR + innerR, outerR + innerR, innerR * 2);
                root.Bounds.Center  = new float3(0.0f);
                root.Bounds.Extents = ext;

                return(builder.CreateBlobAssetReference <LitMeshData>(Allocator.Persistent));
            }
Beispiel #28
0
        public static unsafe BlobBuilderArray <T> Construct <T>(this BlobBuilder builder, ref BlobArray <T> blobArray, T *data, int length) where T : unmanaged
        {
            length = math.max(length, 0);
            var blobBuilderArray = builder.Allocate(ref blobArray, length);

            if (length > 0)
            {
                UnsafeUtility.MemCpy(blobBuilderArray.GetUnsafePtr(), data, blobBuilderArray.Length * sizeof(T));
            }
            return(blobBuilderArray);
        }
Beispiel #29
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));
            }
 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));
     }