Esempio n. 1
0
	void OnEnable()
	{	// This function is called when the object is loaded (used for similar reasons to MonoBehaviour.Reset)
		id = GUID.Create(id);
		if (attribDataFabs == null) attribDataFabs = new List<RPGAttributeData>(0);
		if (levelCurve == null) levelCurve = AnimationCurve.Linear(1, 1, maxXP, maxLevel);
		if (xpAttribId == null) xpAttribId = new GUID();
	}
        /// <summary>
        /// Método para criar um objeto pessoa através do guid 
        /// </summary>
        /// <param name="guid"></param>
        /// <param name="viewOnly">Se true, traz apenas os campos de base, como GUID, EGUID, Nome Fantasia e Razão Social</param>
        /// <returns></returns>
        public static IPessoa Create(GUID guid, bool viewOnly = true)
        {
            if(GUID.IsNullOrEmpty(guid)) return null;

            //recuperar o tipo de pessoa
            Connection connection = null;

            try
            {
                connection = DbContext.CreateConnection();

                DataReader dataReader = connection.ExecuteReader("SELECT TipoPessoa FROM cad_Pessoa WHERE GUID = @p1", new[] {
                    new Parameter{
                        ParameterName = "@p1",
                        Value = guid
                    }});

                if(dataReader.Read())
                    return Create(dataReader.GetEnum<TipoPessoa>(0), guid);
            }
            finally
            {
                connection.Close();
            }

            return null;
        }
        /// <summary>
        /// Cria um item especial com base no GUID informado
        /// </summary>
        /// <param name="guid">GUID que deverá ser pesquisado</param>
        /// <returns>Item especial identificado</returns>
        public static Model.Cadastro.Item.Especial.IEspecial Create(GUID guid)
        {
            //se o GUID for inválido, não carregar
            if(GUID.IsNullOrEmpty(guid)) return null;

            //Buscar o tipo de item e se encontrar, criar.
            Connection connection = null;

            try
            {
                connection = DbContext.CreateConnection();

                DataReader dr = connection.ExecuteReader("SELECT Tipo FROM cad_ItemEsp WHERE GUID = @p1",
                    new Parameter[] {
                        new Parameter{
                            ParameterName = "@p1",
                            Value = guid
                        }
                    });

                if(dr.Read())
                {
                    return Create(dr.GetEnum<TipoItemEspecial>(0), guid);
                }
                else
                    throw new ArgumentException("Não foi encontrado nenhum item com o GUID informado");

            }
            finally
            {
                if(connection != null)
                    connection.Close();
            }
        }
Esempio n. 4
0
        public override int ReadPayload(MemoryStream stream,int length)
        {
            //Debug.Assert(length == GUID.GUID_LEN, "G2PacketQ2 supposed to read " + GUID.GUID_LEN + " but have to read " + length);

            guid = GUID.ReadGUID(stream);
            return (int)guid.bytes.Length;
        }
Esempio n. 5
0
 static extern bool SetupDiEnumDeviceInterfaces(
    IntPtr DeviceInfoSet,
    IntPtr DeviceInfoData,
    ref GUID lpHidGuid,
    UInt32 MemberIndex,
    ref SP_DEVICE_INTERFACE_DATA lpDeviceInterfaceData
 );
Esempio n. 6
0
 /// <summary>
 /// instancia o objeto
 /// </summary>
 public LanSKItem(GUID pai, GUID skPai, int tableHash)
     : this(pai, null, skPai, null, tableHash)
 {
     SKPai = skPai;
     ItemPai = pai;
     TableHash = tableHash;
 }
Esempio n. 7
0
 /// <summary>
 /// instancia o objeto
 /// </summary>
 public LanSK(GUID pai, GUID filho, int tableHash)
     : this(pai, filho, null, tableHash)
 {
     Pai = pai;
     Filho = filho;
     TableHash = Unimake.Convert.ToInt(tableHash);
     GUIDSK = Pai;
 }
        /// <summary>
        /// Cria o registro tipo R01 pelo GUID
        /// </summary>
        /// <param name="guid">GUID do registro tipo R01</param>
        /// <returns>Retorna o registro do tipo R01</returns>
        public static IRegistro01 Create(GUID guid)
        {
            IRegistro01 result = new Registro01();

            result.Populate(guid);

            return result;
        }
Esempio n. 9
0
 /// <summary>
 /// instancia o objeto
 /// </summary>
 public LanSKItem(GUID pai, GUID filho, GUID skPai, GUID skFilho, int tableHash)
     : this()
 {
     ItemPai = pai;
     ItemFilho = filho;
     SKPai = skPai;
     SKFilho = skFilho;
     TableHash = tableHash;
 }
        /// <summary>
        /// Cria um novo objeto IBaixaForma de acordo com seu tipo e popula o o objeto
        /// </summary>
        /// <param name="tipo">Tipo que deverá ser criado</param>
        /// <param name="g">identificador que deverá ser carregado</param>
        /// <returns></returns>
        public static IBaixaForma Create(TipoBaixaForma tipo, GUID g)
        {
            IBaixaForma result = Create(tipo);

            if(result != null)
                result.Populate(g);

            return result;
        }
        /// <summary>
        /// Instancia um movimento com base no item informado.
        /// <para>Utilize quando tiver apenas o item, mas não tem o movimento.</para>
        /// </summary>
        /// <param name="item">item base que deverá ser detectado o tipo de movimento</param>
        /// <param name="guid">Identificador do movimento</param>
        /// <returns></returns>
        public static IMovimento Create(IItem item, GUID guid)
        {
            if (item is Model.Faturamento.Lancamento.Movimento.Item.VendaCF.IItem)
                return new Data.Faturamento.Lancamento.Movimento.PreVenda.PreVenda(guid);
            else if (item is Model.Faturamento.Lancamento.Movimento.Item.PreVenda.IItem)
                return new Data.Faturamento.Lancamento.Movimento.DAV.DAV(guid);
            else if (item is Model.Faturamento.Lancamento.Movimento.Item.DAV.IItem)
                return new Data.Faturamento.Lancamento.Movimento.DAV.DAV(guid);
            else if (item is Model.Faturamento.Lancamento.Movimento.Item.Conferencia.IItem)
                return new Data.Faturamento.Lancamento.Movimento.Conferencia.Conferencia(guid);

            throw new NotImplementedException("Tipo de item não implementado");
        }
        /// <summary>
        /// Cria uma nova instancia de abertura ou fechamento de caixa com base no GUID informado
        /// </summary>
        /// <param name="guid">código do registro para criar a abertura ou fechamento de caixa</param>
        /// <returns></returns>
        public static AbreFechaCaixaBase Create(GUID guid)
        {
            AbreFechaCaixaBase result = null;

            //criar uma abertura de caixa, se o status do caixa for fechado, converter para fechamento
            result = new AbreCaixa(guid);

            //se o status for fechado, converter para um fechamento
            if(result.Status == Status.Fechado)
                result = new FechaCaixa(guid);

            return result;
        }
        /// <summary>
        /// Retorna o objeto identificado pelo GUID passado como parametro
        /// </summary>
        /// <param name="guid">Identificador do registro </param>
        /// <param name="viewOnly">Carrega apenas os dados de base.</param>
        /// <returns>Retorna o objeto carregado do tipo ILancamento </returns>
        public static ILancamento Create(GUID guid, bool viewOnly = true)
        {
            Connection connection = null;
            ILancamento result = null;

            try
            {
                connection = DbContext.CreateConnection();
                Tipo tipo = Tipo.CupomFiscal;
                Unimake.Data.Generic.DataReader dr =
                    connection.ExecuteReader(string.Format(@"SELECT
                                                                GUID                  AS p_GUID               ,
                                                                EGUID                 AS p_EGUID              ,
                                                                DataHoraCadastro      AS p_DataHoraCadastro   ,
                                                                GUIDUsuarioCadastro   AS p_GUIDUsuarioCadastro,
                                                                GUIDempresa           AS p_GUIDempresa        ,
                                                                Excluido              AS p_Excluido           ,
                                                                Tipo                  AS p_Tipo               ,
                                                                Status                AS p_Status             ,
                                                                Descricao             AS p_Descricao          ,
                                                                StatusEnvio           AS p_StatusEnvio        ,
                                                                StatusBaixa           AS p_StatusBaixa
                                                             FROM fat_lan WHERE fat_Lan.GUID='{0}'",
                                             guid.ToString()));

                if (dr.Read())
                {
                    tipo = dr.GetValue<Tipo>("p_Tipo");

                    if (viewOnly)
                    {
                        result = Create(tipo) as ILancamento;
                        DbContext.Populate(result, dr);
                        result.Status = dr.GetValue<Status>("p_Status");
                        result.Descricao = dr.GetValue<string>("p_Descricao");
                        result.StatusEnvio = dr.GetValue<StatusEnvio>("p_StatusEnvio");
                        result.StatusBaixa = dr.GetValue<StatusBaixa>("p_StatusBaixa");
                    }
                    else
                    {
                        result = Create(guid, tipo) as ILancamento;
                    }
                }
            }
            finally
            {
                connection.Close();
            }

            return result;
        }
Esempio n. 14
0
        /// <summary>
        /// instancia o objeto
        /// </summary>
        public LanSK(GUID pai, GUID filho, GUID sk, int tableHash)
            : this()
        {
            Pai = pai;
            Filho = filho;
            GUIDSK = sk;
            TableHash = tableHash;
            if(pai != null)
                Where.Add("GUIDLanPai", pai);
            if(sk != null)
                Where.Add("GUIDLanSK", sk);
            if(filho != null)
                Where.Add("GUIDLanFilho", filho);
            Where.Add("TableHash", TableHash);

            DbContext.Populate(this, Where);
        }
 /// <summary>
 /// Cria um item especial com base em seu tipo e retorna
 /// </summary>
 /// <param name="tipo">Tipo de item que deverá ser criado.</param>
 /// <param name="guid">identificador do item especial</param>
 /// <returns>Item especial criado de acordo com o tipo</returns>
 public static Model.Cadastro.Item.Especial.IEspecial Create(TipoItemEspecial tipo, GUID guid)
 {
     switch(tipo)
     {
         case TipoItemEspecial.DespesaAcessoria:
             return new DespesaAcessoria(guid);
         case TipoItemEspecial.Desconto:
             return new Desconto(guid);
         case TipoItemEspecial.EncargoFinanceiro:
             return new EncargoFinanceiro(guid);
         case TipoItemEspecial.Frete:
             return new Frete(guid);
         case TipoItemEspecial.Seguro:
             return new Seguro(guid);
         default:
             throw new NotImplementedException("O tipo de item especial informado ainda não foi implementado.");
     }
 }
Esempio n. 16
0
        /// <summary>
        /// Método Create para carregar a Pessoa passando o seu GUID e qual o tipo de Pessoa deseja-se carregar.
        /// </summary>
        /// <param name="tipo">Tipo de pessoa que deseja carregar. Exemplo: Usuario, Cliente, etc.</param>
        /// <param name="guid">Guid do Objeto</param>
        /// <param name="viewOnly">Se true, traz apenas os campos de base, como GUID, EGUID, Nome Fantasia e Razão Social</param>
        /// <returns>Retorna o objeto do tipo IPessoa </returns>
        public static IPessoa Create(TipoPessoa tipo, GUID guid, bool viewOnly = true)
        {
            IPessoa pessoa = Create(tipo) as PessoaBase;

            if(pessoa != null)
            {
                pessoa.GUID = guid;

                if(viewOnly)
                {
                    DataReader dr = DbContext.GetDisplayValues(pessoa, new Where {
                        { "cad_Pessoa.GUID", guid }
                    }).DataReader;

                    if(dr.Read())
                    {
                        pessoa.GUID = dr.GetString("p_GUID");
                        pessoa.EGUID = dr.GetString("p_EGUID");
                        pessoa.NomeFantasia = dr.GetString("p_NomeFantasia");
                        pessoa.RazaoSocial = dr.GetString("p_RazaoSocial");
                        pessoa.FisicaJuridica = dr.GetEnum<FisicaJuridica>("p_fisicajuridica");
                        pessoa.Fisica = new Data.Cadastro.Pessoa.Fisica.Fisica(pessoa.GUID);
                        pessoa.Juridica = new Data.Cadastro.Pessoa.Juridica.Juridica(pessoa.GUID);
                        pessoa.ContaCorrente = new ContaCorrente(dr.GetString("p_GUIDContaCorrente"));

                        pessoa.Enderecos = new Data.Cadastro.Pessoa.Endereco().Find<Model.Cadastro.Pessoa.IEndereco>(
                            new Where {
                                {"guidpessoa", pessoa.GUID}
                                });

                        pessoa.CanaisComunicacao = new Data.Cadastro.Pessoa.CanalComunicacao().Find<Model.Cadastro.Pessoa.ICanalComunicacao>(new Where
                        {
                            { "guidpessoa", pessoa.GUID }
                        });

                    }
                }
                else
                    pessoa.Populate(guid);
            }

            return pessoa;
        }
