protected override void ProcessDataInstance(IChannel ch, ref VBuffer <Float> feat, Float label, Float weight)
        {
            base.ProcessDataInstance(ch, ref feat, label, weight);

            // compute the update and update if needed
            Float  output = CurrentMargin(ref feat);
            Double loss   = LossFunction.Loss(output, label);

            // REVIEW: Should this be biasUpdate != 0?
            // This loss does not incorporate L2 if present, but the chance of that addition to the loss
            // exactly cancelling out loss is remote.
            if (loss != 0 || Args.L2RegularizerWeight > 0)
            {
                // If doing lazy weights, we need to update the totalWeights and totalBias before updating weights/bias
                if (Args.DoLazyUpdates && Args.Averaged && NumNoUpdates > 0 && TotalMultipliers * Args.AveragedTolerance <= PendingMultipliers)
                {
                    VectorUtils.AddMult(ref Weights, NumNoUpdates * WeightsScale, ref TotalWeights);
                    TotalBias         += Bias * NumNoUpdates * WeightsScale;
                    NumWeightUpdates  += NumNoUpdates;
                    NumNoUpdates       = 0;
                    TotalMultipliers  += PendingMultipliers;
                    PendingMultipliers = 0;
                }

#if OLD_TRACING // REVIEW: How should this be ported?
                // If doing debugging and have L2 regularization, adjust the loss to account for that component.
                if (DebugLevel > 2 && _args.l2RegularizerWeight != 0)
                {
                    loss += _args.l2RegularizerWeight * VectorUtils.NormSquared(_weights) * _weightsScale * _weightsScale;
                }
#endif

                // Make final adjustments to update parameters.
                Float rate = Args.LearningRate;
                if (Args.DecreaseLearningRate)
                {
                    rate /= MathUtils.Sqrt((Float)NumWeightUpdates + NumNoUpdates + 1);
                }
                Float biasUpdate = -rate *LossFunction.Derivative(output, label);

                // Perform the update to weights and bias.
                VectorUtils.AddMult(ref feat, biasUpdate / WeightsScale, ref Weights);
                WeightsScale *= 1 - 2 * Args.L2RegularizerWeight; // L2 regularization.
                ScaleWeightsIfNeeded();
                Bias += biasUpdate;
                PendingMultipliers += Math.Abs(biasUpdate);

#if OLD_TRACING   // REVIEW: How should this be ported?
                if (DebugLevel > 2)
                { // sanity check:   did loss for the example decrease?
                    Double newLoss = _lossFunction.Loss(CurrentMargin(instance), instance.Label);
                    if (_args.l2RegularizerWeight != 0)
                    {
                        newLoss += _args.l2RegularizerWeight * VectorUtils.NormSquared(_weights) * _weightsScale * _weightsScale;
                    }

                    if (newLoss - loss > 0 && (newLoss - loss > 0.01 || _args.l2RegularizerWeight == 0))
                    {
                        Host.StdErr.WriteLine("Loss increased (unexpected):  Old value: {0}, new value: {1}", loss, newLoss);
                        Host.StdErr.WriteLine("Offending instance #{0}: {1}", _numIterExamples, instance);
                    }
                }
#endif
            }

            // Add to averaged weights and increment the count.
            if (Args.Averaged)
            {
                if (!Args.DoLazyUpdates)
                {
                    IncrementAverageNonLazy();
                }
                else
                {
                    NumNoUpdates++;
                }

                // Reset the weights to averages if needed.
                if (Args.ResetWeightsAfterXExamples > 0 &&
                    NumIterExamples % Args.ResetWeightsAfterXExamples.Value == 0)
                {
                    // #if OLD_TRACING // REVIEW: How should this be ported?
                    Console.WriteLine();
                    // #endif
                    ch.Info("Resetting weights to average weights");
                    VectorUtils.ScaleInto(ref TotalWeights, 1 / (Float)NumWeightUpdates, ref Weights);
                    WeightsScale = 1;
                    Bias         = TotalBias / (Float)NumWeightUpdates;
                }
            }

#if OLD_TRACING // REVIEW: How should this be ported?
            if (DebugLevel > 3)
            {
                // Output the weights.
                Host.StdOut.Write("Weights after the instance are: ");
                foreach (var iv in _weights.Items(all: true))
                {
                    Host.StdOut.Write('\t');
                    Host.StdOut.Write(iv.Value * _weightsScale);
                }
                Host.StdOut.WriteLine();
                Host.StdOut.WriteLine();
            }
#endif
        }
        /// <inheritdoc/>
        protected override void TrainWithoutLock(IProgressChannelProvider progress, FloatLabelCursor.Factory cursorFactory, IRandom rand,
                                                 IdToIdxLookup idToIdx, int numThreads, DualsTableBase duals, Float[] biasReg, Float[] invariants, Float lambdaNInv,
                                                 VBuffer <Float>[] weights, Float[] biasUnreg, VBuffer <Float>[] l1IntermediateWeights, Float[] l1IntermediateBias, Float[] featureNormSquared)
        {
            Contracts.AssertValueOrNull(progress);
            Contracts.Assert(_args.L1Threshold.HasValue);
            Contracts.AssertValueOrNull(idToIdx);
            Contracts.AssertValueOrNull(invariants);
            Contracts.AssertValueOrNull(featureNormSquared);
            int weightArraySize = WeightArraySize;

            Contracts.Assert(weightArraySize == _numClasses);
            Contracts.Assert(Utils.Size(weights) == weightArraySize);
            Contracts.Assert(Utils.Size(biasReg) == weightArraySize);
            Contracts.Assert(Utils.Size(biasUnreg) == weightArraySize);

            int  maxUpdateTrials = 2 * numThreads;
            var  l1Threshold     = _args.L1Threshold.Value;
            bool l1ThresholdZero = l1Threshold == 0;
            var  lr = _args.BiasLearningRate * _args.L2Const.Value;

            var pch = progress != null?progress.StartProgressChannel("Dual update") : null;

            using (pch)
                using (var cursor = _args.Shuffle ? cursorFactory.Create(rand) : cursorFactory.Create())
                {
                    long rowCount = 0;
                    if (pch != null)
                    {
                        pch.SetHeader(new ProgressHeader("examples"), e => e.SetProgress(0, rowCount));
                    }

                    Func <UInt128, long> getIndexFromId = GetIndexFromIdGetter(idToIdx);
                    while (cursor.MoveNext())
                    {
                        long  idx = getIndexFromId(cursor.Id);
                        long  dualIndexInitPos = idx * weightArraySize;
                        var   features         = cursor.Features;
                        var   label            = (int)cursor.Label;
                        Float invariant;
                        Float normSquared;
                        if (invariants != null)
                        {
                            invariant = invariants[idx];
                            Contracts.AssertValue(featureNormSquared);
                            normSquared = featureNormSquared[idx];
                        }
                        else
                        {
                            normSquared = VectorUtils.NormSquared(features);
                            if (_args.BiasLearningRate == 0)
                            {
                                normSquared += 1;
                            }

                            invariant = _loss.ComputeDualUpdateInvariant(2 * normSquared * lambdaNInv * GetInstanceWeight(cursor));
                        }

                        // The output for the label class using current weights and bias.
                        var labelOutput    = WDot(ref features, ref weights[label], biasReg[label] + biasUnreg[label]);
                        var instanceWeight = GetInstanceWeight(cursor);

                        // This will be the new dual variable corresponding to the label class.
                        Float labelDual = 0;

                        // This will be used to update the weights and regularized bias corresponding to the label class.
                        Float labelPrimalUpdate = 0;

                        // This will be used to update the unregularized bias corresponding to the label class.
                        Float labelAdjustment = 0;

                        // Iterates through all classes.
                        for (int iClass = 0; iClass < _numClasses; iClass++)
                        {
                            // Skip the dual/weights/bias update for label class. Will be taken care of at the end.
                            if (iClass == label)
                            {
                                continue;
                            }

                            // Loop trials for compare-and-swap updates of duals.
                            // In general, concurrent update conflict to the same dual variable is rare
                            // if data is shuffled.
                            for (int numTrials = 0; numTrials < maxUpdateTrials; numTrials++)
                            {
                                long dualIndex  = iClass + dualIndexInitPos;
                                var  dual       = duals[dualIndex];
                                var  output     = labelOutput + labelPrimalUpdate * normSquared - WDot(ref features, ref weights[iClass], biasReg[iClass] + biasUnreg[iClass]);
                                var  dualUpdate = _loss.DualUpdate(output, 1, dual, invariant, numThreads);

                                // The successive over-relaxation apporach to adjust the sum of dual variables (biasReg) to zero.
                                // Reference to details: http://stat.rutgers.edu/home/tzhang/papers/ml02_dual.pdf, pp. 16-17.
                                var adjustment = l1ThresholdZero ? lr * biasReg[iClass] : lr * l1IntermediateBias[iClass];
                                dualUpdate -= adjustment;
                                bool success = false;
                                duals.ApplyAt(dualIndex, (long index, ref Float value) =>
                                {
                                    success = Interlocked.CompareExchange(ref value, dual + dualUpdate, dual) == dual;
                                });

                                if (success)
                                {
                                    // Note: dualConstraint[iClass] = lambdaNInv * (sum of duals[iClass])
                                    var primalUpdate = dualUpdate * lambdaNInv * instanceWeight;
                                    labelDual         -= dual + dualUpdate;
                                    labelPrimalUpdate += primalUpdate;
                                    biasUnreg[iClass] += adjustment * lambdaNInv * instanceWeight;
                                    labelAdjustment   -= adjustment;

                                    if (l1ThresholdZero)
                                    {
                                        VectorUtils.AddMult(ref features, weights[iClass].Values, -primalUpdate);
                                        biasReg[iClass] -= primalUpdate;
                                    }
                                    else
                                    {
                                        //Iterative shrinkage-thresholding (aka. soft-thresholding)
                                        //Update v=denseWeights as if there's no L1
                                        //Thresholding: if |v[j]| < threshold, turn off weights[j]
                                        //If not, shrink: w[j] = v[i] - sign(v[j]) * threshold
                                        l1IntermediateBias[iClass] -= primalUpdate;
                                        if (_args.BiasLearningRate == 0)
                                        {
                                            biasReg[iClass] = Math.Abs(l1IntermediateBias[iClass]) - l1Threshold > 0.0
                                        ? l1IntermediateBias[iClass] - Math.Sign(l1IntermediateBias[iClass]) * l1Threshold
                                        : 0;
                                        }

                                        if (features.IsDense)
                                        {
                                            SseUtils.SdcaL1UpdateDense(-primalUpdate, features.Length, features.Values, l1Threshold, l1IntermediateWeights[iClass].Values, weights[iClass].Values);
                                        }
                                        else if (features.Count > 0)
                                        {
                                            SseUtils.SdcaL1UpdateSparse(-primalUpdate, features.Length, features.Values, features.Indices, features.Count, l1Threshold, l1IntermediateWeights[iClass].Values, weights[iClass].Values);
                                        }
                                    }

                                    break;
                                }
                            }
                        }

                        // Updating with label class weights and dual variable.
                        duals[label + dualIndexInitPos] = labelDual;
                        biasUnreg[label] += labelAdjustment * lambdaNInv * instanceWeight;
                        if (l1ThresholdZero)
                        {
                            VectorUtils.AddMult(ref features, weights[label].Values, labelPrimalUpdate);
                            biasReg[label] += labelPrimalUpdate;
                        }
                        else
                        {
                            l1IntermediateBias[label] += labelPrimalUpdate;
                            var intermediateBias = l1IntermediateBias[label];
                            biasReg[label] = Math.Abs(intermediateBias) - l1Threshold > 0.0
                            ? intermediateBias - Math.Sign(intermediateBias) * l1Threshold
                            : 0;

                            if (features.IsDense)
                            {
                                SseUtils.SdcaL1UpdateDense(labelPrimalUpdate, features.Length, features.Values, l1Threshold, l1IntermediateWeights[label].Values, weights[label].Values);
                            }
                            else if (features.Count > 0)
                            {
                                SseUtils.SdcaL1UpdateSparse(labelPrimalUpdate, features.Length, features.Values, features.Indices, features.Count, l1Threshold, l1IntermediateWeights[label].Values, weights[label].Values);
                            }
                        }

                        rowCount++;
                    }
                }
        }