Esempio n. 17
0
        public static Model.Cadastro.TabelaPreco.IItem Create(Model.Cadastro.TabelaPreco.ITabelaPreco tabelaPreco, GUID guid)
        {
            Data.Cadastro.TabelaPreco.Item result = new Data.Cadastro.TabelaPreco.Item();
            result.Parent = tabelaPreco;
            result.Item = Data.Cadastro.Item.Produto.Acabado.Create(guid);

            if (result.Item == null)
                return null;//Não encontrou o produto cadastrado

            Connection connection = null;

            try
            {
                connection = DbContext.CreateConnection();
                DataReader dr = connection.ExecuteReader(@"SELECT GUIDTabelaPreco,
                                                                  GUIDItem,
                                                                  Preco
                                                            FROM cad_TabelaPrecoItem
                                                            WHERE GUIDTabelaPreco = @p1 AND
                                                                  GUIDItem = @p2", new[] {
                         new Parameter {
                             ParameterName = "@p1",
                             Value = tabelaPreco.GUID
                         },
                         new Parameter {
                             ParameterName = "@p2",
                             Value = result.Item.GUID
                         }
                     });

                if (dr.Read())
                {
                    result.Preco = dr.GetDouble("Preco");
                }
            }
            finally
            {
                connection.Close();
            }

            return result;
        }
Esempio n. 18
0
        /// <summary>
        /// Cria um novo item e retorna de acordo com o tipo identificado e carrega o mesmo pelo GUID
        /// </summary>
        /// <param name="guid">GUID de identificação do item</param>
        /// <param name="movimento">Movimento pai para validar o tipo de item</param>
        /// <returns></returns>
        public static ItemBase Create(IMovimento movimento, GUID guid)
        {
            ItemBase result = null;

            if (movimento is Model.Faturamento.Lancamento.Movimento.PreVenda.IPreVenda)
                result = new Data.Faturamento.Lancamento.Movimento.Item.PreVenda.Item(guid);
            else if (movimento is Model.Faturamento.Lancamento.Movimento.DAV.OS.IDAV)
                result = new Data.Faturamento.Lancamento.Movimento.Item.DAV.OS.Item(guid);
            else if (movimento is Model.Faturamento.Lancamento.Movimento.DAV.IDAV)
                result = new Data.Faturamento.Lancamento.Movimento.Item.DAV.Item(guid);
            else if (movimento is Model.Faturamento.Lancamento.Movimento.NFe.INFe)
                result = new Data.Faturamento.Lancamento.Movimento.Item.NFe.Item(guid);
            else if (movimento is Model.Faturamento.Lancamento.Movimento.NFManual.INFManual)
                result = new Data.Faturamento.Lancamento.Movimento.Item.NFManual.Item(guid);
            else if (movimento is Model.Faturamento.Lancamento.Movimento.Devolucao.IDevolucao)
                result = new Data.Faturamento.Lancamento.Movimento.Item.Devolucao.Item(guid);
            else if (movimento is Model.Faturamento.Lancamento.Movimento.Conferencia.IConferencia)
                result = new Data.Faturamento.Lancamento.Movimento.Item.Conferencia.Item();

            return result;
        }
Esempio n. 19
0
        public G2SearchResults(SearchTransaction transaction, GUID guid)
        {
            SearchManager = G2SearchManager.Instance;
            ACKPacket = new List<G2PacketQA>();
            Transaction = transaction;
            SearchGUID = guid;
            TotalFiles = 0;
            SharedTotalFiles = 0;
            PeersBrowsed = new HashSet<Peer>();

            SearchedWord = transaction.Keywords[0].KeywordName;
            Buffer = new PacketBuffer();
            SearchRegrouping = new G2SearchResultRegrouping(transaction, 0, false);
            ContinueRegrouping = true;
            StartSearchTime = DateTime.Now;
            StopSearchTimer = new System.Timers.Timer((double)Settings.SEARCH_TIME_OUT_MS);
            StopSearchTimer.AutoReset = false;
            StopSearchTimer.Elapsed += new ElapsedEventHandler(SearchTimeOut);

            RegroupingThread = new Thread(new ThreadStart(SearchResultThread));
        }
Esempio n. 20
0
        /// <summary>
        /// Retorna um novo produto pelo GUID, identificando o seu tipo
        /// </summary>
        /// <param name="guid">GUID para pesquisar o produto</param>
        /// <param name="viewOnly">Se true, traz apenas os campos de base, como GUID, EGUID, Nome Fantasia e Razão Social</param>
        /// <returns></returns>
        public static ItemBase Create(GUID guid, TipoItem tipo, bool viewOnly = true)
        {
            if(GUID.IsNullOrEmpty(guid)) return null;

            ItemBase result = null;

            Connection connection = null;

            try
            {
                connection = DbContext.CreateConnection();
                DataReader dr = connection.ExecuteReader(String.Format("SELECT TipoItem FROM cad_Item WHERE GUID = '{0}'", guid));

                if(dr.Read())
                {
                    result = Create(tipo);

                    if(viewOnly)
                    {
                        dr = DbContext.GetDisplayValues(result, new Where {
                            { "cad_Item.GUID", guid }
                        }).DataReader;

                        if(dr.Read())
                        {
                            result.Populate(dr.GetString("p_GUID"));
                        }
                    }
                    else
                        result.Populate(guid);
                }
            }
            finally
            {
                connection.Close();
            }

            return result;
        }
Esempio n. 21
0
 /// <summary>
 /// Installs a driver using its INF file
 /// </summary>
 /// <param name="filePath">Relative or absolute INF file path</param>
 /// <param name="hardwareID">ComponentID</param>
 /// <returns></returns>
 public static bool InstallInfDriver(string filePath, string hardwareID, string description = "")
 {
     // TODO: Win10 got wrong bitness onetime (???)
     if (IntPtr.Size == 4 && Environment.Is64BitOperatingSystem)
     {
         MessageBox.Show("This process is 32-bit but the OS is 64-bit. Only 64-bit processes can install 64-bit direvers.",
             "Driver Setup", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2, MessageBoxOptions.ServiceNotification);
         return false;
     }
     filePath = Path.GetFullPath(filePath);
     GUID classGuid = new GUID();
     char[] className = new char[MAX_CLASS_NAME_LEN];
     uint requiredSize = 0;
     SP_DEVINFO_DATA deviceInfoData = new SP_DEVINFO_DATA();
     deviceInfoData.cbSize = (uint)Marshal.SizeOf(deviceInfoData);
     // Use the INF File to extract the Class GUID
     if (!SetupDiGetINFClass(filePath, ref classGuid, className, MAX_CLASS_NAME_LEN, ref requiredSize))
         return false;
     // Create the container for the to-be-created Device Information Element
     IntPtr deviceInfoSet = SetupDiCreateDeviceInfoList(ref classGuid, IntPtr.Zero);
     if (deviceInfoSet == Kernel32.INVALID_HANDLE_VALUE)
         return false;
     // Now create the element. Use the Class GUID and Name from the INF file
     if (!SetupDiCreateDeviceInfo(deviceInfoSet, new string(className), ref classGuid, description, IntPtr.Zero, DICD_GENERATE_ID, ref deviceInfoData))
         return false;
     // Add the HardwareID to the Device's HardwareID property
     if (!SetupDiSetDeviceRegistryProperty(deviceInfoSet, ref deviceInfoData, SPDRP_HARDWAREID, Encoding.Unicode.GetBytes(hardwareID), (uint)Encoding.Unicode.GetByteCount(hardwareID)))
         return false;
     // Transform the registry element into an actual devnode in the PnP HW tree
     if (!SetupDiCallClassInstaller(DI_FUNCTION.DIF_REGISTERDEVICE, deviceInfoSet, ref deviceInfoData))
         return false;
     SetupDiDestroyDeviceInfoList(deviceInfoSet);
     // Update the driver for the device we just created
     if (!Newdev.UpdateDriverForPlugAndPlayDevices(IntPtr.Zero, hardwareID, filePath, Newdev.INSTALLFLAG_FORCE, IntPtr.Zero))
         return false;
     return true;
 }
        /// <summary>
        /// Retorna uma nova tabela de preços. Se o parâmetro viewOnly for true não retornará os itens da tabela
        /// </summary>
        /// <param name="guid">Identificador da tabela de preços</param>
        /// <param name="viewOnly">Se true, traz apenas os dados básicos da tabela</param>
        /// <returns></returns>
        public static ITabelaPreco Create(GUID guid, bool viewOnly = true)
        {
            Connection connection = null;
            ITabelaPreco result = new Data.Cadastro.TabelaPreco.TabelaPreco();

            try
            {
                connection = DbContext.CreateConnection();
                Command command = CommandFactory.PrepareSelect(result, new Where
                {
                    {
                        "GUID = @p1",
                        new Parameter {
                            ParameterName = "@p1",
                            Value = guid
                        }
                    },
                });

                DataReader dataReader = command.ExecuteReader();

                if(dataReader.Read())
                {
                    DbContext.Populate(result, dataReader);
                    result.Descricao = dataReader.GetValue<string>("p_Descricao");
                    result.Promocional = dataReader.GetValue<bool>("p_Promocional");
                    result.ValidadeInicial = dataReader.GetValue<DateTime>("p_ValidadeInicial");
                    result.ValidadeFinal = dataReader.GetValue<DateTime>("p_ValidadeFinal");
                }
            }
            finally
            {
                connection.Close();
            }

            return result;
        }
Esempio n. 23
0
        public override void Gravar()
        {
            Model.Cadastro.Veiculo.IVeiculo v = new OpenPOS.Data.Cadastro.Veiculo.Veiculo();
            AnoFabricacao a = new AnoFabricacao("06d24c3b-40cf-4bc0-a1f6-456fd9458c0a");
            v.AnoFabricacao = a;
            v.Placa = "ABC1234";
            v.Renavam = "12345678";
            GUIDVeiculo = v.Save();
            //DAV dav = new DAV();
            //dav.Veiculo = v;
            //dav.Itens.Add(new Item
            //{
            //    Quantidade = 10,
            //    ValorUnitarioBruto = 12.5,
            //    DescricaoNF = "Produto de teste um",
            //    Vendedor = new Vendedor("8c7aea3e-b28e-4664-8923-3327dfd462ad")
            //});

            //dav.Itens.Add(new Item
            //{
            //    Quantidade = 25,
            //    ValorUnitarioBruto = 15,
            //    DescricaoNF = "Produto de teste dois",
            //    Vendedor = new Vendedor("8c7aea3e-b28e-4664-8923-3327dfd462ad")
            //});

            //dav.Itens.Add(new Item
            //{
            //    Quantidade = 33,
            //    ValorUnitarioBruto = 17.5,
            //    DescricaoNF = "Produto de teste três",
            //    Vendedor = new Vendedor("8c7aea3e-b28e-4664-8923-3327dfd462ad")
            //});

            //GUID = dav.Save();
        }
Esempio n. 24
0
 public static extern ObjectIdentifier[] GetPlayerObjectIdentifiersInAsset(GUID asset, BuildTarget target);
Esempio n. 25
0
        private IEnumerable <ApproveInfo> ProcessLevel(Table item, int?assignmentMap, PXResultset <EPRule> rules)
        {
            foreach (EPRule rule in rules)
            {
                if (rule.RuleID == null || rule.IsActive != true)
                {
                    continue;
                }

                path.Add(rule.RuleID.Value);

                bool isSuccessful  = true;
                var  filteredItems = ExecuteRule(item, rule, ref isSuccessful);

                if (!isSuccessful || (filteredItems != null && filteredItems.Count == 0))
                {
                    continue;
                }

                Guid?OwnerID     = null;
                int? WorkgroupID = rule.WorkgroupID;

                switch (rule.RuleType)
                {
                case EPRuleType.Direct:

                    OwnerID = rule.OwnerID;

                    FillOwnerWorkgroup(ref OwnerID, ref WorkgroupID);

                    if (OwnerID == null && WorkgroupID == null)
                    {
                        continue;
                    }

                    yield return(new ApproveInfo()
                    {
                        OwnerID = OwnerID,
                        WorkgroupID = WorkgroupID,
                        RuleID = rule.RuleID,
                        StepID = rule.StepID,
                        WaitTime = rule.WaitTime
                    });

                    break;

                case EPRuleType.Document:

                    if (rule.OwnerSource == null)
                    {
                        continue;
                    }

                    PXView lineView    = null;
                    PXView primaryView = null;
                    Type   viewType    = null;
                    try
                    {
                        var s        = rule.OwnerSource;
                        var viewName = s.Substring(s.LastIndexOf("(") + 1, s.IndexOf(".") - (s.LastIndexOf("(") + 1));

                        if (String.Equals(viewName, processGraph.PrimaryView, StringComparison.InvariantCultureIgnoreCase))
                        {
                            primaryView = processGraph.Views[viewName];
                            viewType    = primaryView.GetItemType();
                        }
                        else
                        {
                            lineView = processGraph.Views[viewName];
                            viewType = lineView.GetItemType();
                        }
                    }
                    catch (Exception)
                    {
                        // ignored
                    }


                    bool queryContainsDetails = filteredItems != null && filteredItems.Count > 0 && ((PXResult)filteredItems[0])[viewType] != null;

                    var arrayToIterate = queryContainsDetails
                                                        ? filteredItems
                                                        : lineView?.SelectMulti() ?? primaryView.Cache.Current.SingleToList() ?? filteredItems;

                    foreach (object filteredItem in arrayToIterate)
                    {
                        if (filteredItem is PXResult)
                        {
                            var line = ((PXResult)filteredItem)[viewType];
                            processGraph.Caches[viewType].Current = line;
                        }
                        else
                        {
                            processGraph.Caches[viewType].Current = filteredItem;
                        }

                        string code = PXTemplateContentParser.Instance.Process(rule.OwnerSource, processGraph, viewType, null);

                        EPEmployee emp =
                            PXSelect <
                                EPEmployee,
                                Where <EPEmployee.acctCD, Equal <Required <EPEmployee.acctCD> > > >
                            .SelectWindowed(this, 0, 1, code);

                        Users user =
                            PXSelect <
                                Users,
                                Where <Users.username, Equal <Required <Users.username> > > >
                            .SelectWindowed(this, 0, 1, code);

                        OwnerID = emp != null
                                                                ? emp.UserID
                                                                : user != null
                                                                        ? user.PKID
                                                                        : GUID.CreateGuid(code);

                        if (OwnerID == null && WorkgroupID == null)
                        {
                            continue;
                        }

                        yield return(new ApproveInfo()
                        {
                            OwnerID = OwnerID,
                            WorkgroupID = WorkgroupID,
                            RuleID = rule.RuleID,
                            StepID = rule.StepID,
                            WaitTime = rule.WaitTime
                        });
                    }

                    break;

                case EPRuleType.Filter:

                    List <EPRuleBaseCondition> conditions =
                        PXSelectReadonly <EPRuleEmployeeCondition,
                                          Where <EPRuleEmployeeCondition.ruleID, Equal <Required <EPRule.ruleID> > > >
                        .Select(this, rule.RuleID)
                        .Select(_ => (EPRuleBaseCondition)_)
                        .ToList();

                    if (conditions.Count == 0)
                    {
                        break;
                    }

                    foreach (var approveInfo in GetEmployeesByFilter(item, rule, conditions))
                    {
                        yield return(approveInfo);
                    }

                    break;
                }

                if (rule.RuleID != null)
                {
                    if (path.Contains(rule.RuleID.Value))
                    {
                        continue;
                    }

                    foreach (var approveInfo in ProcessLevel(item, assignmentMap, PXSelectReadonly <EPRule> .Search <EPRule.ruleID>(this, rule.RuleID)))
                    {
                        yield return(approveInfo);
                    }
                }

                PXResultset <EPRule> result = PXSelectReadonly <
                    EPRule,
                    Where <
                        EPRule.assignmentMapID, Equal <Required <EPAssignmentMap.assignmentMapID> > >,
                    OrderBy <
                        Asc <EPRule.sequence> > > .Select(this, assignmentMap);

                foreach (var approveInfo in ProcessLevel(item, assignmentMap, result))
                {
                    yield return(approveInfo);
                }
            }
        }
        public void Changing_SceneCallbackVersionHash_ChangesHashesOf_SceneWriteOperations()
        {
            Hash128[] preHash = new Hash128[5];
            for (int i = 0; i < WriteOperations.Length; i++)
            {
                preHash[i] = WriteOperations[i].GetHash128();
            }

            BuildInterfacesWrapper.SceneCallbackVersionHash = HashingMethods.Calculate(GUID.Generate()).ToHash128();

            Hash128[] postHash = new Hash128[5];
            for (int i = 0; i < WriteOperations.Length; i++)
            {
                postHash[i] = WriteOperations[i].GetHash128();
            }

            // We expect AssetBundleWriteOperation [0] and RawWriteOperation [1] to not be changed by  the scene callback version hash.
            for (int i = 0; i < 2; i++)
            {
                Assert.AreEqual(preHash[i], postHash[i], "{0} hash changed.", WriteOperations[i].GetType().Name);
            }

            // We expect SceneBundleWriteOperation [2], SceneDataWriteOperation [3], and SceneRawWriteOperation [4] to be changed by the scene callback version hash.
            for (int i = 2; i < WriteOperations.Length; i++)
            {
                Assert.AreNotEqual(preHash[i], postHash[i], "{0} hash unchanged. Not", WriteOperations[i].GetType().Name);
            }
        }
Esempio n. 27
0
 private void ConfirmGUID(GUID expectedGuid, GUID actualGuid)
 {
     Assert.AreEqual(expectedGuid, actualGuid);
 }
Esempio n. 28
0
        public Dictionary <ulong, List <string> >[] Write(Stream output, Map map, Map detail1, Map detail2, Map props, Map lights, string name, IDataWriter modelFormat)
        {
            if (modelFormat == null)
            {
                modelFormat = new OWMDLWriter();
            }
            //Console.Out.WriteLine("Writing OWMAP");
            using (BinaryWriter writer = new BinaryWriter(output)) {
                writer.Write((ushort)1); // version major
                writer.Write((ushort)1); // version minor

                if (name.Length == 0)
                {
                    writer.Write((byte)0);
                }
                else
                {
                    writer.Write(name);
                }

                uint size = 0;
                for (int i = 0; i < map.Records.Length; ++i)
                {
                    if (map.Records[i] != null && map.Records[i].GetType() != typeof(Map01))
                    {
                        continue;
                    }
                    size++;
                }
                writer.Write(size); // nr objects

                size = 1;
                for (int i = 0; i < detail1.Records.Length; ++i)
                {
                    if (detail1.Records[i] != null && detail1.Records[i].GetType() != typeof(Map02))
                    {
                        continue;
                    }
                    size++;
                }
                for (int i = 0; i < detail2.Records.Length; ++i)
                {
                    if (detail2.Records[i] != null && detail2.Records[i].GetType() != typeof(Map08))
                    {
                        continue;
                    }
                    size++;
                }
                for (int i = 0; i < props.Records.Length; ++i)
                {
                    if (props.Records[i] != null && props.Records[i].GetType() != typeof(MapEntity))
                    {
                        continue;
                    }
                    if (((MapEntity)props.Records[i]).Model == 0)
                    {
                        continue;
                    }
                    size++;
                }
                writer.Write(size); // nr details

                // Extension 1.1 - Lights
                size = 0;
                for (int i = 0; i < lights.Records.Length; ++i)
                {
                    if (lights.Records[i] != null && lights.Records[i].GetType() != typeof(Map09))
                    {
                        continue;
                    }
                    size++;
                }
                writer.Write(size); // nr Lights


                Dictionary <ulong, List <string> >[] ret = new Dictionary <ulong, List <string> > [2];
                ret[0] = new Dictionary <ulong, List <string> >();
                ret[1] = new Dictionary <ulong, List <string> >();

                for (int i = 0; i < map.Records.Length; ++i)
                {
                    if (map.Records[i] != null && map.Records[i].GetType() != typeof(Map01))
                    {
                        continue;
                    }
                    Map01  obj     = (Map01)map.Records[i];
                    string modelFn = $"{GUID.Index(obj.Header.Model):X12}{modelFormat.Format}";
                    writer.Write(modelFn);
                    if (!ret[0].ContainsKey(obj.Header.Model))
                    {
                        ret[0].Add(obj.Header.Model, new List <string>());
                    }
                    ret[0][obj.Header.Model].Add(modelFn);
                    writer.Write(obj.Header.groupCount);
                    for (int j = 0; j < obj.Header.groupCount; ++j)
                    {
                        Map01.Map01Group group      = obj.Groups[j];
                        string           materialFn =
                            $"{GUID.Index(obj.Header.Model):X12}_{GUID.Index(group.ModelLook):X12}.owmat";
                        writer.Write(materialFn);
                        if (!ret[1].ContainsKey(group.ModelLook))
                        {
                            ret[1].Add(group.ModelLook, new List <string>());
                        }
                        ret[1][group.ModelLook].Add(materialFn);
                        writer.Write(group.recordCount);
                        for (int k = 0; k < group.recordCount; ++k)
                        {
                            Map01.Map01GroupRecord record = obj.Records[j][k];
                            writer.Write(record.position.x);
                            writer.Write(record.position.y);
                            writer.Write(record.position.z);
                            writer.Write(record.scale.x);
                            writer.Write(record.scale.y);
                            writer.Write(record.scale.z);
                            writer.Write(record.rotation.x);
                            writer.Write(record.rotation.y);
                            writer.Write(record.rotation.z);
                            writer.Write(record.rotation.w);
                        }
                    }
                }

                writer.Write($"physics.{modelFormat.Format}");
                writer.Write((byte)0);
                writer.Write(0.0f);
                writer.Write(0.0f);
                writer.Write(0.0f);
                writer.Write(1.0f);
                writer.Write(1.0f);
                writer.Write(1.0f);
                writer.Write(0.0f);
                writer.Write(0.0f);
                writer.Write(0.0f);
                writer.Write(1.0f);

                for (int i = 0; i < detail1.Records.Length; ++i)
                {
                    if (detail1.Records[i] != null && detail1.Records[i].GetType() != typeof(Map02))
                    {
                        continue;
                    }
                    Map02  obj     = (Map02)detail1.Records[i];
                    string modelFn = $"{GUID.LongKey(obj.Header.Model):X12}{modelFormat.Format}";
                    string matFn   = $"{GUID.LongKey(obj.Header.Model):X12}.owmat";
                    writer.Write(modelFn);
                    writer.Write(matFn);
                    writer.Write(obj.Header.position.x);
                    writer.Write(obj.Header.position.y);
                    writer.Write(obj.Header.position.z);
                    writer.Write(obj.Header.scale.x);
                    writer.Write(obj.Header.scale.y);
                    writer.Write(obj.Header.scale.z);
                    writer.Write(obj.Header.rotation.x);
                    writer.Write(obj.Header.rotation.y);
                    writer.Write(obj.Header.rotation.z);
                    writer.Write(obj.Header.rotation.w);

                    if (!ret[0].ContainsKey(obj.Header.Model))
                    {
                        ret[0].Add(obj.Header.Model, new List <string>());
                    }
                    ret[0][obj.Header.Model].Add(modelFn);


                    if (!ret[1].ContainsKey(obj.Header.ModelLook))
                    {
                        ret[1].Add(obj.Header.ModelLook, new List <string>());
                    }
                    ret[1][obj.Header.ModelLook].Add(matFn);
                }

                for (int i = 0; i < detail2.Records.Length; ++i)
                {
                    if (detail2.Records[i] != null && detail2.Records[i].GetType() != typeof(Map08))
                    {
                        continue;
                    }
                    Map08  obj     = (Map08)detail2.Records[i];
                    string modelFn = $"{GUID.LongKey(obj.Header.Model):X12}{modelFormat.Format}";
                    string matFn   = $"{GUID.LongKey(obj.Header.Model):X12}.owmat";
                    writer.Write(modelFn);
                    writer.Write(matFn);
                    writer.Write(obj.Header.position.x);
                    writer.Write(obj.Header.position.y);
                    writer.Write(obj.Header.position.z);
                    writer.Write(obj.Header.scale.x);
                    writer.Write(obj.Header.scale.y);
                    writer.Write(obj.Header.scale.z);
                    writer.Write(obj.Header.rotation.x);
                    writer.Write(obj.Header.rotation.y);
                    writer.Write(obj.Header.rotation.z);
                    writer.Write(obj.Header.rotation.w);

                    if (!ret[0].ContainsKey(obj.Header.Model))
                    {
                        ret[0].Add(obj.Header.Model, new List <string>());
                    }
                    ret[0][obj.Header.Model].Add(modelFn);


                    if (!ret[1].ContainsKey(obj.Header.ModelLook))
                    {
                        ret[1].Add(obj.Header.ModelLook, new List <string>());
                    }
                    ret[1][obj.Header.ModelLook].Add(matFn);
                }

                for (int i = 0; i < props.Records.Length; ++i)
                {
                    if (props.Records[i] != null && props.Records[i].GetType() != typeof(MapEntity))
                    {
                        continue;
                    }
                    MapEntity obj = (MapEntity)props.Records[i];
                    if (obj.Model == 0)
                    {
                        continue;
                    }
                    string modelFn = $"{GUID.LongKey(obj.Model):X12}{modelFormat.Format}";
                    string matFn   = $"{GUID.LongKey(obj.ModelLook):X12}.owmat";
                    writer.Write(modelFn);
                    writer.Write(matFn);
                    writer.Write(obj.Header.Position.x);
                    writer.Write(obj.Header.Position.y);
                    writer.Write(obj.Header.Position.z);
                    writer.Write(obj.Header.Scale.x);
                    writer.Write(obj.Header.Scale.y);
                    writer.Write(obj.Header.Scale.z);
                    writer.Write(obj.Header.Rotation.x);
                    writer.Write(obj.Header.Rotation.y);
                    writer.Write(obj.Header.Rotation.z);
                    writer.Write(obj.Header.Rotation.w);

                    if (!ret[0].ContainsKey(obj.Model))
                    {
                        ret[0].Add(obj.Model, new List <string>());
                    }
                    ret[0][obj.Model].Add(modelFn);


                    if (!ret[1].ContainsKey(obj.ModelLook))
                    {
                        ret[1].Add(obj.ModelLook, new List <string>());
                    }
                    ret[1][obj.ModelLook].Add(matFn);
                }

                // Extension 1.1 - Lights
                for (int i = 0; i < lights.Records.Length; ++i)
                {
                    if (lights.Records[i] != null && lights.Records[i].GetType() != typeof(Map09))
                    {
                        continue;
                    }
                    Map09 obj = (Map09)lights.Records[i];
                    writer.Write(obj.Header.position.x);
                    writer.Write(obj.Header.position.y);
                    writer.Write(obj.Header.position.z);
                    writer.Write(obj.Header.rotation.x);
                    writer.Write(obj.Header.rotation.y);
                    writer.Write(obj.Header.rotation.z);
                    writer.Write(obj.Header.rotation.w);
                    writer.Write(obj.Header.LightType);
                    writer.Write(obj.Header.LightFOV);
                    writer.Write(obj.Header.Color.x);
                    writer.Write(obj.Header.Color.y);
                    writer.Write(obj.Header.Color.z);
                    writer.Write(obj.Header.unknown1A);
                    writer.Write(obj.Header.unknown1B);
                    writer.Write(obj.Header.unknown2A);
                    writer.Write(obj.Header.unknown2B);
                    writer.Write(obj.Header.unknown2C);
                    writer.Write(obj.Header.unknown2D);
                    writer.Write(obj.Header.unknown3A);
                    writer.Write(obj.Header.unknown3B);

                    writer.Write(obj.Header.unknownPos1.x);
                    writer.Write(obj.Header.unknownPos1.y);
                    writer.Write(obj.Header.unknownPos1.z);
                    writer.Write(obj.Header.unknownQuat1.x);
                    writer.Write(obj.Header.unknownQuat1.y);
                    writer.Write(obj.Header.unknownQuat1.z);
                    writer.Write(obj.Header.unknownQuat1.w);
                    writer.Write(obj.Header.unknownPos2.x);
                    writer.Write(obj.Header.unknownPos2.y);
                    writer.Write(obj.Header.unknownPos2.z);
                    writer.Write(obj.Header.unknownQuat2.x);
                    writer.Write(obj.Header.unknownQuat2.y);
                    writer.Write(obj.Header.unknownQuat2.z);
                    writer.Write(obj.Header.unknownQuat2.w);
                    writer.Write(obj.Header.unknownPos3.x);
                    writer.Write(obj.Header.unknownPos3.y);
                    writer.Write(obj.Header.unknownPos3.z);
                    writer.Write(obj.Header.unknownQuat3.x);
                    writer.Write(obj.Header.unknownQuat3.y);
                    writer.Write(obj.Header.unknownQuat3.z);
                    writer.Write(obj.Header.unknownQuat3.w);

                    writer.Write(obj.Header.unknown4A);
                    writer.Write(obj.Header.unknown4B);
                    writer.Write(obj.Header.unknown5);
                    writer.Write(obj.Header.unknown6A);
                    writer.Write(obj.Header.unknown6B);
                    writer.Write(obj.Header.unknown7A);
                    writer.Write(obj.Header.unknown7B);
                }

                return(ret);
            }
        }