Exemple #3
0
        /// <inheritdoc/>
        private protected override bool CheckConvergence(
            IProgressChannel pch,
            int iter,
            FloatLabelCursor.Factory cursorFactory,
            DualsTableBase duals,
            IdToIdxLookup idToIdx,
            VBuffer <float>[] weights,
            VBuffer <float>[] bestWeights,
            float[] biasUnreg,
            float[] bestBiasUnreg,
            float[] biasReg,
            float[] bestBiasReg,
            long count,
            Double[] metrics,
            ref Double bestPrimalLoss,
            ref int bestIter)
        {
            Contracts.AssertValue(weights);
            Contracts.AssertValue(duals);
            int numClasses = weights.Length;

            Contracts.Assert(duals.Length >= numClasses * count);
            Contracts.AssertValueOrNull(idToIdx);
            Contracts.Assert(Utils.Size(weights) == numClasses);
            Contracts.Assert(Utils.Size(biasReg) == numClasses);
            Contracts.Assert(Utils.Size(biasUnreg) == numClasses);
            Contracts.Assert(Utils.Size(metrics) == 6);
            var reportedValues = new Double?[metrics.Length + 1];

            reportedValues[metrics.Length] = iter;
            var lossSum     = new CompensatedSum();
            var dualLossSum = new CompensatedSum();
            int numFeatures = weights[0].Length;

            using (var cursor = cursorFactory.Create())
            {
                long row = 0;
                Func <DataViewRowId, long, long> getIndexFromIdAndRow = GetIndexFromIdAndRowGetter(idToIdx, biasReg.Length);
                // Iterates through data to compute loss function.
                while (cursor.MoveNext())
                {
                    Host.CheckAlive();
                    var    instanceWeight = GetInstanceWeight(cursor);
                    var    features       = cursor.Features;
                    var    label          = (int)cursor.Label;
                    var    labelOutput    = WDot(in features, in weights[label], biasReg[label] + biasUnreg[label]);
                    Double subLoss        = 0;
                    Double subDualLoss    = 0;
                    long   idx            = getIndexFromIdAndRow(cursor.Id, row);
                    long   dualIndex      = idx * numClasses;
                    for (int iClass = 0; iClass < numClasses; iClass++)
                    {
                        if (iClass == label)
                        {
                            dualIndex++;
                            continue;
                        }

                        var currentClassOutput = WDot(in features, in weights[iClass], biasReg[iClass] + biasUnreg[iClass]);
                        subLoss += _loss.Loss(labelOutput - currentClassOutput, 1);
                        Contracts.Assert(dualIndex == iClass + idx * numClasses);
                        var dual = duals[dualIndex++];
                        subDualLoss += _loss.DualLoss(1, dual);
                    }

                    lossSum.Add(subLoss * instanceWeight);
                    dualLossSum.Add(subDualLoss * instanceWeight);

                    row++;
                }
                Host.Assert(idToIdx == null || row * numClasses == duals.Length);
            }

            Contracts.Assert(SdcaTrainerOptions.L2Regularization.HasValue);
            Contracts.Assert(SdcaTrainerOptions.L1Regularization.HasValue);
            Double l2Const     = SdcaTrainerOptions.L2Regularization.Value;
            Double l1Threshold = SdcaTrainerOptions.L1Regularization.Value;

            Double weightsL1Norm                = 0;
            Double weightsL2NormSquared         = 0;
            Double biasRegularizationAdjustment = 0;

            for (int iClass = 0; iClass < numClasses; iClass++)
            {
                weightsL1Norm                += VectorUtils.L1Norm(in weights[iClass]) + Math.Abs(biasReg[iClass]);
                weightsL2NormSquared         += VectorUtils.NormSquared(weights[iClass]) + biasReg[iClass] * biasReg[iClass];
                biasRegularizationAdjustment += biasReg[iClass] * biasUnreg[iClass];
            }

            Double l1Regularizer = SdcaTrainerOptions.L1Regularization.Value * l2Const * weightsL1Norm;
            var    l2Regularizer = l2Const * weightsL2NormSquared * 0.5;

            var newLoss     = lossSum.Sum / count + l2Regularizer + l1Regularizer;
            var newDualLoss = dualLossSum.Sum / count - l2Regularizer - l2Const * biasRegularizationAdjustment;
            var dualityGap  = newLoss - newDualLoss;

            metrics[(int)MetricKind.Loss]       = newLoss;
            metrics[(int)MetricKind.DualLoss]   = newDualLoss;
            metrics[(int)MetricKind.DualityGap] = dualityGap;
            metrics[(int)MetricKind.BiasUnreg]  = biasUnreg[0];
            metrics[(int)MetricKind.BiasReg]    = biasReg[0];
            metrics[(int)MetricKind.L1Sparsity] = SdcaTrainerOptions.L1Regularization == 0 ? 1 : weights.Sum(
                weight => weight.GetValues().Count(w => w != 0)) / (numClasses * numFeatures);

            bool converged = dualityGap / newLoss < SdcaTrainerOptions.ConvergenceTolerance;

            if (metrics[(int)MetricKind.Loss] < bestPrimalLoss)
            {
                for (int iClass = 0; iClass < numClasses; iClass++)
                {
                    // Maintain a copy of weights and bias with best primal loss thus far.
                    // This is some extra work and uses extra memory, but it seems worth doing it.
                    // REVIEW: Sparsify bestWeights?
                    weights[iClass].CopyTo(ref bestWeights[iClass]);
                    bestBiasReg[iClass]   = biasReg[iClass];
                    bestBiasUnreg[iClass] = biasUnreg[iClass];
                }

                bestPrimalLoss = metrics[(int)MetricKind.Loss];
                bestIter       = iter;
            }

            for (int i = 0; i < metrics.Length; i++)
            {
                reportedValues[i] = metrics[i];
            }
            if (pch != null)
            {
                pch.Checkpoint(reportedValues);
            }

            return(converged);
        }
Exemple #4
0
        public override void SimulationStep(ushort instanceID, ref CitizenInstance citizenData, ref CitizenInstance.Frame frameData, bool lodPhysics)
        {
            if (IsCagedAnimal(citizenData))
            {
                SimulationStepCaged(instanceID, ref citizenData, ref frameData, lodPhysics);
                return;
            }
            else if (LivestockAIDetour.isFreeAnimal(citizenData))
            {
                SimulationStepWild(instanceID, ref citizenData, ref frameData, lodPhysics);
                return;
            }

            float sqrMagnitude1 = frameData.m_velocity.sqrMagnitude;

            if ((double)sqrMagnitude1 > 0.00999999977648258)
            {
                frameData.m_position += frameData.m_velocity * 0.5f;
            }
            CitizenInstance.Flags flags1 = CitizenInstance.Flags.None;
            if ((int)citizenData.m_targetBuilding != 0)
            {
                CitizenManager        instance = Singleton <CitizenManager> .instance;
                CitizenInstance.Flags flags2   = instance.m_instances.m_buffer[(int)citizenData.m_targetBuilding].m_flags;
                if ((flags2 & CitizenInstance.Flags.Character) != CitizenInstance.Flags.None)
                {
                    Randomizer            randomizer    = new Randomizer((int)instanceID);
                    CitizenInstance.Frame lastFrameData = instance.m_instances.m_buffer[(int)citizenData.m_targetBuilding].GetLastFrameData();
                    Vector3 vector3 = lastFrameData.m_rotation * new Vector3(0.5f, 0.0f, 0.0f);
                    if (randomizer.Int32(2U) == 0)
                    {
                        vector3 = -vector3;
                    }
                    Vector4 vector4 = instance.m_instances.m_buffer[(int)citizenData.m_targetBuilding].m_targetPos + (Vector4)vector3;
                    if ((double)Vector3.SqrMagnitude(lastFrameData.m_position - frameData.m_position) > 10000.0)
                    {
                        citizenData.m_targetBuilding = (ushort)0;
                    }
                    else
                    {
                        flags1 = flags2 & (CitizenInstance.Flags.Underground | CitizenInstance.Flags.InsideBuilding | CitizenInstance.Flags.Transition);
                        citizenData.m_targetPos = vector4;
                    }
                }
                else
                {
                    citizenData.m_targetBuilding = (ushort)0;
                }
            }
            citizenData.m_flags = citizenData.m_flags & ~(CitizenInstance.Flags.Underground | CitizenInstance.Flags.InsideBuilding | CitizenInstance.Flags.Transition) | flags1;
            Vector3 v = (Vector3)citizenData.m_targetPos - frameData.m_position;
            float   f = lodPhysics || (double)citizenData.m_targetPos.w <= 1.0 / 1000.0 ? v.sqrMagnitude : VectorUtils.LengthSqrXZ(v);
            float   a = this.m_info.m_walkSpeed;
            float   b = 2f;

            if ((double)f < 1.0)
            {
                v = Vector3.zero;
            }
            else
            {
                float num       = Mathf.Sqrt(f);
                float maxLength = Mathf.Min(a, num * 0.75f);
                v = Quaternion.Inverse(frameData.m_rotation) * v;
                if ((double)v.z < (double)Mathf.Abs(v.x))
                {
                    v.x       = (double)v.x < 0.0 ? Mathf.Min(-1f, v.x) : Mathf.Max(1f, v.x);
                    v.z       = Mathf.Abs(v.x);
                    maxLength = Mathf.Min(0.5f, num * 0.1f);
                }
                v = Vector3.ClampMagnitude(frameData.m_rotation * v, maxLength);
            }
            Vector3 vector3_1 = v - frameData.m_velocity;
            float   magnitude = vector3_1.magnitude;
            Vector3 vector3_2 = vector3_1 * (b / Mathf.Max(magnitude, b));

            frameData.m_velocity += vector3_2;
            float  sqrMagnitude2 = frameData.m_velocity.sqrMagnitude;
            bool   flag          = !lodPhysics && (double)citizenData.m_targetPos.w > 1.0 / 1000.0 && ((double)sqrMagnitude2 > 0.00999999977648258 || (double)sqrMagnitude1 > 0.00999999977648258);
            ushort buildingID    = !flag ? (ushort)0 : Singleton <BuildingManager> .instance.GetWalkingBuilding(frameData.m_position + frameData.m_velocity * 0.5f);

            if ((double)sqrMagnitude2 > 0.00999999977648258)
            {
                Vector3 forward = frameData.m_velocity;
                if (!lodPhysics)
                {
                    Vector3 pushAmount  = Vector3.zero;
                    float   pushDivider = 0.0f;
                    this.CheckCollisions(instanceID, ref citizenData, frameData.m_position, frameData.m_position + frameData.m_velocity, buildingID, ref pushAmount, ref pushDivider);
                    if ((double)pushDivider > 0.00999999977648258)
                    {
                        pushAmount           *= 1f / pushDivider;
                        pushAmount            = Vector3.ClampMagnitude(pushAmount, Mathf.Sqrt(sqrMagnitude2) * 0.5f);
                        frameData.m_velocity += pushAmount;
                        forward += pushAmount * 0.25f;
                    }
                }
                frameData.m_position += frameData.m_velocity * 0.5f;
                if ((double)forward.sqrMagnitude > 0.00999999977648258)
                {
                    frameData.m_rotation = Quaternion.LookRotation(forward);
                }
            }
            if (flag)
            {
                Vector3 worldPos      = frameData.m_position;
                float   terrainHeight = Singleton <TerrainManager> .instance.SampleDetailHeight(worldPos);

                if ((int)buildingID != 0)
                {
                    float num = Singleton <BuildingManager> .instance.m_buildings.m_buffer[(int)buildingID].SampleWalkingHeight(worldPos, terrainHeight);
                    worldPos.y             = worldPos.y + (num - worldPos.y) * Mathf.Min(1f, citizenData.m_targetPos.w * 4f);
                    frameData.m_position.y = worldPos.y;
                }
                else if ((double)Mathf.Abs(terrainHeight - worldPos.y) < 2.0)
                {
                    worldPos.y             = worldPos.y + (terrainHeight - worldPos.y) * Mathf.Min(1f, citizenData.m_targetPos.w * 4f);
                    frameData.m_position.y = worldPos.y;
                }
            }
            frameData.m_underground    = (citizenData.m_flags & CitizenInstance.Flags.Underground) != CitizenInstance.Flags.None;
            frameData.m_insideBuilding = (citizenData.m_flags & CitizenInstance.Flags.InsideBuilding) != CitizenInstance.Flags.None;
            frameData.m_transition     = (citizenData.m_flags & CitizenInstance.Flags.Transition) != CitizenInstance.Flags.None;
            var mRandomEffect = ((PetAI)Convert.ChangeType(this, typeof(PetAI))).m_randomEffect;

            if (mRandomEffect == null || Singleton <SimulationManager> .instance.m_randomizer.Int32(40U) != 0)
            {
                return;
            }
            InstanceID instance1 = new InstanceID();

            instance1.CitizenInstance = instanceID;
            EffectInfo.SpawnArea spawnArea = new EffectInfo.SpawnArea(frameData.m_position, Vector3.up, 0.0f);
            float num1 = 3.75f;

            Singleton <EffectManager> .instance.DispatchEffect(mRandomEffect, instance1, spawnArea, frameData.m_velocity *num1, 0.0f, 1f, Singleton <CitizenManager> .instance.m_audioGroup);
        }