Esempio n. 29
0
        public static bool BuildAssetBundle(string manifestPath, GUID assetGuid, string cacheFilePath, BuildTarget target, bool collectDependencies = false, HashSet <Entities.Hash128> dependencies = null, HashSet <System.Type> types = null, long fileIdent = -1)
        {
            using (new BuildInterfacesWrapper())
            {
                Directory.CreateDirectory(k_TempBuildPath);

                // Used for naming
                string asset;
                if (fileIdent != -1)
                {
                    GUID convGuid = assetGuid;
                    PackBuiltinExtraWithFileIdent(ref convGuid, fileIdent);
                    asset = convGuid.ToString();
                }
                else
                {
                    asset = assetGuid.ToString();
                }

                // Deterministic ID Generator
                var generator = new Unity5PackedIdentifiers();

                // Target platform settings & script information
                var settings = new BuildSettings
                {
                    buildFlags = ContentBuildFlags.None,
                    target     = target,
                    group      = BuildPipeline.GetBuildTargetGroup(target),
                    typeDB     = null
                };

                if (assetGuid == k_UnityBuiltinResources)
                {
                    FilterBuiltinResourcesObjectManifest(manifestPath);
                }

                if (assetGuid == k_UnityBuiltinExtraResources)
                {
                    FilterBuiltinExtraResourcesObjectManifest(manifestPath);
                }

#if UNITY_2020_1_OR_NEWER
                // Collect all the objects we need for this asset & bundle (returned array order is deterministic)
                var manifestObjects = ContentBuildInterface.GetPlayerObjectIdentifiersInSerializedFile(manifestPath, settings.target);
#else
                var method = typeof(ContentBuildInterface).GetMethod("GetPlayerObjectIdentifiersInSerializedFile", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
                // Collect all the objects we need for this asset & bundle (returned array order is deterministic)
                var manifestObjects = (ObjectIdentifier[])method.Invoke(null, new object[] { manifestPath, settings.target });
#endif

                // Collect all the objects we need to reference for this asset (returned array order is deterministic)
                var manifestDependencies = ContentBuildInterface.GetPlayerDependenciesForObjects(manifestObjects, settings.target, settings.typeDB);

                // Scene / Project lighting information
                var globalUsage = ContentBuildInterface.GetGlobalUsageFromGraphicsSettings();
                globalUsage = ForceKeepInstancingVariants(globalUsage);

                // Inter-asset feature usage (shader features, used mesh channels)
                var usageSet = new BuildUsageTagSet();
                ContentBuildInterface.CalculateBuildUsageTags(manifestDependencies, manifestDependencies, globalUsage, usageSet); // TODO: Cache & Append to the assets that are influenced by this usageTagSet, ideally it would be a nice api to extract just the data for a given asset or object from the result

                // Bundle all the needed write parameters
                var writeParams = new WriteParameters
                {
                    // Target platform settings & script information
                    settings = settings,

                    // Scene / Project lighting information
                    globalUsage = globalUsage,

                    // Inter-asset feature usage (shader features, used mesh channels)
                    usageSet = usageSet,

                    // Serialized File Layout
                    writeCommand = new WriteCommand
                    {
                        fileName         = generator.GenerateInternalFileName(asset),
                        internalName     = generator.GenerateAssetBundleInternalFileName(asset),
                        serializeObjects = new List <SerializationInfo>() // Populated Below
                    },

                    // External object references
                    referenceMap = new BuildReferenceMap(), // Populated Below

                    // Asset Bundle object layout
                    bundleInfo = new AssetBundleInfo
                    {
                        bundleName = asset,
                        // What is loadable from this bundle
                        bundleAssets = new List <AssetLoadInfo>
                        {
                            // The manifest object and it's dependencies
                            new AssetLoadInfo
                            {
                                address           = asset,
                                asset             = assetGuid,                // TODO: Remove this as it is unused in C++
                                includedObjects   = manifestObjects.ToList(), // TODO: In our effort to modernize the public API design we over complicated it trying to take List or return ReadOnlyLists. Should have just stuck with Arrays[] in all places
                                referencedObjects = manifestDependencies.ToList()
                            }
                        }
                    }
                };

                // For Builtin Resources, we just want to reference them directly instead of pull them in.
                //if (assetGuid == k_UnityBuiltinResources)
                //    assetGuid = manifestGuid;

                // The requirement is that a single asset bundle only contains the ObjectManifest and the objects that are directly part of the asset, objects for external assets will be in their own bundles. IE: 1 asset per bundle layout
                // So this means we need to take manifestObjects & manifestDependencies and filter storing them into writeCommand.serializeObjects and/or referenceMap based on if they are this asset or other assets
                foreach (var obj in manifestObjects)
                {
                    writeParams.writeCommand.serializeObjects.Add(new SerializationInfo {
                        serializationObject = obj, serializationIndex = generator.SerializationIndexFromObjectIdentifier(obj)
                    });
                    writeParams.referenceMap.AddMapping(writeParams.writeCommand.internalName, generator.SerializationIndexFromObjectIdentifier(obj), obj);
                }

                foreach (var obj in manifestDependencies)
                {
                    // MonoScripts need to live beside the MonoBehavior (in this case ScriptableObject) and loaded first. We could move it to it's own bundle, but this is safer and it's a lightweight object
                    var type = ContentBuildInterface.GetTypeForObject(obj);
                    if (obj.guid == k_UnityBuiltinResources)
                    {
                        // For Builtin Resources, we can reference them directly
                        // TODO: Once we switch to using GlobalObjectId for SBP, we will need a mapping for certain special cases of GUID <> FilePath for Builtin Resources
                        writeParams.referenceMap.AddMapping(obj.filePath, obj.localIdentifierInFile, obj);
                    }
                    else if (type == typeof(MonoScript))
                    {
                        writeParams.writeCommand.serializeObjects.Add(new SerializationInfo {
                            serializationObject = obj, serializationIndex = generator.SerializationIndexFromObjectIdentifier(obj)
                        });
                        writeParams.referenceMap.AddMapping(writeParams.writeCommand.internalName, generator.SerializationIndexFromObjectIdentifier(obj), obj);
                    }
                    else if (collectDependencies || obj.guid == assetGuid)
                    {
                        // If we are a specific built-in asset, only add the built-in asset
                        if (fileIdent != -1 && obj.localIdentifierInFile != fileIdent)
                        {
                            continue;
                        }

                        writeParams.writeCommand.serializeObjects.Add(new SerializationInfo {
                            serializationObject = obj, serializationIndex = generator.SerializationIndexFromObjectIdentifier(obj)
                        });
                        writeParams.referenceMap.AddMapping(writeParams.writeCommand.internalName, generator.SerializationIndexFromObjectIdentifier(obj), obj);
                    }
                    else if (obj.guid == k_UnityBuiltinExtraResources)
                    {
                        GUID convGUID = obj.guid;
                        PackBuiltinExtraWithFileIdent(ref convGUID, obj.localIdentifierInFile);

                        writeParams.referenceMap.AddMapping(generator.GenerateAssetBundleInternalFileName(convGUID.ToString()), generator.SerializationIndexFromObjectIdentifier(obj), obj);

                        dependencies?.Add(convGUID);
                    }
                    else if (!obj.guid.Empty())
                    {
                        writeParams.referenceMap.AddMapping(generator.GenerateAssetBundleInternalFileName(obj.guid.ToString()), generator.SerializationIndexFromObjectIdentifier(obj), obj);
                    }

                    // This will be solvable after we move SBP into the asset pipeline as importers.
                    if (!obj.guid.Empty() && obj.guid != assetGuid && type != typeof(MonoScript) && obj.guid != k_UnityBuiltinExtraResources)
                    {
                        dependencies?.Add(obj.guid);
                    }

                    if (type != null)
                    {
                        types?.Add(type);
                    }
                }

                // Write the serialized file
                var result = ContentBuildInterface.WriteSerializedFile(k_TempBuildPath, writeParams);
                // Archive and compress the serialized & resource files for the previous operation
                var crc = ContentBuildInterface.ArchiveAndCompress(result.resourceFiles.ToArray(), cacheFilePath, UnityEngine.BuildCompression.Uncompressed);

                // Because the shader compiler progress bar hooks are absolute shit
                EditorUtility.ClearProgressBar();

                //Debug.Log($"Wrote '{writeParams.writeCommand.fileName}' to '{k_TempBuildPath}/{writeParams.writeCommand.internalName}' resulting in {result.serializedObjects.Count} objects in the serialized file.");
                //Debug.Log($"Archived '{k_TempBuildPath}/{writeParams.writeCommand.internalName}' to '{cacheFilePath}' resulting in {crc} CRC.");

                Directory.Delete(k_TempBuildPath, true);

                return(crc != 0);
            }
        }
Esempio n. 30
0
 /// <summary>
 /// Instancia este objeto, inicia as variáveis e carrega o registro pelo GUID informado
 /// </summary>
 /// <param name="guid">Identificador único do registro</param>
 public Configuracao(GUID guid)
     : this()
 {
     Populate(guid);
 }
Esempio n. 31
0
        public void Parse(Dictionary <ushort, List <ulong> > track, Dictionary <ulong, Record> map, CASCHandler handler, bool quiet, OverToolFlags flags)
        {
            string output = flags.Positionals[2];

            foreach (ulong key in track[0x54])
            {
                if (!map.ContainsKey(key))
                {
                    continue;
                }
                Dictionary <OWRecord, string> items = new Dictionary <OWRecord, string>();
                using (Stream input = Util.OpenFile(map[key], handler)) {
                    if (input == null)
                    {
                        continue;
                    }
                    STUD stud = new STUD(input);
                    if (stud.Instances == null || stud.Instances[0] == null)
                    {
                        continue;
                    }

                    GlobalInventoryMaster master = stud.Instances[0] as GlobalInventoryMaster;
                    if (master == null)
                    {
                        continue;
                    }

                    foreach (OWRecord record in master.StandardItems)
                    {
                        items[record] = "ACHIEVEMENT";
                    }

                    for (int i = 0; i < master.Generic.Length; ++i)
                    {
                        string name = $"STANDARD_{ItemEvents.GetInstance().GetEvent(master.Generic[i].@event)}";
                        for (int j = 0; j < master.GenericItems[i].Length; ++j)
                        {
                            items[master.GenericItems[i][j]] = name;
                        }
                    }

                    for (int i = 0; i < master.Categories.Length; ++i)
                    {
                        string name = ItemEvents.GetInstance().GetEvent(master.Categories[i].@event);
                        for (int j = 0; j < master.CategoryItems[i].Length; ++j)
                        {
                            items[master.CategoryItems[i][j]] = name;
                        }
                    }

                    for (int i = 0; i < master.ExclusiveOffsets.Length; ++i)
                    {
                        string name = $"LOOTBOX_EXCLUSIVE_{i:X}";
                        for (int j = 0; j < master.LootboxExclusive[i].Length; ++j)
                        {
                            items[master.LootboxExclusive[i][j].item] = name;
                        }
                    }
                }

                foreach (KeyValuePair <OWRecord, string> recordname in items)
                {
                    OWRecord record    = recordname.Key;
                    string   itemGroup = recordname.Value;
                    if (!map.ContainsKey(record.key))
                    {
                        continue;
                    }

                    STUD stud = new STUD(Util.OpenFile(map[record.key], handler));
                    if (stud.Instances == null)
                    {
                        continue;
                    }
                    IInventorySTUDInstance instance = (IInventorySTUDInstance)stud.Instances[0];
                    string name = Util.GetString(instance.Header.name.key, map, handler);
                    if (name == null)
                    {
                        name = $"{GUID.LongKey(key):X12}";
                    }

                    switch (instance.Name)
                    {
                    case "Spray":
                        Console.Out.WriteLine("Extracting spray {0}...", name);
                        ExtractLogic.Spray.Extract(stud, output, "Generic", name, itemGroup, track, map, handler, quiet, flags);
                        break;

                    case "Icon":
                        Console.Out.WriteLine("Extracting icon {0}...", name);
                        ExtractLogic.Icon.Extract(stud, output, "Generic", name, itemGroup, track, map, handler, quiet, flags);
                        break;

                    case "Portrait":
                        PortraitItem portrait = instance as PortraitItem;
                        ExtractLogic.Portrait.Extract(stud, output, "Generic", $"Tier {portrait.Data.tier}", itemGroup, track, map, handler, quiet, flags);
                        break;

                    default:
                        continue;
                    }
                }
            }
        }
Esempio n. 32
0
        static void Main(string[] args)
        {
            if (args.Length < 3)
            {
                Console.Out.WriteLine("Usage: PackageTool.exe [-LLang] \"overwatch_folder\" \"output_folder\" <keys...>");
                Console.Out.WriteLine("Keys must start with 'i' for content keys, 'p' for package keys, 'n' for package indexes, 't' for package indexes + indices");
                Console.Out.WriteLine("Keys must start with 'a' for specific APMs");
                Console.Out.WriteLine("If any key starts with Q it will dump all files.");
                Console.Out.WriteLine("If any key starts with D it will only output filenames to console, but not write files");
                return;
            }

            string root = args[0];

            OwRootHandler.LOAD_PACKAGES = true;
            CASCConfig config = null;

            // ngdp:us:pro
            // http:us:pro:us.patch.battle.net:1119
            if (root.ToLowerInvariant().Substring(0, 5) == "ngdp:")
            {
                string   cdn     = root.Substring(5, 4);
                string[] parts   = root.Substring(5).Split(':');
                string   region  = "us";
                string   product = "pro";
                if (parts.Length > 1)
                {
                    region = parts[1];
                }
                if (parts.Length > 2)
                {
                    product = parts[2];
                }
                if (cdn == "bnet")
                {
                    config = CASCConfig.LoadOnlineStorageConfig(product, region);
                }
                else
                {
                    if (cdn == "http")
                    {
                        string host = string.Join(":", parts.Skip(3));
                        config = CASCConfig.LoadOnlineStorageConfig(host, product, region, true, true, true);
                    }
                }
            }
            else
            {
                config = CASCConfig.LoadLocalStorageConfig(root, true, true);
            }
            if (args[0][0] == '-' && args[0][1] == 'L')
            {
                string lang = args[0].Substring(2);
                config.Languages = new HashSet <string>(new string[1] {
                    lang
                });
                args = args.Skip(1).ToArray();
            }

            string output = args[1] + Path.DirectorySeparatorChar;

            Console.Out.WriteLine("{0} v{1}", Assembly.GetExecutingAssembly().GetName().Name, OWLib.Util.GetVersion());

            HashSet <ulong>  packageKeys    = new HashSet <ulong>();
            HashSet <ulong>  packageIndices = new HashSet <ulong>();
            HashSet <ulong>  packageIndent  = new HashSet <ulong>();
            HashSet <string> contentKeys    = new HashSet <string>();
            HashSet <ulong>  dumped         = new HashSet <ulong>();
            HashSet <ulong>  fileKeys       = new HashSet <ulong>();
            HashSet <ulong>  types          = new HashSet <ulong>();
            string           apmName        = null;
            bool             dumpAll        = false;
            bool             dry            = false;

            for (int i = 2; i < args.Length; ++i)
            {
                string arg = args[i];
                switch (arg[0])
                {
                case 'q':
                case 'Q':
                    dumpAll = true;
                    break;

                case 'd':
                case 'D':
                    dry = true;
                    break;

                case 'p':
                    packageKeys.Add(ulong.Parse(arg.Substring(1), NumberStyles.HexNumber));
                    break;

                case 'P':
                    packageKeys.Add(ulong.Parse(arg.Substring(1), NumberStyles.Number));
                    break;

                case 'n':
                    packageIndices.Add(ulong.Parse(arg.Substring(1), NumberStyles.HexNumber));
                    break;

                case 'N':
                    packageIndices.Add(ulong.Parse(arg.Substring(1), NumberStyles.Number));
                    break;

                case 't':
                    packageIndent.Add(ulong.Parse(arg.Substring(1), NumberStyles.HexNumber));
                    break;

                case 'T':
                    packageIndent.Add(ulong.Parse(arg.Substring(1), NumberStyles.Number));
                    break;

                case 'a':
                case 'A':
                    apmName = arg.Substring(1).ToLowerInvariant();
                    break;

                case 'i':
                case 'I':
                    contentKeys.Add(arg.Substring(1).ToUpperInvariant());
                    break;

                case 'f':
                    fileKeys.Add(ulong.Parse(arg.Substring(1), NumberStyles.HexNumber));
                    break;

                case 'F':
                    fileKeys.Add(ulong.Parse(arg.Substring(1), NumberStyles.Number));
                    break;

                case 'M':
                    types.Add(ulong.Parse(arg.Substring(1), NumberStyles.HexNumber));
                    break;
                }
            }

            if (contentKeys.Count + packageKeys.Count + packageIndices.Count + packageIndent.Count + fileKeys.Count + types.Count == 0 && !dumpAll)
            {
                Console.Error.WriteLine("Must have at least 1 query");
                return;
            }

            CASCHandler   handler = CASCHandler.OpenStorage(config);
            OwRootHandler ow      = handler.Root as OwRootHandler;

            if (ow == null)
            {
                Console.Error.WriteLine("Not a valid Overwatch installation");
                return;
            }

            Console.Out.WriteLine("Extracting...");

            HashSet <ulong> indicesExtracted = new HashSet <ulong>();
            HashSet <ulong> CMFExtracted     = new HashSet <ulong>();

            foreach (APMFile apm in ow.APMFiles)
            {
                if (apmName != null && !Path.GetFileName(apm.Name).ToLowerInvariant().Contains(apmName))
                {
                    continue;
                }
                Console.Out.WriteLine("Iterating {0}", Path.GetFileName(apm.Name));
                HashSet <ulong> removed = new HashSet <ulong>();
                foreach (ulong key in fileKeys)
                {
                    if (apm.CMFMap.ContainsKey(key))
                    {
                        ulong  rtype  = GUID.Type(key);
                        ulong  rindex = GUID.LongKey(key);
                        string ofn    = $"{output}{Path.DirectorySeparatorChar}cmf{Path.DirectorySeparatorChar}{rtype:X3}{Path.DirectorySeparatorChar}";
                        if (!dry && !Directory.Exists(ofn))
                        {
                            Console.Out.WriteLine("Created directory {0}", ofn);
                            Directory.CreateDirectory(ofn);
                        }
                        ofn = $"{ofn}{rindex:X12}.{rtype:X3}";
                        if (!dry)
                        {
                            using (Stream outputStream = File.Open(ofn, FileMode.Create, FileAccess.Write)) {
                                EncodingEntry recordEncoding;
                                if (!handler.Encoding.GetEntry(apm.CMFMap[key].HashKey, out recordEncoding))
                                {
                                    Console.Error.WriteLine("Cannot open file {0} -- malformed CMF?", ofn);
                                    continue;
                                }

                                try {
                                    using (Stream recordStream = handler.OpenFile(recordEncoding.Key)) {
                                        CopyBytes(recordStream, outputStream, recordEncoding.Size);
                                    }
                                    Console.Out.WriteLine("Saved file {0}", ofn);
                                    removed.Add(key);
                                } catch {
                                    Console.Error.WriteLine("Cannot open file {0} -- encryption", ofn);
                                }
                            }
                        }
                    }
                }
                foreach (ulong key in removed)
                {
                    fileKeys.Remove(key);
                }
                if (types.Count > 0 || dumpAll)
                {
                    foreach (ulong key in apm.CMFMap.Keys)
                    {
                        if (types.Contains(GUID.Type(key)) || dumpAll)
                        {
                            ulong  rtype  = GUID.Type(key);
                            ulong  rindex = GUID.LongKey(key);
                            string ofn    = $"{output}{Path.DirectorySeparatorChar}cmf{Path.DirectorySeparatorChar}{rtype:X3}{Path.DirectorySeparatorChar}";
                            if (!dry && !Directory.Exists(ofn))
                            {
                                Console.Out.WriteLine("Created directory {0}", ofn);
                                Directory.CreateDirectory(ofn);
                            }
                            ofn = $"{ofn}{rindex:X12}.{rtype:X3}";
                            if (!dry)
                            {
                                using (Stream outputStream = File.Open(ofn, FileMode.Create, FileAccess.Write)) {
                                    EncodingEntry recordEncoding;
                                    if (!handler.Encoding.GetEntry(apm.CMFMap[key].HashKey, out recordEncoding))
                                    {
                                        Console.Error.WriteLine("Cannot open file {0} -- malformed CMF?", ofn);
                                        continue;
                                    }

                                    try {
                                        using (Stream recordStream = handler.OpenFile(recordEncoding.Key)) {
                                            CopyBytes(recordStream, outputStream, recordEncoding.Size);
                                        }
                                        Console.Out.WriteLine("Saved file {0}", ofn);
                                    } catch {
                                        Console.Error.WriteLine("Cannot open file {0} -- encryption", ofn);
                                    }
                                }
                            }
                        }
                    }
                }
                if (dumpAll)
                {
                    continue;
                }
                if (contentKeys.Count + packageKeys.Count + packageIndices.Count + packageIndent.Count + fileKeys.Count > 0)
                {
                    for (long i = 0; i < apm.Packages.LongLength; ++i)
                    {
                        if (contentKeys.Count + packageKeys.Count + packageIndices.Count + packageIndent.Count + fileKeys.Count == 0)
                        {
                            break;
                        }

                        APMPackage package = apm.Packages[i];

                        if (!dumpAll)
                        {
                            bool ret = true;
                            if (packageKeys.Count > 0 && packageKeys.Contains(package.packageKey))
                            {
                                ret = false;
                            }

                            if (ret && contentKeys.Count > 0 && contentKeys.Contains(package.indexContentKey.ToHexString().ToUpperInvariant()))
                            {
                                ret = false;
                            }

                            if (ret && packageIndices.Count > 0 && packageIndices.Contains(GUID.Index(package.packageKey)) && !indicesExtracted.Contains(package.packageKey))
                            {
                                ret = false;
                            }

                            if (ret && packageIndent.Count > 0 && packageIndent.Contains(GUID.LongKey(package.packageKey)))
                            {
                                ret = false;
                            }

                            if (ret)
                            {
                                continue;
                            }
                        }

                        packageKeys.Remove(package.packageKey);
                        indicesExtracted.Add(package.packageKey);
                        packageIndent.Remove(GUID.LongKey(package.packageKey));
                        contentKeys.Remove(package.indexContentKey.ToHexString().ToUpperInvariant());

                        PackageIndex         index   = apm.Indexes[i];
                        PackageIndexRecord[] records = apm.Records[i];

                        string o = null;
                        if (dumpAll)
                        {
                            o = output;
                        }
                        else
                        {
                            o = $"{output}{GUID.LongKey(package.packageKey):X12}{Path.DirectorySeparatorChar}";
                        }

                        EncodingEntry bundleEncoding;
                        bool          allowBundle = handler.Encoding.GetEntry(index.bundleContentKey, out bundleEncoding);

                        Stream bundleStream = null;
                        if (allowBundle)
                        {
                            try {
                                bundleStream = handler.OpenFile(bundleEncoding.Key);
                            } catch {
                                Console.Error.WriteLine("Cannot open bundle {0:X16} -- encryption", index.bundleKey);
                                continue;
                            }
                        }
                        foreach (PackageIndexRecord record in records)
                        {
                            if (dumpAll && !dumped.Add(record.Key))
                            {
                                continue;
                            }
                            ulong  rtype  = GUID.Type(record.Key);
                            ulong  rindex = GUID.LongKey(record.Key);
                            string ofn    = $"{o}{rtype:X3}{Path.DirectorySeparatorChar}";
                            if (!dry && !Directory.Exists(ofn))
                            {
                                Console.Out.WriteLine("Created directory {0}", ofn);
                                Directory.CreateDirectory(ofn);
                            }
                            ofn = $"{ofn}{rindex:X12}.{rtype:X3}";
                            if (!dry)
                            {
                                using (Stream outputStream = File.Open(ofn, FileMode.Create, FileAccess.Write)) {
                                    if (((ContentFlags)record.Flags & ContentFlags.Bundle) == ContentFlags.Bundle)
                                    {
                                        if (allowBundle)
                                        {
                                            bundleStream.Position = record.Offset;
                                            CopyBytes(bundleStream, outputStream, record.Size);
                                        }
                                        else
                                        {
                                            Console.Error.WriteLine("Cannot open file {0} -- can't open bundle", ofn);
                                            continue;
                                        }
                                    }
                                    else
                                    {
                                        EncodingEntry recordEncoding;
                                        if (!handler.Encoding.GetEntry(record.ContentKey, out recordEncoding))
                                        {
                                            Console.Error.WriteLine("Cannot open file {0} -- doesn't have bundle flags", ofn);
                                            continue;
                                        }

                                        try {
                                            using (Stream recordStream = handler.OpenFile(recordEncoding.Key)) {
                                                CopyBytes(recordStream, outputStream, record.Size);
                                            }
                                        } catch {
                                            Console.Error.WriteLine("Cannot open file {0} -- encryption", ofn);
                                        }
                                    }
                                }
                            }

                            Console.Out.WriteLine("Saved file {0}", ofn);
                        }

                        if (allowBundle)
                        {
                            bundleStream.Dispose();
                        }
                    }
                }
            }
        }
Esempio n. 33
0
 public float GetTessellationDetail(GUID guid)
 {
     return(((SpriteDataExt)base.dataProvider.GetSpriteData(guid)).tessellationDetail);
 }
Esempio n. 34
0
 public void SetOutlines(GUID guid, List <Vector2[]> data)
 {
     ((SpriteDataExt)base.dataProvider.GetSpriteData(guid)).spriteOutline = data;
 }
Esempio n. 35
0
        public List <Vector2[]> GetOutlines(GUID guid)
        {
            int spriteDataIndex = base.dataProvider.GetSpriteDataIndex(guid);

            return(SpriteOutlineDataTransfer.Load(new SerializedObject(base.dataProvider), base.dataProvider.spriteImportMode, spriteDataIndex));
        }
        /// <inheritdoc />
        public ReturnCode Run()
        {
            IList <CachedInfo> cachedInfo   = null;
            IList <CachedInfo> uncachedInfo = null;

            if (m_Parameters.UseCache && m_Cache != null)
            {
                IList <CacheEntry> entries = m_Content.Scenes.Select(x => m_Cache.GetCacheEntry(x, Version)).ToList();
                m_Cache.LoadCachedData(entries, out cachedInfo);

                uncachedInfo = new List <CachedInfo>();
            }

            for (int i = 0; i < m_Content.Scenes.Count; i++)
            {
                GUID   scene     = m_Content.Scenes[i];
                string scenePath = AssetDatabase.GUIDToAssetPath(scene.ToString());

                SceneDependencyInfo sceneInfo;
                BuildUsageTagSet    usageTags;

                if (cachedInfo != null && cachedInfo[i] != null)
                {
                    if (!m_Tracker.UpdateInfoUnchecked(string.Format("{0} (Cached)", scenePath)))
                    {
                        return(ReturnCode.Canceled);
                    }

                    sceneInfo = (SceneDependencyInfo)cachedInfo[i].Data[0];
                    usageTags = cachedInfo[i].Data[1] as BuildUsageTagSet;
                }
                else
                {
                    if (!m_Tracker.UpdateInfoUnchecked(scenePath))
                    {
                        return(ReturnCode.Canceled);
                    }

                    var      references   = new HashSet <ObjectIdentifier>();
                    string[] dependencies = AssetDatabase.GetDependencies(scenePath);
                    foreach (var assetPath in dependencies)
                    {
                        var assetGuid = new GUID(AssetDatabase.AssetPathToGUID(assetPath));
                        if (ValidationMethods.ValidAsset(assetGuid) != ValidationMethods.Status.Asset)
                        {
                            continue;
                        }

                        // TODO: Use Cache to speed this up?
                        var assetIncludes   = ContentBuildInterface.GetPlayerObjectIdentifiersInAsset(assetGuid, m_Parameters.Target);
                        var assetReferences = ContentBuildInterface.GetPlayerDependenciesForObjects(assetIncludes, m_Parameters.Target, m_Parameters.ScriptInfo);
                        references.UnionWith(assetIncludes);
                        references.UnionWith(assetReferences);
                    }

                    sceneInfo = new SceneDependencyInfo();
                    usageTags = new BuildUsageTagSet();

                    var boxedInfo = (object)sceneInfo;
                    typeof(SceneDependencyInfo).GetField("m_Scene", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(boxedInfo, scenePath);
#if !UNITY_2019_3_OR_NEWER
                    typeof(SceneDependencyInfo).GetField("m_ProcessedScene", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(boxedInfo, scenePath);
#endif
                    typeof(SceneDependencyInfo).GetField("m_ReferencedObjects", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(boxedInfo, references.ToArray());
                    sceneInfo = (SceneDependencyInfo)boxedInfo;

                    if (uncachedInfo != null)
                    {
                        uncachedInfo.Add(GetCachedInfo(scene, sceneInfo.referencedObjects, sceneInfo, usageTags));
                    }
                }

                SetOutputInformation(scene, sceneInfo, usageTags);
            }

            if (m_Parameters.UseCache && m_Cache != null)
            {
                m_Cache.SaveCachedData(uncachedInfo);
            }

            return(ReturnCode.Success);
        }
Esempio n. 37
0
 public static Hash128 CalculateTargetHash(GUID guid, BuildTarget target, AssetDatabaseExperimental.ImportSyncMode syncMode)
 {
     return(LiveLinkBuildImporter.GetHash(guid.ToString(), target, syncMode));
 }
Esempio n. 38
0
 /// <summary>
 /// Instancia este objeto, inicia as variáveis e carrega o registro pelo GUID informado
 /// </summary>
 /// <param name="guid">identificador único do registro</param>
 public GrupoBase(GUID guid)
     : this()
 {
     Populate(guid);
 }
Esempio n. 39
0
        public static bool BuildSceneBundle(GUID sceneGuid, string cacheFilePath, BuildTarget target, bool collectDependencies = false, HashSet <Entities.Hash128> dependencies = null, HashSet <System.Type> types = null)
        {
            using (new BuildInterfacesWrapper())
                using (new SceneStateCleanup())
                {
                    Directory.CreateDirectory(k_TempBuildPath);

                    var scene     = sceneGuid.ToString();
                    var scenePath = AssetDatabase.GUIDToAssetPath(scene);

                    // Deterministic ID Generator
                    var generator = new Unity5PackedIdentifiers();

                    // Target platform settings & script information
                    var settings = new BuildSettings
                    {
                        buildFlags = ContentBuildFlags.None,
                        target     = target,
                        group      = BuildPipeline.GetBuildTargetGroup(target),
                        typeDB     = null
                    };

                    // Inter-asset feature usage (shader features, used mesh channels)
                    var usageSet          = new BuildUsageTagSet();
                    var dependencyResults = ContentBuildInterface.CalculatePlayerDependenciesForScene(scenePath, settings, usageSet);

                    // Bundle all the needed write parameters
                    var writeParams = new WriteSceneParameters
                    {
                        // Target platform settings & script information
                        settings = settings,

                        // Scene / Project lighting information
                        globalUsage = dependencyResults.globalUsage,

                        // Inter-asset feature usage (shader features, used mesh channels)
                        usageSet = usageSet,

                        // Scene being written out
                        scenePath = scenePath,

                        // Serialized File Layout
                        writeCommand = new WriteCommand
                        {
                            fileName         = generator.GenerateSceneInternalFileName(scenePath),
                            internalName     = generator.GenerateSceneBundleInternalFileName(scenePath),
                            serializeObjects = new List <SerializationInfo>() // Populated Below
                        },

                        // External object references
                        referenceMap = new BuildReferenceMap(), // Populated Below

                        // External object preload
                        preloadInfo = new PreloadInfo(), // Populated Below

                        sceneBundleInfo = new SceneBundleInfo
                        {
                            bundleName   = scene,
                            bundleScenes = new List <SceneLoadInfo> {
                                new SceneLoadInfo {
                                    asset        = sceneGuid,
                                    address      = scenePath,
                                    internalName = generator.GenerateInternalFileName(scenePath)
                                }
                            }
                        }
                    };

                    // The requirement is that a single asset bundle only contains the ObjectManifest and the objects that are directly part of the asset, objects for external assets will be in their own bundles. IE: 1 asset per bundle layout
                    // So this means we need to take manifestObjects & manifestDependencies and filter storing them into writeCommand.serializeObjects and/or referenceMap based on if they are this asset or other assets
                    foreach (var obj in dependencyResults.referencedObjects)
                    {
                        // MonoScripts need to live beside the MonoBehavior (in this case ScriptableObject) and loaded first. We could move it to it's own bundle, but this is safer and it's a lightweight object
                        var type = ContentBuildInterface.GetTypeForObject(obj);
                        if (obj.guid == k_UnityBuiltinResources)
                        {
                            // For Builtin Resources, we can reference them directly
                            // TODO: Once we switch to using GlobalObjectId for SBP, we will need a mapping for certain special cases of GUID <> FilePath for Builtin Resources
                            writeParams.referenceMap.AddMapping(obj.filePath, obj.localIdentifierInFile, obj);
                        }
                        else if (type == typeof(MonoScript))
                        {
                            writeParams.writeCommand.serializeObjects.Add(new SerializationInfo {
                                serializationObject = obj, serializationIndex = generator.SerializationIndexFromObjectIdentifier(obj)
                            });
                            writeParams.referenceMap.AddMapping(writeParams.writeCommand.internalName, generator.SerializationIndexFromObjectIdentifier(obj), obj);
                        }
                        else if (collectDependencies || obj.guid == sceneGuid)
                        {
                            writeParams.writeCommand.serializeObjects.Add(new SerializationInfo {
                                serializationObject = obj, serializationIndex = generator.SerializationIndexFromObjectIdentifier(obj)
                            });
                            writeParams.referenceMap.AddMapping(writeParams.writeCommand.internalName, generator.SerializationIndexFromObjectIdentifier(obj), obj);
                        }
                        else if (obj.guid == k_UnityBuiltinExtraResources)
                        {
                            GUID convGUID = obj.guid;
                            PackBuiltinExtraWithFileIdent(ref convGUID, obj.localIdentifierInFile);

                            writeParams.referenceMap.AddMapping(generator.GenerateAssetBundleInternalFileName(convGUID.ToString()), generator.SerializationIndexFromObjectIdentifier(obj), obj);

                            dependencies?.Add(convGUID);
                        }
                        else if (!obj.guid.Empty())
                        {
                            writeParams.referenceMap.AddMapping(generator.GenerateAssetBundleInternalFileName(obj.guid.ToString()), generator.SerializationIndexFromObjectIdentifier(obj), obj);
                        }

                        // This will be solvable after we move SBP into the asset pipeline as importers.
                        if (!obj.guid.Empty() && obj.guid != sceneGuid && type != typeof(MonoScript) && obj.guid != k_UnityBuiltinExtraResources)
                        {
                            dependencies?.Add(obj.guid);
                        }

                        if (type != null)
                        {
                            types?.Add(type);
                        }
                    }

                    // Write the serialized file
                    var result = ContentBuildInterface.WriteSceneSerializedFile(k_TempBuildPath, writeParams);
                    // Archive and compress the serialized & resource files for the previous operation
                    var crc = ContentBuildInterface.ArchiveAndCompress(result.resourceFiles.ToArray(), cacheFilePath, UnityEngine.BuildCompression.Uncompressed);

                    // Because the shader compiler progress bar hooks are absolute shit
                    EditorUtility.ClearProgressBar();

                    //Debug.Log($"Wrote '{writeParams.writeCommand.fileName}' to '{k_TempBuildPath}/{writeParams.writeCommand.internalName}' resulting in {result.serializedObjects.Count} objects in the serialized file.");
                    //Debug.Log($"Archived '{k_TempBuildPath}/{writeParams.writeCommand.internalName}' to '{cacheFilePath}' resulting in {crc} CRC.");

                    Directory.Delete(k_TempBuildPath, true);

                    return(crc != 0);
                }
        }
Esempio n. 40
0
 public MetaPtr(long fileID, GUID guid, AssetType assetType)
 {
     FileID    = fileID;
     GUID      = guid;
     AssetType = assetType;
 }
 public string Get(GUID id)
 {
     return(id.ToString());
 }
 /// <summary>
 /// Adds an Entity Scene that will be produced by a ScriptedImporter from any data source.
 /// EntityScenes may only be added from the ClassicBuildPipelineCustomizer.OnBeforeRegisterAdditionalFilesToDeploy callback.
 /// </summary>
 public void Add(GUID sceneGUID, GUID assetGUID, Type importerType)
 {
     SceneGUID.Add(sceneGUID);
     ArtifactKeys.Add(new ArtifactKey(assetGUID, importerType));
 }
        public void Changing_ShaderCallbackVersionHash_ChangesHashesOf_AllWriteOperations()
        {
            Hash128[] preHash = new Hash128[5];
            for (int i = 0; i < WriteOperations.Length; i++)
            {
                preHash[i] = WriteOperations[i].GetHash128();
            }

            BuildInterfacesWrapper.ShaderCallbackVersionHash = HashingMethods.Calculate(GUID.Generate()).ToHash128();

            Hash128[] postHash = new Hash128[5];
            for (int i = 0; i < WriteOperations.Length; i++)
            {
                postHash[i] = WriteOperations[i].GetHash128();
            }

            // We expect all write operation hashes to be changed by the scene callback version hash.
            for (int i = 0; i < WriteOperations.Length; i++)
            {
                Assert.AreNotEqual(preHash[i], postHash[i], "{0} hash unchanged.", WriteOperations[i].GetType().Name);
            }
        }
Esempio n. 44
0
        public static unsafe void BuildManifest(GUID guid, AssetObjectManifest manifest)
        {
            var objects = AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GUIDToAssetPath(guid.ToString()));

            BuildManifest(objects, manifest);
        }
        public ReturnCode Run()
        {
            var globalUsage = m_DependencyData.GlobalUsage;

            foreach (SceneDependencyInfo sceneInfo in m_DependencyData.SceneInfo.Values)
            {
                globalUsage |= sceneInfo.globalUsage;
            }

            if (m_SpriteData == null)
            {
                m_SpriteData = new BuildSpriteData();
            }

            if (m_ExtendedAssetData == null)
            {
                m_ExtendedAssetData = new BuildExtendedAssetData();
            }

            IList <CachedInfo> cachedInfo   = null;
            List <CachedInfo>  uncachedInfo = null;

            if (m_Parameters.UseCache && m_Cache != null)
            {
                IList <CacheEntry> entries = m_Content.Assets.Select(x => m_Cache.GetCacheEntry(x, Version)).ToList();
                m_Cache.LoadCachedData(entries, out cachedInfo);

                uncachedInfo = new List <CachedInfo>();
            }

            for (int i = 0; i < m_Content.Assets.Count; i++)
            {
                GUID   asset     = m_Content.Assets[i];
                string assetPath = AssetDatabase.GUIDToAssetPath(asset.ToString());

                AssetLoadInfo      assetInfo;
                BuildUsageTagSet   usageTags;
                SpriteImporterData importerData;
                ExtendedAssetData  assetData;

                if (cachedInfo != null && cachedInfo[i] != null)
                {
                    if (!m_Tracker.UpdateInfoUnchecked(string.Format("{0} (Cached)", assetPath)))
                    {
                        return(ReturnCode.Canceled);
                    }

                    assetInfo    = cachedInfo[i].Data[0] as AssetLoadInfo;
                    usageTags    = cachedInfo[i].Data[1] as BuildUsageTagSet;
                    importerData = cachedInfo[i].Data[2] as SpriteImporterData;
                    assetData    = cachedInfo[i].Data[3] as ExtendedAssetData;
                }
                else
                {
                    if (!m_Tracker.UpdateInfoUnchecked(assetPath))
                    {
                        return(ReturnCode.Canceled);
                    }

                    assetInfo    = new AssetLoadInfo();
                    usageTags    = new BuildUsageTagSet();
                    importerData = null;
                    assetData    = null;

                    assetInfo.asset = asset;
                    var includedObjects = ContentBuildInterface.GetPlayerObjectIdentifiersInAsset(asset, m_Parameters.Target);
                    assetInfo.includedObjects = new List <ObjectIdentifier>(includedObjects);
                    var referencedObjects = ContentBuildInterface.GetPlayerDependenciesForObjects(includedObjects, m_Parameters.Target, m_Parameters.ScriptInfo);
                    assetInfo.referencedObjects = new List <ObjectIdentifier>(referencedObjects);
                    var allObjects = new List <ObjectIdentifier>(includedObjects);
                    allObjects.AddRange(referencedObjects);
                    ContentBuildInterface.CalculateBuildUsageTags(allObjects.ToArray(), includedObjects, globalUsage, usageTags, m_DependencyData.DependencyUsageCache);

                    var importer = AssetImporter.GetAtPath(assetPath) as TextureImporter;
                    if (importer != null && importer.textureType == TextureImporterType.Sprite)
                    {
#if !UNITY_2020_1_OR_NEWER
                        // Legacy Sprite Packing Modes
                        if (EditorSettings.spritePackerMode == SpritePackerMode.AlwaysOn || EditorSettings.spritePackerMode == SpritePackerMode.BuildTimeOnly)
                        {
                            importerData = new SpriteImporterData();
                            importerData.PackedSprite  = !string.IsNullOrEmpty(importer.spritePackingTag);
                            importerData.SourceTexture = includedObjects.First();
                        }
                        else if (!referencedObjects.IsNullOrEmpty()) // Sprite is referencing packed data
#else
                        if (!referencedObjects.IsNullOrEmpty())      // Sprite is referencing packed data
#endif
                        {
                            importerData = new SpriteImporterData();
                            importerData.PackedSprite  = EditorSettings.spritePackerMode != SpritePackerMode.Disabled;
                            importerData.SourceTexture = includedObjects.First();
                        }
                    }

                    var representations = AssetDatabase.LoadAllAssetRepresentationsAtPath(assetPath);
                    if (!representations.IsNullOrEmpty())
                    {
                        assetData = new ExtendedAssetData();
                        foreach (var representation in representations)
                        {
                            if (AssetDatabase.IsMainAsset(representation))
                            {
                                continue;
                            }

                            string guid;
                            long   localId;
                            if (!AssetDatabase.TryGetGUIDAndLocalFileIdentifier(representation, out guid, out localId))
                            {
                                continue;
                            }

                            assetData.Representations.AddRange(includedObjects.Where(x => x.localIdentifierInFile == localId));
                        }
                    }

                    if (uncachedInfo != null)
                    {
                        uncachedInfo.Add(GetCachedInfo(asset, assetInfo, usageTags, importerData, assetData));
                    }
                }

                SetOutputInformation(asset, assetInfo, usageTags, importerData, assetData);
            }

            if (m_SpriteData.ImporterData.Count == 0)
            {
                m_SpriteData = null;
            }

            if (m_ExtendedAssetData.ExtendedData.Count == 0)
            {
                m_SpriteData = null;
            }

            if (m_Parameters.UseCache && m_Cache != null)
            {
                m_Cache.SaveCachedData(uncachedInfo);
            }

            return(ReturnCode.Success);
        }
Esempio n. 46
0
 private GUID GetNewGUID()
 {
     return(GUID.Generate());
 }
Esempio n. 47
0
 public override int GetHashCode()
 {
     return(GUID.GetHashCode());
 }
Esempio n. 48
0
 /// <summary>
 /// Load an asset from the specified asset <see cref="GUID"/>.
 /// </summary>
 /// <param name="assetGuid">The asset <see cref="GUID"/> to load from.</param>
 /// <returns>The loaded asset if successful, <see langword="null"/> otherwise.</returns>
 public static TContainer LoadAsset(GUID assetGuid) => LoadAsset(AssetDatabase.GUIDToAssetPath(assetGuid.ToString()));
 void SetOutputInformation(GUID asset, SceneDependencyInfo sceneInfo, BuildUsageTagSet usageTags)
 {
     // Add generated scene information to BuildDependencyData
     m_DependencyData.SceneInfo.Add(asset, sceneInfo);
     m_DependencyData.SceneUsage.Add(asset, usageTags);
 }
Esempio n. 50
0
 public void LoadData()
 {
     listViTriHienThi = ViTriHienThi.getAll();
     if (listViTriHienThi.Count > 0)
     {
         ucTreeViTri.CreateTreeList();
         ucTreeViTri.ASPxTreeList_ViTri.DataSource = listViTriHienThi;
         ucTreeViTri.ASPxTreeList_ViTri.DataBind();
         SearchFunction();
         treevitri.Visible = true;
         if (Request.QueryString["key"] != null)
         {
             string key = "";
             try
             {
                 key = Request.QueryString["key"].ToString();
             }
             catch
             {
                 Response.Redirect(Request.Url.AbsolutePath);
             }
             DevExpress.Web.ASPxTreeList.TreeListNode node = ucTreeViTri.ASPxTreeList_ViTri.FindNodeByKeyValue(key);
             if (node != null)
             {
                 node.Focus();
                 ucTreeViTri.FocusAndExpandToNode(node);
                 Guid   id   = GUID.From(node.GetValue("id"));
                 string type = node.GetValue("loai").ToString();
                 if (type.Equals(typeof(CoSo).Name))
                 {
                     objCoSo = CoSo.getById(id);
                     if (objCoSo != null)
                     {
                         info.Visible        = true;
                         Label_ThongTin.Text = "Thông tin " + objCoSo.ten;
                         Label_Ten.Text      = objCoSo.ten;
                         ucViTri_BreadCrumb.Label_TenViTri.Text = Label_Ten.Text = objCoSo.ten;
                         Label_Thuoc.Text = "[Đại học Sài Gòn]";
                         Label_MoTa.Text  = StringHelper.ConvertRNToBR(objCoSo.mota);
                     }
                     else
                     {
                         Response.Redirect(Request.Url.AbsolutePath);
                     }
                 }
                 else if (type.Equals(typeof(Dayy).Name))
                 {
                     objDay = Dayy.getById(id);
                     if (objDay != null)
                     {
                         info.Visible        = true;
                         Label_ThongTin.Text = "Thông tin " + objDay.ten;
                         Label_Ten.Text      = objDay.ten;
                         Label_Thuoc.Text    = objDay.coso != null ? objDay.coso.ten : "[Cơ sở]";
                         ucViTri_BreadCrumb.Label_TenViTri.Text = string.Format("{0} ({1})", Label_Ten.Text, Label_Thuoc.Text);
                         Label_MoTa.Text = StringHelper.ConvertRNToBR(objDay.mota);
                     }
                     else
                     {
                         Response.Redirect(Request.Url.AbsolutePath);
                     }
                 }
                 else if (type.Equals(typeof(Tang).Name))
                 {
                     objTang = Tang.getById(id);
                     if (objTang != null)
                     {
                         info.Visible        = true;
                         Label_ThongTin.Text = "Thông tin " + objTang.ten;
                         Label_Ten.Text      = objTang.ten;
                         if (objTang.day != null)
                         {
                             if (objTang.day.coso != null)
                             {
                                 Label_Thuoc.Text = objTang.day.coso.ten + " - " + objTang.day.ten;
                             }
                             else
                             {
                                 Label_Thuoc.Text = "[Cơ sở] - " + objTang.day.ten;
                             }
                         }
                         else
                         {
                             Label_Thuoc.Text = "[Cơ sở] - [Dãy]";
                         }
                         ucViTri_BreadCrumb.Label_TenViTri.Text = string.Format("{0} ({1})", Label_Ten.Text, Label_Thuoc.Text);
                         Label_MoTa.Text = StringHelper.ConvertRNToBR(objTang.mota);
                     }
                     else
                     {
                         Response.Redirect(Request.Url.AbsolutePath);
                     }
                 }
                 else
                 {
                     Response.Redirect(Request.Url.AbsolutePath);
                 }
             }
             else
             {
                 Response.Redirect(Request.Url.AbsolutePath);
             }
         }
         else
         {
             DevExpress.Web.ASPxTreeList.TreeListNode node = ucTreeViTri.ASPxTreeList_ViTri.FindNodeByKeyValue("");
             node.Focus();
         }
     }
     else
     {
         thongbaoloi.Visible     = true;
         ucDanger.LabelInfo.Text = "Chưa có vị trí";
     }
 }
Esempio n. 51
0
 public void SetTessellationDetail(GUID guid, float value)
 {
     ((SpriteDataExt)base.dataProvider.GetSpriteData(guid)).tessellationDetail = value;
 }
 static extern unsafe int SetupDiEnumDeviceInterfaces(
     int DeviceInfoSet,
     int DeviceInfoData,
     ref  GUID lpHidGuid,
     int MemberIndex,
     ref  SP_DEVICE_INTERFACE_DATA lpDeviceInterfaceData);
 static extern unsafe int SetupDiGetClassDevs(
     ref GUID lpHidGuid,
     int* Enumerator,
     int* hwndParent,
     int Flags);
Esempio n. 54
0
        public void Update(List <LiveLinkChangeSet> changeSets, NativeList <Hash128> loadScenes, NativeList <Hash128> unloadScenes, LiveLinkMode mode)
        {
            // If build settings have changed, we need to trigger a full conversion
            if (_BuildSettingsGUID != default)
            {
                var buildSettingsDependencyHash = AssetDatabase.GetAssetDependencyHash(AssetDatabase.GUIDToAssetPath(_BuildSettingsGUID.ToString()));
                if (_BuildSettingsArtifactHash != buildSettingsDependencyHash)
                {
                    _BuildSettingsArtifactHash = buildSettingsDependencyHash;
                    RequestCleanConversion();
                }
            }

            if (_PreviousGlobalDirtyID != GlobalDirtyID)
            {
                RequestCleanConversion();
                _PreviousGlobalDirtyID = GlobalDirtyID;
            }

            // By default all scenes need to have m_GameObjectSceneCullingMask, otherwise they won't show up in game view
            _GUIDToEditScene.Clear();
            for (int i = 0; i != EditorSceneManager.sceneCount; i++)
            {
                var scene     = EditorSceneManager.GetSceneAt(i);
                var sceneGUID = new GUID(AssetDatabase.AssetPathToGUID(scene.path));

                if (_LoadedScenes.Contains(sceneGUID))
                {
                    if (scene.isLoaded && sceneGUID != default(GUID))
                    {
                        _GUIDToEditScene.Add(sceneGUID, scene);
                    }
                }
            }

            foreach (var scene in _SceneGUIDToLiveLink)
            {
                if (!_GUIDToEditScene.ContainsKey(scene.Key))
                {
                    unloadScenes.Add(scene.Key);
                }
            }

            // Process scenes that are no longer loaded
            foreach (var scene in unloadScenes)
            {
                var liveLink = _SceneGUIDToLiveLink[scene];
                liveLink.Dispose();
                _SceneGUIDToLiveLink.Remove(scene);
                _SentLoadScenes.Remove(scene);
            }
            foreach (var scene in _RemovedScenes)
            {
                if (_SceneGUIDToLiveLink.TryGetValue(scene, out var liveLink))
                {
                    liveLink.Dispose();
                    _SceneGUIDToLiveLink.Remove(scene);
                }

                unloadScenes.Add(scene);
                _SentLoadScenes.Remove(scene);
            }
            _RemovedScenes.Clear();

            _SentLoadScenes.RemoveWhere(scene => !_LoadedScenes.Contains(scene));

            // Process all scenes that the player needs
            foreach (var sceneGuid in _LoadedScenes)
            {
                var isLoaded = _GUIDToEditScene.TryGetValue(sceneGuid, out var scene);

                // We are editing with live link. Ensure it is active & up to date
                if (isLoaded)
                {
                    var liveLink = GetLiveLink(sceneGuid);
                    if (liveLink == null)
                    {
                        AddLiveLinkChangeSet(sceneGuid, changeSets, mode);
                    }
                    else
                    {
                        if (liveLink.LiveLinkDirtyID != GetSceneDirtyID(scene) || liveLink.DidRequestUpdate())
                        {
                            AddLiveLinkChangeSet(sceneGuid, changeSets, mode);
                        }
                    }
                }
                else
                {
                    if (_SentLoadScenes.Add(sceneGuid))
                    {
                        loadScenes.Add(sceneGuid);
                    }
                }
            }
        }
Esempio n. 55
0
 private void CarregarMovimento(GUID guid)
 {
     CarregarMovimento(Data.Abstract.Faturamento.Lancamento.Movimento.MovimentoBase.Create(guid, false) as IMovimento);
 }
Esempio n. 56
0
 // Use the VMDataBridge to safely retrieve our input values
 #region databridge callback
 /// <summary>
 /// Register the data bridge callback.
 /// </summary>
 protected override void OnBuilt()
 {
     base.OnBuilt();
     VMDataBridge.DataBridge.Instance.RegisterCallback(GUID.ToString(), DataBridgeCallback);
     isUpdating = false;
 }
Esempio n. 57
0
 /// <summary>
 /// Instancia este objeto, inicia as variáveis e carrega o registro pelo GUID informado
 /// </summary>
 /// <param name="guid">Identificador único do registro</param>
 public DAV(GUID guid)
     : this()
 {
     Populate(guid);
 }
Esempio n. 58
0
        public override IEnumerable <AssociativeNode> BuildOutputAst(List <AssociativeNode> inputAstNodes)
        {
            this.ClearErrorsAndWarnings();


            if (SelectedItems == null || hasBeenDeleted)
            {
                //SelectedItems = new Dictionary<string, DMLocator>();
                _locatorLstNode      = AstFactory.BuildNullNode();
                _SelectedNameLstNode = AstFactory.BuildNullNode();
                // _mayaLocator = AstFactory.BuildNullNode();
                hasBeenDeleted = false;
                //return Enumerable.Empty<AssociativeNode>();
            }
            else
            {
                if (SelectedItems.Count > 0)
                {
                    //only rebuild the entire list of geom if needed. otherwise this has been created and is built and updated as needed on only the geometry that has changed
                    if (!isFromUpdate)
                    {
                        dynamoObject = new Dictionary <string, AssociativeNode>(SelectedItems.Count);
                        locatorName  = new Dictionary <string, AssociativeNode>(SelectedItems.Count);
                        //mayaLocator = new Dictionary<string, AssociativeNode>(SelectedItems.Count);

                        foreach (var dag in SelectedItems.Values)
                        {
                            buildAstNodes(dag.dagName);
                        }
                    }


                    _locatorLstNode      = AstFactory.BuildExprList(dynamoObject.Values.ToList());
                    _SelectedNameLstNode = AstFactory.BuildExprList(locatorName.Values.ToList());
                    //_mayaLocator = AstFactory.BuildExprList(mayaLocator.Values.ToList());
                }
                else
                {
                    _locatorLstNode = AstFactory.BuildNullNode();
                }
            }

            isFromUpdate = false;

            return(new[]
            {
                AstFactory.BuildAssignment(GetAstIdentifierForOutputIndex(0), _locatorLstNode),
                AstFactory.BuildAssignment(AstFactory.BuildIdentifier(AstIdentifierBase + "_dummy"),
                                           VMDataBridge.DataBridge.GenerateBridgeDataAst(GUID.ToString(), AstFactory.BuildExprList(inputAstNodes))),

                AstFactory.BuildAssignment(GetAstIdentifierForOutputIndex(1), _SelectedNameLstNode),
                AstFactory.BuildAssignment(AstFactory.BuildIdentifier(AstIdentifierBase + "_dummy"),
                                           VMDataBridge.DataBridge.GenerateBridgeDataAst(GUID.ToString(), AstFactory.BuildExprList(inputAstNodes))),
            });
        }
Esempio n. 59
0
 /// <summary>
 /// Construtor com parametro pelo GUID
 /// </summary>
 /// <param name="guid">GUID do movimento</param>
 public Log(GUID guid)
     : this()
 {
     Populate(guid);
 }
Esempio n. 60
0
        /**
         * Read hyperlink from input stream
         *
         * @param in the stream to Read from
         */

        public HyperlinkRecord(RecordInputStream in1)
        {
            _range = new CellRangeAddress(in1);

            // 16-byte GUID
            _guid = new GUID(in1);

            /*
             * streamVersion (4 bytes): An unsigned integer that specifies the version number
             * of the serialization implementation used to save this structure. This value MUST equal 2.
             */
            int streamVersion = in1.ReadInt();

            if (streamVersion != 0x00000002)
            {
                throw new RecordFormatException("Stream Version must be 0x2 but found " + streamVersion);
            }
            _linkOpts = in1.ReadInt();

            if ((_linkOpts & HLINK_LABEL) != 0)
            {
                int label_len = in1.ReadInt();
                _label = in1.ReadUnicodeLEString(label_len);
            }
            if ((_linkOpts & HLINK_TARGET_FRAME) != 0)
            {
                int len = in1.ReadInt();
                _targetFrame = in1.ReadUnicodeLEString(len);
            }
            if ((_linkOpts & HLINK_URL) != 0 && (_linkOpts & HLINK_UNC_PATH) != 0)
            {
                _moniker = null;
                int nChars = in1.ReadInt();
                _address = in1.ReadUnicodeLEString(nChars);
            }
            if ((_linkOpts & HLINK_URL) != 0 && (_linkOpts & HLINK_UNC_PATH) == 0)
            {
                _moniker = new GUID(in1);

                if (URL_MONIKER.Equals(_moniker))
                {
                    int length = in1.ReadInt();

                    /*
                     * The value of <code>length<code> be either the byte size of the url field
                     * (including the terminating NULL character) or the byte size of the url field plus 24.
                     * If the value of this field is set to the byte size of the url field,
                     * then the tail bytes fields are not present.
                     */
                    int remaining = in1.Remaining;
                    if (length == remaining)
                    {
                        int nChars = length / 2;
                        _address = in1.ReadUnicodeLEString(nChars);
                    }
                    else
                    {
                        int nChars = (length - TAIL_SIZE) / 2;
                        _address = in1.ReadUnicodeLEString(nChars);

                        /*
                         * TODO: make sense of the remaining bytes
                         * According to the spec they consist of:
                         * 1. 16-byte  GUID: This field MUST equal
                         *    {0xF4815879, 0x1D3B, 0x487F, 0xAF, 0x2C, 0x82, 0x5D, 0xC4, 0x85, 0x27, 0x63}
                         * 2. Serial version, this field MUST equal 0 if present.
                         * 3. URI Flags
                         */
                        _uninterpretedTail = ReadTail(URL_uninterpretedTail, in1);
                    }
                }
                else if (FILE_MONIKER.Equals(_moniker))
                {
                    _fileOpts = in1.ReadShort();

                    int len = in1.ReadInt();
                    _shortFilename     = StringUtil.ReadCompressedUnicode(in1, len);
                    _uninterpretedTail = ReadTail(FILE_uninterpretedTail, in1);
                    int size = in1.ReadInt();
                    if (size > 0)
                    {
                        int charDataSize = in1.ReadInt();

                        //From the spec: An optional unsigned integer that MUST be 3 if present
                        // but some files has 4
                        int usKeyValue = in1.ReadUShort();
                        _address = StringUtil.ReadUnicodeLE(in1, charDataSize / 2);
                    }
                    else
                    {
                        _address = null;
                    }
                }
                else if (STD_MONIKER.Equals(_moniker))
                {
                    _fileOpts = in1.ReadShort();

                    int len = in1.ReadInt();

                    byte[] path_bytes = new byte[len];
                    in1.ReadFully(path_bytes);

                    _address = Encoding.UTF8.GetString(path_bytes);
                }
            }

            if ((_linkOpts & HLINK_PLACE) != 0)
            {
                int len = in1.ReadInt();
                _textMark = in1.ReadUnicodeLEString(len);
            }

            if (in1.Remaining > 0)
            {
                Console.WriteLine(HexDump.ToHex(in1.ReadRemainder()));
            }
        }