Exemple #5
0
        IEnumerator CommandPosition(IBDAIControl wingman, PilotCommands command)
        {
            if (focusIndexes.Count == 0 && !commandSelf)
            {
                yield break;
            }

            DisplayScreenMessage(Localizer.Format("#LOC_BDArmory_WingCommander_ScreenMessage"));//"Select target coordinates.\nRight-click to cancel."

            if (command == PilotCommands.FlyTo)
            {
                waitingForFlytoPos = true;
            }
            else if (command == PilotCommands.Attack)
            {
                waitingForAttackPos = true;
            }

            yield return(null);

            bool waitingForPos = true;

            drawMouseDiamond = true;
            while (waitingForPos)
            {
                if (Input.GetMouseButtonDown(1))
                {
                    break;
                }
                if (Input.GetMouseButtonDown(0))
                {
                    Vector3 mousePos = new Vector3(Input.mousePosition.x / Screen.width,
                                                   Input.mousePosition.y / Screen.height, 0);
                    Plane surfPlane = new Plane(vessel.upAxis,
                                                vessel.transform.position - (vessel.altitude * vessel.upAxis));
                    Ray   ray = FlightCamera.fetch.mainCamera.ViewportPointToRay(mousePos);
                    float dist;
                    if (surfPlane.Raycast(ray, out dist))
                    {
                        Vector3  worldPoint = ray.GetPoint(dist);
                        Vector3d gps        = VectorUtils.WorldPositionToGeoCoords(worldPoint, vessel.mainBody);

                        if (command == PilotCommands.FlyTo)
                        {
                            wingman.CommandFlyTo(gps);
                        }
                        else if (command == PilotCommands.Attack)
                        {
                            wingman.CommandAttack(gps);
                        }

                        StartCoroutine(CommandPositionGUIRoutine(wingman, new GPSTargetInfo(gps, command.ToString())));
                    }

                    break;
                }
                yield return(null);
            }

            waitingForAttackPos = false;
            waitingForFlytoPos  = false;
            drawMouseDiamond    = false;
            ScreenMessages.RemoveMessage(screenMessage);
        }
Exemple #6
0
        public static TargetSignatureData GetHeatTarget(Ray ray, float scanRadius, float highpassThreshold, bool allAspect, MissileFire mf = null, bool favorGroundTargets = false)
        {
            float minMass = 0.05f;  //otherwise the RAMs have trouble shooting down incoming missiles
            TargetSignatureData finalData = TargetSignatureData.noTarget;
            float finalScore = 0;

            foreach (Vessel vessel in LoadedVessels)
            {
                if (!vessel || !vessel.loaded)
                {
                    continue;
                }

                if (favorGroundTargets && !vessel.LandedOrSplashed) // for AGM heat guidance
                {
                    continue;
                }

                TargetInfo tInfo = vessel.gameObject.GetComponent <TargetInfo>();
                if (mf == null ||
                    !tInfo ||
                    !(mf && tInfo.isMissile && tInfo.team != BoolToTeam(mf.team) && (tInfo.MissileBaseModule.MissileState == MissileBase.MissileStates.Boost || tInfo.MissileBaseModule.MissileState == MissileBase.MissileStates.Cruise)))
                {
                    if (vessel.GetTotalMass() < minMass)
                    {
                        continue;
                    }
                }


                float angle = Vector3.Angle(vessel.CoM - ray.origin, ray.direction);
                if (angle < scanRadius)
                {
                    if (RadarUtils.TerrainCheck(ray.origin, vessel.transform.position))
                    {
                        continue;
                    }


                    if (!allAspect)
                    {
                        if (!Misc.Misc.CheckSightLineExactDistance(ray.origin, vessel.CoM + vessel.Velocity(), Vector3.Distance(vessel.CoM, ray.origin), 5, 5))
                        {
                            continue;
                        }
                    }

                    float score = GetVesselHeatSignature(vessel) * Mathf.Clamp01(15 / angle);
                    score *= Mathf.Pow(1400, 2) / Mathf.Clamp((vessel.CoM - ray.origin).sqrMagnitude, 90000, 36000000);

                    if (vessel.LandedOrSplashed && !favorGroundTargets)
                    {
                        score /= 4;
                    }

                    score *= Mathf.Clamp(Vector3.Angle(vessel.transform.position - ray.origin, -VectorUtils.GetUpDirection(ray.origin)) / 90, 0.5f, 1.5f);

                    if (score > finalScore)
                    {
                        finalScore = score;
                        finalData  = new TargetSignatureData(vessel, score);
                    }
                }
            }

            // see if there are flares decoying us:
            TargetSignatureData flareData = GetFlareTarget(ray, scanRadius, highpassThreshold, allAspect, finalScore);

            if (finalScore < highpassThreshold)
            {
                finalData = TargetSignatureData.noTarget;
            }

            // return matching flare
            if (!flareData.Equals(TargetSignatureData.noTarget))
            {
                return(flareData);
            }

            //else return the target:
            return(finalData);
        }
Exemple #7
0
        private PcaPredictor TrainCore(IChannel ch, RoleMappedData data, int dimension)
        {
            Host.AssertValue(ch);
            ch.AssertValue(data);

            if (_rank > dimension)
            {
                throw ch.Except("Rank ({0}) cannot be larger than the original dimension ({1})", _rank, dimension);
            }
            int oversampledRank = Math.Min(_rank + _oversampling, dimension);

            //exact: (size of the 2 big matrices + other minor allocations) / (2^30)
            Double memoryUsageEstimate = 2.0 * dimension * oversampledRank * sizeof(Float) / 1e9;

            if (memoryUsageEstimate > 2)
            {
                ch.Info("Estimate memory usage: {0:G2} GB. If running out of memory, reduce rank and oversampling factor.", memoryUsageEstimate);
            }

            var y    = Zeros(oversampledRank, dimension);
            var mean = _center ? VBufferUtils.CreateDense <Float>(dimension) : VBufferUtils.CreateEmpty <Float>(dimension);

            var omega = GaussianMatrix(oversampledRank, dimension, _seed);

            var  cursorFactory = new FeatureFloatVectorCursor.Factory(data, CursOpt.Features | CursOpt.Weight);
            long numBad;

            Project(Host, cursorFactory, ref mean, omega, y, out numBad);
            if (numBad > 0)
            {
                ch.Warning("Skipped {0} instances with missing features/weights during training", numBad);
            }

            //Orthonormalize Y in-place using stabilized Gram Schmidt algorithm.
            //Ref: https://en.wikipedia.org/wiki/Gram-Schmidt#Algorithm
            for (var i = 0; i < oversampledRank; ++i)
            {
                var v = y[i];
                VectorUtils.ScaleBy(ref v, 1 / VectorUtils.Norm(y[i]));

                // Make the next vectors in the queue orthogonal to the orthonormalized vectors.
                for (var j = i + 1; j < oversampledRank; ++j) //subtract the projection of y[j] on v.
                {
                    VectorUtils.AddMult(ref v, -VectorUtils.DotProduct(ref v, ref y[j]), ref y[j]);
                }
            }
            var q = y;     // q in QR decomposition.

            var b = omega; // reuse the memory allocated by Omega.

            Project(Host, cursorFactory, ref mean, q, b, out numBad);

            //Compute B2 = B' * B
            var b2 = new Float[oversampledRank * oversampledRank];

            for (var i = 0; i < oversampledRank; ++i)
            {
                for (var j = i; j < oversampledRank; ++j)
                {
                    b2[i * oversampledRank + j] = b2[j * oversampledRank + i] = VectorUtils.DotProduct(ref b[i], ref b[j]);
                }
            }

            Float[] smallEigenvalues;// eigenvectors and eigenvalues of the small matrix B2.
            Float[] smallEigenvectors;
            EigenUtils.EigenDecomposition(b2, out smallEigenvalues, out smallEigenvectors);
            PostProcess(b, smallEigenvalues, smallEigenvectors, dimension, oversampledRank);

            return(new PcaPredictor(Host, _rank, b, ref mean));
        }
        public void Render(GraphicsDevice gd, CommandList cl, SceneContext sc, RenderPasses renderPass, SpriteModelResourceContainer modelResource, ref SpriteModelRenderData renderData)
        {
            if (renderData.Shared.RenderMode == RenderMode.Glow)
            {
                renderData.Shared.RenderAmount = GlowBlend(ref renderData.Shared, sc.ViewState);
            }

            //Don't render if blend is 0 (even if blend were ignored below)
            if (renderData.Shared.RenderAmount == 0)
            {
                return;
            }

            var blend = renderData.Shared.RenderMode != RenderMode.Normal ? renderData.Shared.RenderAmount : 255;

            //TODO: glow sprite visibility testing
            var angles = GetSpriteAngles(ref renderData.Shared, modelResource.SpriteModel.SpriteFile.Type, sc.ViewState);

            angles = VectorUtils.ToRadians(angles);

            var wai = new WorldAndInverse();

            var anglesWithoutYaw = angles;

            anglesWithoutYaw.Y = 0;

            wai.World = Matrix4x4.CreateScale(renderData.Shared.Scale)
                * WorldAndInverse.CreateRotationMatrix(anglesWithoutYaw)
                * WorldAndInverse.CreateRotationMatrix(new Vector3(0, angles.Y, 0))
                * Matrix4x4.CreateTranslation(renderData.Shared.Origin);

            wai.InverseWorld = VdUtilities.CalculateInverseTranspose(ref wai.World);

            //var wai = new WorldAndInverse(renderData.Origin, angles, renderData.Scale);

            sc.UpdateWorldAndInverseBuffer(cl, ref wai);

            var alpha = 255;

            switch (renderData.Shared.RenderMode)
            {
                case RenderMode.Normal:
                case RenderMode.TransTexture:
                case RenderMode.TransAlpha:
                    alpha = blend;
                    break;
            }

            var renderColor = new Vector4(CalculateSpriteColor(ref renderData.Shared, blend), alpha) / 255.0f;

            cl.UpdateBuffer(modelResource.RenderColorBuffer, 0, ref renderColor);

            renderData.Frame = Math.Clamp((int)renderData.Frame, 0, modelResource.VertexBuffers.Length - 1);

            var frameBuffer = modelResource.VertexBuffers[(int)renderData.Frame];

            var pipeline = Pipelines[renderData.Shared.RenderMode];

            cl.SetVertexBuffer(0, frameBuffer);
            cl.SetIndexBuffer(modelResource.IndexBuffer, IndexFormat.UInt16);
            cl.SetPipeline(pipeline);
            cl.SetGraphicsResourceSet(0, modelResource.ResourceSet);
            cl.DrawIndexed((uint)SPRResourceUtils.Indices.Length, 1, 0, 0, 0);
        }
Exemple #9
0
        public void Set(Vector3Int pos, BaseObject obj)
        {
            int i = VectorUtils.ToIndex(pos, Dimensions.x, Dimensions.y);

            _objects[i] = obj;
        }
Exemple #10
0
 //=====================================
 public void SetPosition(Vector2 pos)
 {
     myTranform.position = VectorUtils.GetPosition3D(pos);
 }
        private Vector3 GetSpriteAngles(ref SharedModelRenderData renderData, SpriteType type, IViewState viewState)
        {
            //Convert parallel sprites to parallel oriented if a roll was specified
            if (type == SpriteType.Parallel && renderData.Angles.Z != 0)
            {
                type = SpriteType.ParallelOriented;
            }

            Vector3 GetModifiedViewAngles()
            {
                var angles = viewState.Angles;

                //Pitch and roll need to be inverted to operate in the sprite's coordinate system
                //Yaw stays the same
                angles.X = -angles.X;
                angles.Z = -angles.Z;

                return angles;
            }

            switch (type)
            {
                case SpriteType.FacingUpright:
                    {
                        //This is bugged in vanilla since it uses an origin that isn't initialized by sprite models, only other models
                        var angles = VectorUtils.VectorToAngles(-renderData.Origin);

                        //No pitch
                        angles.X = 0;

                        return angles;
                    }

                case SpriteType.ParallelUpright:
                    {
                        var angles = GetModifiedViewAngles();

                        //No pitch
                        angles.X = 0;

                        return angles;
                    }

                case SpriteType.Parallel:
                    {
                        return GetModifiedViewAngles();
                    }

                case SpriteType.Oriented:
                    {
                        return renderData.Angles;
                    }

                case SpriteType.ParallelOriented:
                    {
                        var angles = GetModifiedViewAngles();

                        //Apply roll
                        angles.Z -= renderData.Angles.Z;

                        return angles;
                    }

                default:
                    {
                        Logger.Warning($"{nameof(GetSpriteAngles)}: Bad sprite type {type}");
                        break;
                    }
            }

            return new Vector3();
        }
Exemple #12
0
    // Merges all pieces in a silhouette that have neighboring end points with each other
    public void MergeSilhouettePieces(Silhouette silhouette)
    {
        int threshold = SilhouetteMergingThreshold; // Maximum distance between two piece endpoints

        for (int i = 0; i < silhouette.Pieces.Count - 1; i++)
        {
            for (int j = i + 1; j < silhouette.Pieces.Count; j++)
            {
                SilhouettePiece sp1 = silhouette.Pieces[i];
                SilhouettePiece sp2 = silhouette.Pieces[j];

                LinkedListNode <ContourPixel>[] neighbors = VectorUtils.NeighboringStartOrEndPoints(sp1, sp2, threshold);
                if (neighbors[1] != null)
                {
                    //Debug.Log("Merging...");
                    silhouette.Pieces.Remove(sp1);
                    silhouette.Pieces.Remove(sp2);

                    SilhouettePiece mergedPiece = new SilhouettePiece();

                    LinkedListNode <ContourPixel> currentNode;
                    LinkedListNode <ContourPixel> nodeCopy;

                    if (neighbors[0].Next == null)
                    {
                        //Debug.Log("First piece 1");
                        currentNode = sp1.Points.First;
                        while (currentNode.Value != neighbors[0].Value) // Add all points up to first connecting point
                        {
                            nodeCopy = new LinkedListNode <ContourPixel>(currentNode.Value);
                            mergedPiece.Points.AddLast(nodeCopy);
                            currentNode = currentNode.Next;
                        }
                        nodeCopy = new LinkedListNode <ContourPixel>(neighbors[0].Value);
                        mergedPiece.Points.AddLast(nodeCopy); // Add first connecting point
                        currentNode = currentNode.Next;

                        nodeCopy = new LinkedListNode <ContourPixel>(neighbors[1].Value);
                        mergedPiece.Points.AddLast(nodeCopy); // Add second connecting point

                        if (neighbors[1].Next == null)
                        {
                            //Debug.Log("Second piece 1");
                            currentNode = sp2.Points.Last;
                            while (currentNode != null) // Add the rest of the points in the other piece
                            {
                                nodeCopy = new LinkedListNode <ContourPixel>(currentNode.Value);
                                mergedPiece.Points.AddLast(nodeCopy);
                                currentNode = currentNode.Previous;
                            }
                        }
                        else // neighbors[1].Previous == null
                        {
                            //Debug.Log("Second piece 1");
                            currentNode = sp2.Points.First;
                            while (currentNode != null) // Add the rest of the points in the other piece
                            {
                                nodeCopy = new LinkedListNode <ContourPixel>(currentNode.Value);
                                mergedPiece.Points.AddLast(nodeCopy);
                                currentNode = currentNode.Next;
                            }
                        }
                    }
                    else // (n.previous == null)
                    {
                        //Debug.Log("First piece 2");
                        currentNode = sp1.Points.Last;
                        while (currentNode.Value != neighbors[0].Value) // Add all points up to first connecting point
                        {
                            nodeCopy = new LinkedListNode <ContourPixel>(currentNode.Value);
                            mergedPiece.Points.AddLast(nodeCopy);
                            currentNode = currentNode.Previous;
                        }
                        nodeCopy = new LinkedListNode <ContourPixel>(neighbors[0].Value);
                        mergedPiece.Points.AddLast(nodeCopy); // Add first connecting point
                        currentNode = currentNode.Previous;

                        nodeCopy = new LinkedListNode <ContourPixel>(neighbors[1].Value);
                        mergedPiece.Points.AddLast(nodeCopy); // Add second connecting point

                        if (neighbors[1].Next == null)
                        {
                            //Debug.Log("Second piece 2");
                            currentNode = sp2.Points.Last;
                            while (currentNode != null) // Add the rest of the points in the other piece
                            {
                                nodeCopy = new LinkedListNode <ContourPixel>(currentNode.Value);
                                mergedPiece.Points.AddLast(nodeCopy);
                                currentNode = currentNode.Previous;
                            }
                        }
                        else // neighbors[1].Previous == null
                        {
                            //Debug.Log("Second piece 2");
                            currentNode = sp2.Points.First;
                            while (currentNode != null) // Add the rest of the points in the other piece
                            {
                                nodeCopy = new LinkedListNode <ContourPixel>(currentNode.Value);
                                mergedPiece.Points.AddLast(nodeCopy);
                                currentNode = currentNode.Next;
                            }
                        }
                    }
                    //Debug.Log("Added");
                    silhouette.Pieces.Add(mergedPiece);
                }
            }
        }
    }
Exemple #13
0
    // Takes a contour and draws its silhouette
    public Silhouette DrawSilhouette(Contour contour)
    {
        Silhouette silhouette = new Silhouette(contour.Color);

        int pixelCount = 0;

        ContourPixel dummyPixel = new ContourPixel
        {
            IsDummy = true
        };

        int sX, sY, nX, nY;

        ContourPixel startPixel = FindNextStartPixel(contour, dummyPixel);
        ContourPixel nextPixel  = startPixel;

        bool started;

        //try
        //{

        while (startPixel != null && pixelCount != contour.NumberOfPixels)
        {
            started = false;

            // Add the first pixel of the new silhouette piece
            SilhouettePiece silhouettePiece = new SilhouettePiece();
            silhouettePiece.Points.AddFirst(startPixel);

            sX = startPixel.XCoord;
            sY = startPixel.YCoord;

            nX = startPixel.XCoord;
            nY = startPixel.YCoord;

            // Check if outside window
            //---------------------------------------------------------------------------------------------
            if (VectorUtils.AdjustIteration(contour, nX, nY) == "go-left-or-right")
            {
                //Debug.Log("Over eller under");
                if ((contour.Pixels[nX - 1, nY] != null) && !contour.Pixels[nX - 1, nY].Visited)
                {
                    nX = nX - 1;
                }
                else if ((contour.Pixels[nX + 1, nY] != null) && !contour.Pixels[nX + 1, nY].Visited)
                {
                    nX = nX + 1;
                }
            }
            else if (VectorUtils.AdjustIteration(contour, nX, nY) == "go-up-or-right")
            {
                //Debug.Log("Venstre");
                if ((contour.Pixels[nX, nY + 1] != null) && !contour.Pixels[nX, nY + 1].Visited)
                {
                    nY = nY + 1;
                }
                else if ((contour.Pixels[nX + 1, nY] != null) && !contour.Pixels[nX + 1, nY].Visited)
                {
                    nX = nX + 1;
                }
            }
            else if (VectorUtils.AdjustIteration(contour, nX, nY) == "go-up-or-left")
            {
                //Debug.Log("Høyre");
                if ((contour.Pixels[nX, nY + 1] != null) && !contour.Pixels[nX, nY + 1].Visited)
                {
                    nY = nY + 1;
                }
                else if ((contour.Pixels[nX - 1, nY] != null) && !contour.Pixels[nX - 1, nY].Visited)
                {
                    nX = nX - 1;
                }
            }
            //---------------------------------------------------------------------------------------------

            while (VectorUtils.MoreToDraw(contour, nX, nY) && (!(nX == sX && nY == sY) || !started))
            {
                //previousPixel = nextPixel;

                nextPixel = StepToNextPixel(contour, nX, nY, nextPixel);

                nX = nextPixel.XCoord;
                nY = nextPixel.YCoord;
                pixelCount++;

                silhouettePiece.Points.AddLast(nextPixel);

                started = true;
            }

            startPixel = FindNextStartPixel(contour, startPixel);
            silhouette.Pieces.Add(silhouettePiece);
        }

        /*} catch (Exception e)
         * {
         *  return silhouettes;
         * }*/

        return(silhouette);
    }
Exemple #14
0
    private void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        #region Disable textures
        // Finne mesher
        allMeshes = new List <Transform>();
        foreach (GameObject go in UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects())
        {
            if (go.GetComponent <Transform>().childCount > 0)
            {
                if (go.GetComponent <Transform>().GetChild(0).GetComponent <Renderer>() != null)
                {
                    for (int i = 0; i < go.GetComponent <Transform>().childCount; i++)
                    {
                        allMeshes.Add(go.GetComponent <Transform>().GetChild(i));
                    }
                }
            }
        }

        // Fjerne teksturene
        for (int i = 0; i < allMeshes.Count; i++)
        {
            Material[] materials = allMeshes[i].GetComponent <Renderer>().materials;
            for (int j = 0; j < materials.Length; j++)
            {
                allMeshes[i].GetComponent <Renderer>().materials[j].mainTexture = null;
            }
        }
        #endregion

        #region Assigning group colors to meshes
        System.Random random = new System.Random();
        materialMap = new Dictionary <string, List <Color> >();

        // Give every triangle in a mesh a single, random color
        for (int i = 0; i < allMeshes.Count; i++)
        {
            List <Color> colorList = new List <Color>();
            Color        newColor  = VectorUtils.RandomRGB(random);

            Material[] materials = allMeshes[i].GetComponent <Renderer>().materials;
            String     meshName  = allMeshes[i].name;
            for (int j = 0; j < materials.Length; j++)
            {
                Color oldColor = materials[j].color; // Original color
                colorList.Add(oldColor);

                allMeshes[i].GetComponent <Renderer>().materials[j].color = newColor; // Temporary ID color
            }
            materialMap.Add(meshName, colorList);
        }

        #endregion

        #region Per-Pixel Linked list

        GeneratePerPixelLinkedList();

        #endregion

        #region ID rendering

        camA.Render();

        if (!runOnceId)
        {
            idContoursAllLayers = new List <List <Contour> >();

            int i = 0;
            while (i < NumberOfLayers) // *4
            {
                Shader.SetGlobalInt("_loopMax", i);

                if (SortLayersByDepth)
                {
                    Shader.SetGlobalFloat("_sortLayers", 1);
                }
                else
                {
                    Shader.SetGlobalFloat("_sortLayers", 0);
                }

                Graphics.ClearRandomWriteTargets();
                Graphics.SetRandomWriteTarget(1, nodeBuffer);
                //Graphics.SetRandomWriteTarget(2, head);

                RenderTexture renderTex = RenderTexture.GetTemporary(Width, Height, 0, RenderTextureFormat.Default);
                Material      mat       = new Material(Shader.Find("Hidden/VectorShader"));

                Graphics.Blit(source, renderTex, mat);
                Graphics.Blit(renderTex, destination);

                // Copy from RenderTexture to a texture
                RenderTexture.active = renderTex;
                Texture2D tex2d = new Texture2D(Width, Height, TextureFormat.RGB24, false);
                tex2d.ReadPixels(new Rect(0, 0, renderTex.width, renderTex.height), 0, 0);
                tex2d.Apply();

                Rect rect = new Rect(0, 0, Width, Height);

                List <Contour> idContoursCurrentLayer = ExtractLayerContours(tex2d); // EXTRACTING CONTOURS
                idContoursAllLayers.Add(idContoursCurrentLayer);

                RenderTexture.ReleaseTemporary(renderTex);

                //VectorUtils.SaveTextureToFile(tex2d, "idldiTex" + i + ".png");

                i += 1; // += 4
            }
            //Graphics.ClearRandomWriteTargets(); // meg

            // Storing textures for viewing

            /*for (int j = 0; j < idContoursAllLayers.Count; j++)
             * {
             *  if (idContoursAllLayers[j].Count != 0)
             *  {
             *      Texture2D contourTexture = VectorUtils.ContourTexture(idContoursAllLayers[j], Width, Height);
             *      VectorUtils.SaveTextureToFile(contourTexture, "idTex" + j + ".png");
             *  }
             * }*/

            runOnceId = true;
        }
        #endregion

        #region Reset mesh colors

        // Reset all mesh colors
        for (int i = 0; i < allMeshes.Count; i++)
        {
            Material[]   materials = allMeshes[i].GetComponent <Renderer>().materials;
            String       meshName  = allMeshes[i].name;
            List <Color> colorList = materialMap[meshName];
            for (int j = 0; j < materials.Length; j++)
            {
                allMeshes[i].GetComponent <Renderer>().materials[j].color = colorList[j]; // NB: sharedMaterials ruins everything!!
            }
        }

        #endregion

        #region Per-Pixel Linked list 2

        ReleaseBuffers();

        GeneratePerPixelLinkedList();

        #endregion

        #region Rendering final scene

        camA.Render();

        if (!runOnceFinal)
        {
            colorContoursAllLayers = new List <List <Contour> >();

            int i = 0;
            while (i < NumberOfLayers) //*4
            {
                Shader.SetGlobalInt("_loopMax", i * 4);

                if (SortLayersByDepth)
                {
                    Shader.SetGlobalFloat("_sortLayers", 1);
                }
                else
                {
                    Shader.SetGlobalFloat("_sortLayers", 0);
                }

                Graphics.ClearRandomWriteTargets();
                Graphics.SetRandomWriteTarget(1, nodeBuffer);
                //Graphics.SetRandomWriteTarget(2, head);

                RenderTexture renderTex = RenderTexture.GetTemporary(Width, Height, 0, RenderTextureFormat.Default);
                Material      mat       = new Material(Shader.Find("Hidden/VectorShader"));

                Graphics.Blit(source, renderTex, mat);
                Graphics.Blit(renderTex, destination);

                // Copy from RenderTexture to a texture
                RenderTexture.active = renderTex;
                Texture2D tex2d = new Texture2D(Width, Height, TextureFormat.RGB24, false);
                tex2d.ReadPixels(new Rect(0, 0, renderTex.width, renderTex.height), 0, 0);
                tex2d.Apply();

                Rect rect = new Rect(0, 0, Width, Height);

                List <Contour> colorContoursCurrentLayer = ExtractLayerContours(tex2d);

                colorContoursAllLayers.Add(colorContoursCurrentLayer);

                RenderTexture.ReleaseTemporary(renderTex);

                //VectorUtils.SaveTextureToFile(tex2d, "ldiTex" + i + ".png");

                i += 1;
            }
            //Graphics.ClearRandomWriteTargets(); // meg

            // Storing textures for viewing

            /*for (int j = 0; j < colorContoursAllLayers.Count; j++)
             * {
             *  if (colorContoursAllLayers[j].Count != 0)
             *  {
             *      Texture2D contourTexture = VectorUtils.ContourTexture(colorContoursAllLayers[j], Width, Height);
             *      VectorUtils.SaveTextureToFile(contourTexture, "colorTex" + j + ".png");
             *  }
             * }*/

            runOnceFinal = true;

            #endregion

            #region Draw SVG

            List <List <ContourGroup> > contourGroupsAllLayers = IdentifyGroups(idContoursAllLayers, colorContoursAllLayers); // IDENTIFY GROUPS

            List <Layer> layers = new List <Layer>();
            foreach (List <ContourGroup> cGroups in contourGroupsAllLayers) // DRAW SILHOUETTES
            {
                Layer layer = new Layer();
                foreach (ContourGroup cg in cGroups)
                {
                    SilhouetteGroup sg = new SilhouetteGroup();
                    layer.SilhouetteGroups.Add(DrawSilhouettesForGroup(cg.Contours));
                }
                layers.Add(layer);
            }
            layers.Reverse();

            SVGProject.SVGWriter writer = new SVGProject.SVGWriter(Width, Height);
            writer.WriteSilhouettesToSVG(layers, Height); // WRITING SVG FILE

            try
            {
                // writer.SaveDocument(@"C:\Users\Vidar Hartveit Ure\Desktop\forsok.svg");
                // writer.SaveDocument(@"E:\Vidar\Desktop\forsok.svg");
                writer.SaveDocument(SVGFilePath);
            }
            catch (DirectoryNotFoundException e)
            {
                Debug.Log("Error on file saving: Directory not found!");
                QuitApplication();
            }

            int layerCount      = layers.Count;
            int groupCount      = 0;
            int pieceCount      = 0;
            int silhouetteCount = 0;
            int pointCount      = 0;

            foreach (Layer l in layers)
            {
                foreach (SilhouetteGroup sg in l.SilhouetteGroups)
                {
                    groupCount++;
                    foreach (Silhouette s in sg.Silhouettes)
                    {
                        silhouetteCount++;
                        foreach (SilhouettePiece spi in s.Pieces)
                        {
                            pieceCount++;
                            foreach (ContourPixel p in spi.Points)
                            {
                                pointCount++;
                            }
                        }
                    }
                }
            }

            Debug.Log("Number of layers: " + layerCount);
            Debug.Log("Number of silhouette groups: " + groupCount);
            Debug.Log("Number of silhouettes: " + silhouetteCount);
            Debug.Log("Number of silhouette pieces: " + pieceCount);
            Debug.Log("Number of points: " + pointCount);

            //Texture2D silhouetteTexture = LayerTexture(layers[0]);
            //SaveTextureToFile(silhouetteTexture, "siltex.png");

            QuitApplication();

            #endregion
        }
    }
 /// <summary>
 /// Return the raw margin from the decision hyperplane
 /// </summary>
 protected override Float Margin(ref VBuffer <Float> feat)
 {
     return(Bias + VectorUtils.DotProduct(ref feat, ref Weights) * WeightsScale);
 }
Exemple #16
0
        public static Vector2 GetStartPoint()
        {
            ushort buildingZM = AdrController.CurrentConfig.GlobalConfig.AddressingConfig.ZeroMarkBuilding;

            if (buildingZM == 0)
            {
                return(Vector2.zero);
            }
            else
            {
                return(BuildingManager.instance.m_buildings.m_buffer[buildingZM].m_flags == Building.Flags.None ? Vector2.zero : VectorUtils.XZ(BuildingManager.instance.m_buildings.m_buffer[buildingZM].m_position));
            }
        }
Exemple #17
0
        /// <summary>
        /// Find a flare within acceptable thermal range that will "decoy" for the passed heatsignature
        /// </summary>
        public static TargetSignatureData GetFlareTarget(Ray ray, float scanRadius, float highpassThreshold, bool allAspect, float heatSignature)
        {
            TargetSignatureData flareTarget = TargetSignatureData.noTarget;

            List <CMFlare> .Enumerator flare = BDArmorySetup.Flares.GetEnumerator();
            while (flare.MoveNext())
            {
                if (!flare.Current)
                {
                    continue;
                }

                float angle = Vector3.Angle(flare.Current.transform.position - ray.origin, ray.direction);
                if (angle < scanRadius)
                {
                    float score = flare.Current.thermal * Mathf.Clamp01(15 / angle);

                    score *= Mathf.Pow(1400, 2) / Mathf.Clamp((flare.Current.transform.position - ray.origin).sqrMagnitude, 90000, 36000000);
                    score *= Mathf.Clamp(Vector3.Angle(flare.Current.transform.position - ray.origin, -VectorUtils.GetUpDirection(ray.origin)) / 90, 0.5f, 1.5f);

                    // check acceptable range:
                    // flare cannot be too cool, but also not too bright
                    if ((score > heatSignature * 0.9) && (score < heatSignature * 1.15))
                    {
                        flareTarget = new TargetSignatureData(flare.Current, score);
                    }
                }
            }

            return(flareTarget);
        }
Exemple #18
0
    public void TessellateConvexContour_GeneratesTriangleFan()
    {
        // Build a square shape, flag it as convex
        var shape = new Shape()
        {
            Contours = new BezierContour[] {
                new BezierContour()
                {
                    Segments = new BezierPathSegment[] {
                        new BezierPathSegment()
                        {
                            P0 = new Vector2(0, 0), P1 = new Vector2(0.25f, 0), P2 = new Vector2(0.75f, 0)
                        },
                        new BezierPathSegment()
                        {
                            P0 = new Vector2(1, 0), P1 = new Vector2(1, 0.25f), P2 = new Vector2(1, 0.75f)
                        },
                        new BezierPathSegment()
                        {
                            P0 = new Vector2(1, 1), P1 = new Vector2(0.75f, 1), P2 = new Vector2(0.25f, 1)
                        },
                        new BezierPathSegment()
                        {
                            P0 = new Vector2(0, 1), P1 = new Vector2(0, 0.75f), P2 = new Vector2(0, 0.25f)
                        },
                    },
                    Closed = true
                }
            },
            Fill = new SolidFill()
            {
                Color = Color.red
            },
            IsConvex = true
        };

        var scene = new Scene()
        {
            Root = new SceneNode()
            {
                Shapes = new List <Shape> {
                    shape
                }
            }
        };
        var geoms = VectorUtils.TessellateScene(scene, MakeTessOptions(1000));

        Assert.AreEqual(1, geoms.Count);

        var geom = geoms[0];

        Assert.AreEqual(5, geom.Vertices.Length);
        Assert.AreEqual(12, geom.Indices.Length);
        Assert.AreEqual(new Vector2(0.5f, 0.5f), geom.Vertices[0]);
        Assert.AreEqual(new Vector2(0.0f, 0.0f), geom.Vertices[1]);
        Assert.AreEqual(new Vector2(1.0f, 0.0f), geom.Vertices[2]);
        Assert.AreEqual(new Vector2(1.0f, 1.0f), geom.Vertices[3]);
        Assert.AreEqual(new Vector2(0.0f, 1.0f), geom.Vertices[4]);

        Assert.AreEqual(0, geom.Indices[0]);
        Assert.AreEqual(1, geom.Indices[1]);
        Assert.AreEqual(2, geom.Indices[2]);
        Assert.AreEqual(0, geom.Indices[3]);
        Assert.AreEqual(2, geom.Indices[4]);
        Assert.AreEqual(3, geom.Indices[5]);
        Assert.AreEqual(0, geom.Indices[6]);
        Assert.AreEqual(3, geom.Indices[7]);
        Assert.AreEqual(4, geom.Indices[8]);
        Assert.AreEqual(0, geom.Indices[9]);
        Assert.AreEqual(4, geom.Indices[10]);
        Assert.AreEqual(1, geom.Indices[11]);
    }
        public Vector3 GetDirection(MissileBase missile, Vector3 targetPosition, Vector3 targetVelocity)
        {
            //set up
            if (_originalDistance == float.MinValue)
            {
                _startPoint       = missile.vessel.CoM;
                _originalDistance = Vector3.Distance(targetPosition, missile.vessel.CoM);
            }

            var surfaceDistanceVector = Vector3
                                        .Project((missile.vessel.CoM - _startPoint), (targetPosition - _startPoint).normalized);

            var pendingDistance = _originalDistance - surfaceDistanceVector.magnitude;

            if (missile.TimeIndex < 1)
            {
                return(missile.vessel.CoM + missile.vessel.Velocity() * 10);
            }

            Vector3 agmTarget;

            if (missile.vessel.verticalSpeed > 0 && pendingDistance > _originalDistance * 0.5)
            {
                missile.debugString.Append($"Ascending");
                missile.debugString.Append(Environment.NewLine);

                var freeFallTime = CalculateFreeFallTime(missile);
                missile.debugString.Append($"freeFallTime: {freeFallTime}");
                missile.debugString.Append(Environment.NewLine);

                var futureDistanceVector = Vector3
                                           .Project((missile.vessel.GetFuturePosition() - _startPoint), (targetPosition - _startPoint).normalized);

                var futureHorizontalSpeed = CalculateFutureHorizontalSpeed(missile);

                var horizontalTime = (_originalDistance - futureDistanceVector.magnitude) / futureHorizontalSpeed;


                missile.debugString.Append($"horizontalTime: {horizontalTime}");
                missile.debugString.Append(Environment.NewLine);

                if (freeFallTime >= horizontalTime)
                {
                    missile.debugString.Append($"Free fall achieved:");
                    missile.debugString.Append(Environment.NewLine);

                    missile.Throttle = Mathf.Clamp(missile.Throttle - 0.001f, 0.01f, 1f);
                }
                else
                {
                    missile.debugString.Append($"Free fall not achieved:");
                    missile.debugString.Append(Environment.NewLine);

                    missile.Throttle = Mathf.Clamp(missile.Throttle + 0.001f, 0.01f, 1f);
                }

                Vector3 dToTarget = targetPosition - missile.vessel.CoM;
                Vector3 direction = Quaternion.AngleAxis(Mathf.Clamp(missile.maxOffBoresight * 0.9f, 0, missile.BallisticAngle), Vector3.Cross(dToTarget, VectorUtils.GetUpDirection(missile.vessel.CoM))) * dToTarget;
                agmTarget = missile.vessel.CoM + direction;


                missile.debugString.Append($"Throttle: {missile.Throttle}");
                missile.debugString.Append(Environment.NewLine);
            }
            else
            {
                missile.debugString.Append($"Descending");
                missile.debugString.Append(Environment.NewLine);
                agmTarget = MissileGuidance.GetAirToGroundTarget(targetPosition, targetVelocity, missile.vessel, 1.85f);

                missile.Throttle = Mathf.Clamp((float)(missile.vessel.atmDensity * 10f), 0.01f, 1f);
            }

            if (missile is BDModularGuidance)
            {
                if (missile.vessel.InVacuum())
                {
                    missile.vessel.Autopilot.SetMode(VesselAutopilot.AutopilotMode.Prograde);
                    agmTarget = missile.vessel.CoM + missile.vessel.Velocity() * 100;
                }
                else
                {
                    missile.vessel.Autopilot.SetMode(VesselAutopilot.AutopilotMode.StabilityAssist);
                }
            }
            return(agmTarget);
        }
        private List <Image> CreateSoleLayerImages(TAMImageDiagram diagram, TAMMipmapLevel level)
        {
            var margin = _configuration.Margin;
            var soleImageResolution            = _configuration.SoleImagesResolutionPerLevel[level];
            var soleImageResolutionWithMargins = (soleImageResolution * (1 + margin * 2)).ToIntVector2();
            var marginLength = (soleImageResolutionWithMargins - soleImageResolution) / 2;

            var outImages = Enumerable.Range(0, _layersCount)
                            .Select(c => new Bitmap((int)soleImageResolutionWithMargins.X, (int)soleImageResolutionWithMargins.Y, PixelFormat.Format32bppPArgb))
                            .ToList();

            var occupancyArray = new int[(int)soleImageResolutionWithMargins.X, (int)soleImageResolutionWithMargins.Y];

            //Debug.Log($"OutiMages: {outImages[0].Size} || SoleImageResolution {soleImageResolution} Sole with margins {soleImageResolutionWithMargins}");
            foreach (var stroke in diagram.Strokes)
            {
                using (ImageFactory strokeFactory = new ImageFactory(true))
                {
                    var strokeSizeInPixels = VectorUtils.MemberwiseMultiply(
                        new Vector2(stroke.Length, stroke.Height * _configuration.StrokeHeightMultiplierPerLevel[level]), soleImageResolution.ToFloatVec()).ToIntVector2();
                    var rotation = Mathf.Rad2Deg * stroke.Rotation;

                    var rotatedStrokeImage = strokeFactory.Load(_strokeImage)
                                             .Resize(new ResizeLayer(new Size(strokeSizeInPixels.X, strokeSizeInPixels.Y), ResizeMode.Stretch))
                                             .Rotate(rotation).Image;
                    var imageWithId = AddIdToStrokeImage(rotatedStrokeImage, (uint)stroke.Id);

                    var position = VectorUtils.MemberwiseMultiply(UvToMarginUv(stroke.Center), soleImageResolutionWithMargins.ToFloatVec()).ToIntVector2();
                    position -= new IntVector2(rotatedStrokeImage.Width / 2, rotatedStrokeImage.Height / 2);

                    for (int x = 0; x < imageWithId.Size.Width; x++)
                    {
                        for (int y = 0; y < imageWithId.Size.Height; y++)
                        {
                            var inImagePosition = position + new IntVector2(x, y);

                            uint offsetBitX = 0;
                            uint offsetBitY = 0;
                            if (inImagePosition.X - marginLength.X / 2 >= soleImageResolution.X || inImagePosition.X - marginLength.X * 1.5 < 0)
                            {
                                offsetBitX = 1;
                            }
                            if (inImagePosition.Y - marginLength.Y / 2 >= soleImageResolution.Y || inImagePosition.Y - marginLength.Y * 1.5 < 0)
                            {
                                offsetBitY = 1;
                            }

                            inImagePosition.X = inImagePosition.X % soleImageResolutionWithMargins.X; //probably not needed
                            inImagePosition.Y = inImagePosition.Y % soleImageResolutionWithMargins.Y;

                            var strokePixel = imageWithId.GetPixel(x, y);

                            byte newGColor = (byte)((strokePixel.G | (offsetBitX << 6)) | offsetBitY << 7);
                            strokePixel = Color.FromArgb(strokePixel.A, strokePixel.R, newGColor, strokePixel.B);

                            if (strokePixel.A > 0)
                            {
                                var layerIndex = 0;
                                var occupancy  = occupancyArray[inImagePosition.X, inImagePosition.Y];
                                if (occupancy != 0)
                                {
                                    layerIndex = (occupancy) % _layersCount;
                                }
                                occupancyArray[inImagePosition.X, inImagePosition.Y]++;

                                if (!_configuration.UseSmoothAlpha)
                                {
                                    var a = strokePixel.A;
                                    if (a > 0)
                                    {
                                        a = 255;
                                    }

                                    strokePixel = Color.FromArgb(a, strokePixel.R, strokePixel.G, strokePixel.B);
                                }

                                if (!_configuration.UseDithering)
                                {
                                    outImages[layerIndex].SetPixel(inImagePosition.X, inImagePosition.Y, strokePixel);
                                }
                                else
                                {
                                    var oldPixel = outImages[layerIndex].GetPixel(inImagePosition.X, inImagePosition.Y);
                                    if (_configuration.UseSmoothAlpha)
                                    {
                                        var oldAlpha = oldPixel.A;
                                        var maxAlpha = Mathf.Max(oldAlpha, strokePixel.A);
                                        strokePixel = Color.FromArgb(maxAlpha, strokePixel.R, strokePixel.G, strokePixel.B);

                                        if (layerIndex != 0)
                                        {
                                            var layer0Pixel    = outImages[0].GetPixel(inImagePosition.X, inImagePosition.Y);
                                            var layer0OldAlpha = layer0Pixel.A;
                                            if (layer0OldAlpha < strokePixel.A)
                                            {
                                                var newLayer0Pixel = Color.FromArgb(strokePixel.A, layer0Pixel.R, layer0Pixel.G, layer0Pixel.B);
                                                outImages[0].SetPixel(inImagePosition.X, inImagePosition.Y, newLayer0Pixel);
                                            }
                                        }
                                    }

                                    var  ditheringModuler  = Mathf.CeilToInt((float)occupancy / _layersCount) + 1;
                                    bool ditherPixelActive = (inImagePosition.X + inImagePosition.Y) % ditheringModuler == 0;

                                    if (ditherPixelActive)
                                    {
                                        outImages[layerIndex].SetPixel(inImagePosition.X, inImagePosition.Y, strokePixel);
                                    }
                                    else
                                    {
                                        var updatedOldPixel = Color.FromArgb(strokePixel.A, oldPixel.R, oldPixel.G, oldPixel.B);
                                        outImages[layerIndex].SetPixel(inImagePosition.X, inImagePosition.Y, updatedOldPixel);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return(outImages.Cast <Image>().ToList());
        }
        private static Float[] Train(IHost host, ColInfo[] infos, Arguments args, IDataView trainingData)
        {
            Contracts.AssertValue(host, "host");
            host.AssertNonEmpty(infos);

            var       avgDistances  = new Float[infos.Length];
            const int reservoirSize = 5000;

            bool[] activeColumns = new bool[trainingData.Schema.ColumnCount];
            for (int i = 0; i < infos.Length; i++)
            {
                activeColumns[infos[i].Source] = true;
            }

            var reservoirSamplers = new ReservoirSamplerWithReplacement <VBuffer <Float> > [infos.Length];

            using (var cursor = trainingData.GetRowCursor(col => activeColumns[col]))
            {
                var rng = args.Seed.HasValue ? RandomUtils.Create(args.Seed) : host.Rand;
                for (int i = 0; i < infos.Length; i++)
                {
                    if (infos[i].TypeSrc.IsVector)
                    {
                        var get = cursor.GetGetter <VBuffer <Float> >(infos[i].Source);
                        reservoirSamplers[i] = new ReservoirSamplerWithReplacement <VBuffer <Float> >(rng, reservoirSize, get);
                    }
                    else
                    {
                        var   getOne = cursor.GetGetter <Float>(infos[i].Source);
                        Float val    = 0;
                        ValueGetter <VBuffer <Float> > get =
                            (ref VBuffer <Float> dst) =>
                        {
                            getOne(ref val);
                            dst = new VBuffer <float>(1, new[] { val });
                        };
                        reservoirSamplers[i] = new ReservoirSamplerWithReplacement <VBuffer <Float> >(rng, reservoirSize, get);
                    }
                }

                while (cursor.MoveNext())
                {
                    for (int i = 0; i < infos.Length; i++)
                    {
                        reservoirSamplers[i].Sample();
                    }
                }
                for (int i = 0; i < infos.Length; i++)
                {
                    reservoirSamplers[i].Lock();
                }
            }

            for (int iinfo = 0; iinfo < infos.Length; iinfo++)
            {
                var instanceCount = reservoirSamplers[iinfo].NumSampled;

                // If the number of pairs is at most the maximum reservoir size / 2, we go over all the pairs,
                // so we get all the examples. Otherwise, get a sample with replacement.
                VBuffer <Float>[] res;
                int resLength;
                if (instanceCount < reservoirSize && instanceCount * (instanceCount - 1) <= reservoirSize)
                {
                    res       = reservoirSamplers[iinfo].GetCache();
                    resLength = reservoirSamplers[iinfo].Size;
                    Contracts.Assert(resLength == instanceCount);
                }
                else
                {
                    res       = reservoirSamplers[iinfo].GetSample().ToArray();
                    resLength = res.Length;
                }

                // If the dataset contains only one valid Instance, then we can't learn anything anyway, so just return 1.
                if (instanceCount <= 1)
                {
                    avgDistances[iinfo] = 1;
                }
                else
                {
                    Float[] distances;
                    var     sub = args.Column[iinfo].MatrixGenerator;
                    if (sub == null)
                    {
                        sub = args.MatrixGenerator;
                    }
                    // create a dummy generator in order to get its type.
                    // REVIEW this should be refactored. See https://github.com/dotnet/machinelearning/issues/699
                    var  matrixGenerator = sub.CreateComponent(host, 1);
                    bool gaussian        = matrixGenerator is GaussianFourierSampler;

                    // If the number of pairs is at most the maximum reservoir size / 2, go over all the pairs.
                    if (resLength < reservoirSize)
                    {
                        distances = new Float[instanceCount * (instanceCount - 1) / 2];
                        int count = 0;
                        for (int i = 0; i < instanceCount; i++)
                        {
                            for (int j = i + 1; j < instanceCount; j++)
                            {
                                distances[count++] = gaussian ? VectorUtils.L2DistSquared(ref res[i], ref res[j])
                                    : VectorUtils.L1Distance(ref res[i], ref res[j]);
                            }
                        }
                        host.Assert(count == distances.Length);
                    }
                    else
                    {
                        distances = new Float[reservoirSize / 2];
                        for (int i = 0; i < reservoirSize - 1; i += 2)
                        {
                            // For Gaussian kernels, we scale by the L2 distance squared, since the kernel function is exp(-gamma ||x-y||^2).
                            // For Laplacian kernels, we scale by the L1 distance, since the kernel function is exp(-gamma ||x-y||_1).
                            distances[i / 2] = gaussian ? VectorUtils.L2DistSquared(ref res[i], ref res[i + 1]) :
                                               VectorUtils.L1Distance(ref res[i], ref res[i + 1]);
                        }
                    }

                    // If by chance, in the random permutation all the pairs are the same instance we return 1.
                    Float median = MathUtils.GetMedianInPlace(distances, distances.Length);
                    avgDistances[iinfo] = median == 0 ? 1 : median;
                }
            }
            return(avgDistances);
        }
Exemple #22
0
        private void RenderNotConnectLine(RenderManager.CameraInfo cameraInfo)
        {
            var bezier = new Bezier3()
            {
                a = SelectPoint.Position,
                b = SelectPoint.Direction,
                c = SelectPoint.Direction.Turn90(true),
                d = NodeMarkupTool.MouseWorldPosition,
            };

            Line2.Intersect(VectorUtils.XZ(bezier.a), VectorUtils.XZ(bezier.a + bezier.b), VectorUtils.XZ(bezier.d), VectorUtils.XZ(bezier.d + bezier.c), out _, out float v);
            bezier.c = v >= 0 ? bezier.c : -bezier.c;

            NetSegment.CalculateMiddlePoints(bezier.a, bezier.b, bezier.d, bezier.c, true, true, out bezier.b, out bezier.c);
            NodeMarkupTool.RenderBezier(cameraInfo, bezier, Colors.Hover);
        }
Exemple #23
0
        public static void Postfix(RenderManager.CameraInfo cameraInfo, ushort vehicleID, Color color)
        {
            Vehicle     vehicleData = Singleton <VehicleManager> .instance.m_vehicles.m_buffer[vehicleID];
            VehicleInfo vehicleInfo = vehicleData.Info;

            if (vehicleInfo.m_vehicleType != VehicleInfo.VehicleType.Ship && vehicleInfo.m_vehicleType != VehicleInfo.VehicleType.Ferry)
            {
                return;
            }

            uint targetFrame = GetTargetFrame(ref vehicleData, vehicleInfo, vehicleID);

            Vehicle.Frame frameData  = vehicleData.GetFrameData(targetFrame - 16);
            Vector3       position   = frameData.m_position;
            Vector2       xz         = VectorUtils.XZ(frameData.m_position);
            float         y          = position.y;
            Quaternion    rotation   = frameData.m_rotation;
            Vector3       size       = vehicleData.Info.m_generatedInfo.m_size;
            Vector2       forwardDir = VectorUtils.XZ(rotation * Vector3.forward).normalized;
            Vector2       rightDir   = VectorUtils.XZ(rotation * Vector3.right).normalized;
            float         circleMinY = y - vehicleInfo.m_generatedInfo.m_negativeHeight - 50f;
            float         circleMaxY = y + vehicleInfo.m_generatedInfo.m_size.y + 50f;

            Quad2 passingQuad = new Quad2 {
                a = xz - 0.5f * size.z * forwardDir - 0.5f * size.x * rightDir,
                b = xz - 0.5f * size.z * forwardDir + 0.5f * size.x * rightDir,
                c = xz + 0.75f * size.z * forwardDir + 0.5f * size.x * rightDir,
                d = xz + 0.75f * size.z * forwardDir - 0.5f * size.x * rightDir
            };

            DrawSearchConeQuad(cameraInfo, circleMinY, circleMaxY, passingQuad);

            RenderPos(vehicleData.GetTargetPos(0), vehicleInfo, cameraInfo);
            RenderPos(vehicleData.GetTargetPos(1), vehicleInfo, cameraInfo);
            RenderPos(vehicleData.GetTargetPos(2), vehicleInfo, cameraInfo);
            RenderPos(vehicleData.GetTargetPos(3), vehicleInfo, cameraInfo);

            float halfWidth = vehicleData.Info.m_generatedInfo.m_size.x / 2;
            Quad2 quad01    = GetShipQuad(vehicleData.m_targetPos0, vehicleData.m_targetPos1, halfWidth);
            Quad2 quad12    = GetShipQuad(vehicleData.m_targetPos1, vehicleData.m_targetPos2, halfWidth);
            Quad2 quad23    = GetShipQuad(vehicleData.m_targetPos2, vehicleData.m_targetPos3, halfWidth);

            DrawSearchConeQuad2(cameraInfo, circleMinY, circleMaxY, quad01);
            DrawSearchConeQuad2(cameraInfo, circleMinY, circleMaxY, quad12);
            DrawSearchConeQuad2(cameraInfo, circleMinY, circleMaxY, quad23);

            Vector2 quadMin = Vector2.Min(Vector2.Min(passingQuad.Min(), quad01.Min()), Vector2.Min(quad12.Min(), quad23.Min()));
            Vector2 quadMax = Vector2.Max(Vector2.Max(passingQuad.Max(), quad01.Max()), Vector2.Max(quad12.Max(), quad23.Max()));
            float   yMin    = Mathf.Min(Mathf.Min(vehicleData.m_targetPos0.y, vehicleData.m_targetPos1.y),
                                        Mathf.Min(vehicleData.m_targetPos2.y, vehicleData.m_targetPos3.y));
            float yMax = Mathf.Max(Mathf.Max(vehicleData.m_targetPos0.y, vehicleData.m_targetPos1.y),
                                   Mathf.Max(vehicleData.m_targetPos2.y, vehicleData.m_targetPos3.y));

            int             minGridX        = Math.Max((int)((quadMin.x - 72f) / 64f + 135f), 0);
            int             minGridZ        = Math.Max((int)((quadMin.y - 72f) / 64f + 135f), 0);
            int             maxGridX        = Math.Min((int)((quadMax.x + 72f) / 64f + 135f), 269);
            int             maxGridZ        = Math.Min((int)((quadMax.y + 72f) / 64f + 135f), 269);
            float           minY            = yMin - vehicleInfo.m_generatedInfo.m_negativeHeight - 2f;
            float           maxY            = yMax + vehicleInfo.m_generatedInfo.m_size.y + 2f;
            BuildingManager buildingManager = Singleton <BuildingManager> .instance;

            for (int gridZ = minGridZ; gridZ <= maxGridZ; gridZ++)
            {
                for (int gridX = minGridX; gridX <= maxGridX; gridX++)
                {
                    ushort buildingID = buildingManager.m_buildingGrid[gridZ * 270 + gridX];
                    while (buildingID != 0)
                    {
                        bool overlap01 = buildingManager.m_buildings.m_buffer[buildingID].OverlapQuad(buildingID,
                                                                                                      quad01, minY, maxY, ItemClass.CollisionType.Terrain);
                        bool overlap12 = buildingManager.m_buildings.m_buffer[buildingID].OverlapQuad(buildingID,
                                                                                                      quad12, minY, maxY, ItemClass.CollisionType.Terrain);
                        bool overlap23 = buildingManager.m_buildings.m_buffer[buildingID].OverlapQuad(buildingID,
                                                                                                      quad23, minY, maxY, ItemClass.CollisionType.Terrain);
                        bool overlap = overlap01 || overlap12 || overlap23;

                        Color color2 = (overlap ? Color.magenta : Color.white);
                        BuildingTool.RenderOverlay(cameraInfo, ref buildingManager.m_buildings.m_buffer[buildingID], color2, color2);
                        buildingID = buildingManager.m_buildings.m_buffer[buildingID].m_nextGridBuilding;
                    }
                }
            }

            //float searchConeLength = (vehicleInfo.m_vehicleType == VehicleInfo.VehicleType.Ship)
            //    ? ShipAICheckOtherVehiclesPatch.kSearchConeLength
            //    : FerryAICheckOtherVehiclesPatch.kSearchConeLength;

            //uint targetFrame = GetTargetFrame(ref vehicleData, vehicleInfo, vehicleID);
            //Vehicle.Frame frameData = vehicleData.GetFrameData(targetFrame - 16);
            //Vector3 position = frameData.m_position;
            //Vector2 xz = VectorUtils.XZ(frameData.m_position);
            //float y = position.y;
            //Quaternion rotation = frameData.m_rotation;
            //Vector3 size = vehicleData.Info.m_generatedInfo.m_size;
            //Vector2 forwardDir = VectorUtils.XZ(rotation * Vector3.forward).normalized;
            //Vector2 rightDir = VectorUtils.XZ(rotation * Vector3.right).normalized;
            //float circleMinY = y - vehicleInfo.m_generatedInfo.m_negativeHeight - 50f;
            //float circleMaxY = y + vehicleInfo.m_generatedInfo.m_size.y + 50f;

            //Quad2 searchConeQuad = new Quad2 {
            //    a = xz - 0.5f * size.z * forwardDir - 0.5f * size.x * rightDir,
            //    b = xz - 0.5f * size.z * forwardDir + 0.5f * size.x * rightDir,
            //    c = xz + (0.5f * size.z + searchConeLength) * forwardDir + 2f * size.x * rightDir,
            //    d = xz + (0.5f * size.z + searchConeLength) * forwardDir - 2f * size.x * rightDir
            //};
            //DrawSearchConeQuad(cameraInfo, circleMinY, circleMaxY, searchConeQuad);

            //Quad2 passingQuad = new Quad2 {
            //    a = xz - 0.5f * size.z * forwardDir - 0.5f * size.x * rightDir,
            //    b = xz - 0.5f * size.z * forwardDir + 0.5f * size.x * rightDir,
            //    c = xz + 1f * size.z * forwardDir + 0.5f * size.x * rightDir,
            //    d = xz + 1f * size.z * forwardDir - 0.5f * size.x * rightDir
            //};
            //DrawSearchConeQuad(cameraInfo, circleMinY, circleMaxY, passingQuad);

            //Vector2 searchConeMin = searchConeQuad.Min();
            //Vector2 searchConeMax = searchConeQuad.Max();
            //Singleton<RenderManager>.instance.OverlayEffect.DrawCircle(cameraInfo, Color.yellow, VectorUtils.X_Y(searchConeMin), 20f, circleMinY, circleMaxY, renderLimits: false, alphaBlend: true);
            //Singleton<RenderManager>.instance.OverlayEffect.DrawCircle(cameraInfo, Color.yellow, VectorUtils.X_Y(searchConeMax), 20f, circleMinY, circleMaxY, renderLimits: false, alphaBlend: true);

            //int minGridX = Math.Max((int)((searchConeMin.x - 72f) / 64f + 135f), 0);
            //int minGridZ = Math.Max((int)((searchConeMin.y - 72f) / 64f + 135f), 0);
            //int maxGridX = Math.Min((int)((searchConeMax.x + 72f) / 64f + 135f), 269);
            //int maxGridZ = Math.Min((int)((searchConeMax.y + 72f) / 64f + 135f), 269);
            //DrawBuildingGridRange(cameraInfo, circleMinY, circleMaxY, minGridX, minGridZ, maxGridX, maxGridZ);

            //float minY = y - vehicleInfo.m_generatedInfo.m_negativeHeight - 2f;
            //float maxY = y + vehicleInfo.m_generatedInfo.m_size.y + 2f;
            //BuildingManager buildingManager = Singleton<BuildingManager>.instance;
            //for (int gridZ = minGridZ; gridZ <= maxGridZ; gridZ++) {
            //    for (int gridX = minGridX; gridX <= maxGridX; gridX++) {
            //        ushort buildingID = buildingManager.m_buildingGrid[gridZ * 270 + gridX];
            //        while (buildingID != 0) {
            //            Color color2 = (buildingManager.m_buildings.m_buffer[buildingID].OverlapQuad(buildingID, searchConeQuad, minY, maxY, ItemClass.CollisionType.Terrain) ? Color.magenta : Color.white);
            //            BuildingTool.RenderOverlay(cameraInfo, ref buildingManager.m_buildings.m_buffer[buildingID], color2, color2);
            //            buildingID = buildingManager.m_buildings.m_buffer[buildingID].m_nextGridBuilding;
            //        }
            //    }
            //}
        }
Exemple #24
0
        protected override double[] GetGradient(IChannel ch)
        {
            Contracts.AssertValue(ch);
            _previousGradient = _currentGradient;

            _currentGradient = ObjectiveFunction.GetGradient(ch, TrainingScores.Scores);
            // We need to make a copy of gradient coz the reference returned is private structare of ObejctiveFunctionBase is valid only till next GetGradient call
            _currentGradient = (double[])_currentGradient.Clone();

            double[] previousDk = _currentDk;

            //First iteration
            if (_previousGradient == null)
            {
                _previousGradient = _currentGradient;
            }
#if !POLAK_RIBIERE_STEP
            // Compute Beta[k] = curG[k] * (curG[k] - prevG[k])
            // TODO: this can be optimized for speed. Keeping it slow but simple for now
            double beta = VectorUtils.GetDotProduct(_currentGradient, VectorUtils.Subtract(_currentGradient, _previousGradient)) / VectorUtils.GetDotProduct(_previousGradient, _previousGradient);
#else //Fletcher Reeves step
            // Compute Beta[k] = (curG[k]*cutG[k]) / (prevG[k] * prevG[k])
            double beta = VectorUtils.GetDotProduct(currentGradient, currentGradient) / VectorUtils.GetDotProduct(previousGradient, previousGradient);
#endif
            if (beta < 0)
            {
                beta = 0;
            }

            ch.Info("beta: {0}", beta);
            VectorUtils.MutiplyInPlace(previousDk, beta);
            VectorUtils.AddInPlace(previousDk, _currentGradient);
            _currentDk = previousDk; // Reallay no-op opration

            // We know that LeastSquaresRegressionTreeLearner does not destroy gradients so we can return our reference that we will need in next iter.
            if (TreeLearner is LeastSquaresRegressionTreeLearner)
            {
                return(_currentDk);
            }
            // Assume that other treLearners destroy the gradient array so return a copy.
            else
            {
                return((double[])_currentDk.Clone());
            }
        }
Exemple #25
0
    public static RedLightController Create(PlayerController player, Vector2 _pos)
    {
        var prefab = player.redLightPrefab;
        var go     = GameObject.Instantiate(prefab);

        go.transform.position = VectorUtils.V23(_pos, go.transform.position.z);
        var sr            = go.GetComponentInChildren <SpriteRenderer>();
        var redLightTrans = go.transform;
        var rdLtCtrl      = new RedLightController();

        rdLtCtrl.posRef      = new ClassRef <Vector2>((pos) => redLightTrans.position = VectorUtils.V23(pos, redLightTrans.position.z), () => VectorUtils.V32(redLightTrans.position));
        rdLtCtrl.spriteAlpha = ApCtrl.CreateAlphaData(ApCtrl.SpriteAlpha(sr), player);
        rdLtCtrl.spriteAlpha.convertSpeed = player.redLightAlphaConvertSpeed;
        rdLtCtrl.lightAlpha = ApCtrl.CreateAlphaData(ApCtrl.LightRendererAlpha(go.GetComponentInChildren <LightRenderer>()), player);
        rdLtCtrl.lightAlpha.convertSpeed = player.redLightAlphaConvertSpeed;
        rdLtCtrl.go             = go;
        rdLtCtrl.mb             = player;
        rdLtCtrl.particleSystem = go.GetComponentInChildren <ParticleSystem>();
        rdLtCtrl.emission       = rdLtCtrl.particleSystem.emission;
        rdLtCtrl.EmissionEnable = false;
        return(rdLtCtrl);
    }
Exemple #26
0
        /// <summary>
        /// Initialize weights by running SGD up to specified tolerance.
        /// </summary>
        private protected virtual VBuffer <float> InitializeWeightsSgd(IChannel ch, FloatLabelCursor.Factory cursorFactory)
        {
            if (!Quiet)
            {
                ch.Info("Running SGD initialization with tolerance {0}", SgdInitializationTolerance);
            }

            int        numExamples  = 0;
            var        oldWeights   = VBufferUtils.CreateEmpty <float>(BiasCount + WeightCount);
            DTerminate terminateSgd =
                (in VBuffer <float> x) =>
            {
                if (++numExamples % 1000 != 0)
                {
                    return(false);
                }
                VectorUtils.AddMult(in x, -1, ref oldWeights);
                float normDiff = VectorUtils.Norm(oldWeights);
                x.CopyTo(ref oldWeights);
                // #if OLD_TRACING // REVIEW: How should this be ported?
                if (!Quiet)
                {
                    Console.Write(".");
                    if (numExamples % 50000 == 0)
                    {
                        Console.WriteLine("\t{0}\t{1}", numExamples, normDiff);
                    }
                }
                // #endif
                return(normDiff < SgdInitializationTolerance);
            };

            VBuffer <float>  result = default(VBuffer <float>);
            FloatLabelCursor cursor = null;

            try
            {
                float[] scratch = null;

                SgdOptimizer.DStochasticGradient lossSgd =
                    (in VBuffer <float> x, ref VBuffer <float> grad) =>
                {
                    // Zero out the gradient by sparsifying.
                    VBufferUtils.Resize(ref grad, grad.Length, 0);
                    EnsureBiases(ref grad);

                    if (cursor == null || !cursor.MoveNext())
                    {
                        if (cursor != null)
                        {
                            cursor.Dispose();
                        }
                        cursor = cursorFactory.Create();
                        if (!cursor.MoveNext())
                        {
                            return;
                        }
                    }
                    AccumulateOneGradient(in cursor.Features, cursor.Label, cursor.Weight, in x, ref grad, ref scratch);
                };

                VBuffer <float> sgdWeights;
                if (DenseOptimizer)
                {
                    sgdWeights = VBufferUtils.CreateDense <float>(BiasCount + WeightCount);
                }
                else
                {
                    sgdWeights = VBufferUtils.CreateEmpty <float>(BiasCount + WeightCount);
                }
                SgdOptimizer sgdo = new SgdOptimizer(terminateSgd);
                sgdo.Minimize(lossSgd, ref sgdWeights, ref result);
                // #if OLD_TRACING // REVIEW: How should this be ported?
                if (!Quiet)
                {
                    Console.WriteLine();
                }
                // #endif
                ch.Info("SGD initialization done in {0} rounds", numExamples);
            }
            finally
            {
                if (cursor != null)
                {
                    cursor.Dispose();
                }
            }

            return(result);
        }
        void ReceivePing(Vessel v, Vector3 source, RWRThreatTypes type, float persistTime)
        {
            if (v == null)
            {
                return;
            }
            if (referenceTransform == null)
            {
                return;
            }
            if (weaponManager == null)
            {
                return;
            }

            if (rwrEnabled && vessel && v == vessel)
            {
                //if we are airborne or on land, no Sonar or SLW type weapons on the RWR!
                if ((type == RWRThreatTypes.Torpedo || type == RWRThreatTypes.TorpedoLock || type == RWRThreatTypes.Sonar) && (vessel.situation != Vessel.Situations.SPLASHED))
                {
                    // rwr stays silent...
                    return;
                }

                if (type == RWRThreatTypes.MissileLaunch || type == RWRThreatTypes.Torpedo)
                {
                    StartCoroutine(
                        LaunchWarningRoutine(new TargetSignatureData(Vector3.zero,
                                                                     RadarUtils.WorldToRadar(source, referenceTransform, RwrDisplayRect, rwrDisplayRange),
                                                                     Vector3.zero, true, (float)type)));
                    PlayWarningSound(type, (source - vessel.transform.position).sqrMagnitude);
                    return;
                }
                else if (type == RWRThreatTypes.MissileLock)
                {
                    if (weaponManager && weaponManager.guardMode)
                    {
                        weaponManager.FireChaff();
                        // TODO: if torpedo inbound, also fire accoustic decoys (not yet implemented...)
                    }
                }

                int openIndex = -1;
                for (int i = 0; i < dataCount; i++)
                {
                    if (pingsData[i].exists &&
                        ((Vector2)pingsData[i].position -
                         RadarUtils.WorldToRadar(source, referenceTransform, RwrDisplayRect, rwrDisplayRange)).sqrMagnitude < 900f)    //prevent ping spam
                    {
                        break;
                    }

                    if (!pingsData[i].exists && openIndex == -1)
                    {
                        openIndex = i;
                    }
                }

                if (openIndex >= 0)
                {
                    referenceTransform.rotation = Quaternion.LookRotation(vessel.ReferenceTransform.up,
                                                                          VectorUtils.GetUpDirection(transform.position));

                    pingsData[openIndex] = new TargetSignatureData(Vector3.zero,
                                                                   RadarUtils.WorldToRadar(source, referenceTransform, RwrDisplayRect, rwrDisplayRange), Vector3.zero,
                                                                   true, (float)type); // HACK! Evil misuse of signalstrength for the threat type!
                    pingWorldPositions[openIndex] = source;                            //FIXME source is improperly defined
                    StartCoroutine(PingLifeRoutine(openIndex, persistTime));

                    PlayWarningSound(type, (source - vessel.transform.position).sqrMagnitude);
                }
            }
        }
Exemple #28
0
 public override int GetHashCode()
 {
     return(VectorUtils.GetHashCode(this.X, this.Y));
 }
Exemple #29
0
        public static void Postfix(ref NetSegment __instance)
        {
            if (__instance.m_flags != NetSegment.Flags.None)
            {
                var m_info = __instance.Info;
                if (m_info == null)
                {
                    return;
                }

                if (__instance.m_lanes != 0u || (m_info.m_lanes != null && m_info.m_lanes.Length != 0))
                {
                    //Patch Begin
                    NetManager instance  = Singleton <NetManager> .instance;
                    uint       firstLane = __instance.m_lanes;
                    float      num       = 0f;
                    float      num2      = 0f;
                    if ((m_info.m_netAI is RoadAI) || (m_info.m_netAI is RoadBridgeAI) || (m_info.m_netAI is RoadTunnelAI))
                    {
                        if (CSURUtil.IsCSURLaneOffset(m_info))
                        {
                            for (int i = 0; i < m_info.m_lanes.Length; i++)
                            {
                                if (firstLane == 0)
                                {
                                    break;
                                }
                                float        laneOffset     = 0;
                                NetInfo.Lane lane           = m_info.m_lanes[i];
                                float        laneOffsetUnit = CSURUtil.CSURLaneOffset(m_info, lane);
                                laneOffset = laneOffsetUnit * 3.75f;
                                //DebugLog.LogToFileOnly("lanepostion = " + lane.m_position.ToString() + " laneoffset = " + laneOffset.ToString());
                                float effort = (OptionUI.smoothLevel == 2) ? 0.002f : (OptionUI.smoothLevel == 1) ? 0.01f : 0.05f;
                                //EG: before patch: point1-point4 is 1.5*3.75
                                //After patch, point1-point4 is (1 1.3333 1.6667 2)*3.75
                                var     bezier        = instance.m_lanes.m_buffer[firstLane].m_bezier;
                                Vector3 newBezierA    = bezier.Position(0) + (new Vector3(-bezier.Tangent(0).z, 0, bezier.Tangent(0).x).normalized) * (laneOffset * 0.5f);
                                Vector3 newBezierA1   = bezier.Position(effort) + (new Vector3(-bezier.Tangent(effort).z, 0, bezier.Tangent(effort).x).normalized) * (laneOffset * (0.5f - effort));
                                Vector3 newBezierADir = VectorUtils.NormalizeXZ(newBezierA1 - newBezierA);
                                Vector3 newBezierD    = bezier.Position(1) + (new Vector3(bezier.Tangent(1).z, 0, -bezier.Tangent(1).x).normalized) * (laneOffset * 0.5f);
                                Vector3 newBezierD1   = bezier.Position(1f - effort) + (new Vector3(bezier.Tangent(1f - effort).z, 0, -bezier.Tangent(1f - effort).x).normalized) * (laneOffset * (0.5f - effort));
                                Vector3 newBezierDDir = VectorUtils.NormalizeXZ(newBezierD1 - newBezierD);

                                Bezier3 newBezier = default(Bezier3);
                                newBezier.a = newBezierA;
                                newBezier.d = newBezierD;

                                //Try to get smooth bezier as close as real roadmesh
                                NetSegment.CalculateMiddlePoints(newBezierA, newBezierADir, newBezierD, newBezierDDir, true, true, out newBezier.b, out newBezier.c);

                                instance.m_lanes.m_buffer[firstLane].m_bezier = newBezier;
                                num      += instance.m_lanes.m_buffer[firstLane].UpdateLength();
                                num2     += 1f;
                                firstLane = instance.m_lanes.m_buffer[firstLane].m_nextLane;
                            }

                            if (num2 != 0f)
                            {
                                __instance.m_averageLength = num / num2;
                            }
                            else
                            {
                                __instance.m_averageLength = 0f;
                            }
                            bool flag7 = false;
                            if (__instance.m_averageLength < 11f && (instance.m_nodes.m_buffer[__instance.m_startNode].m_flags & NetNode.Flags.Junction) != 0 && (instance.m_nodes.m_buffer[__instance.m_endNode].m_flags & NetNode.Flags.Junction) != 0)
                            {
                                flag7 = true;
                            }
                            firstLane = __instance.m_lanes;
                            for (int j = 0; j < m_info.m_lanes.Length; j++)
                            {
                                if (firstLane == 0)
                                {
                                    break;
                                }
                                NetLane.Flags flags4 = (NetLane.Flags)(instance.m_lanes.m_buffer[firstLane].m_flags & -9);
                                if (flag7)
                                {
                                    flags4 |= NetLane.Flags.JoinedJunction;
                                }
                                instance.m_lanes.m_buffer[firstLane].m_flags = (ushort)flags4;
                                firstLane = instance.m_lanes.m_buffer[firstLane].m_nextLane;
                            }
                        }
                        //Patch End
                    }
                }
            }
        }
 /// <summary>
 /// Return the raw margin from the decision hyperplane
 /// </summary>
 protected Float AveragedMargin(ref VBuffer <Float> feat)
 {
     Contracts.Assert(Args.Averaged);
     return((TotalBias + VectorUtils.DotProduct(ref feat, ref TotalWeights)) / (Float)NumWeightUpdates);
 }