text
string
size
int64
token_count
int64
#include <gtest/gtest.h> #include <gmock/gmock.h> #include <string> #include <stout/json.hpp> #include <stout/stringify.hpp> using std::string; TEST(JsonTest, BinaryData) { JSON::String s(string("\"\\/\b\f\n\r\t\x00\x19 !#[]\x7F\xFF", 17)); EXPECT_EQ("\"\\\"\\\\\\/\\b\\f\\n\\r\\t\\u0000\\u0019 !#[]\\u007F\\u00FF\"", stringify(s)); } TEST(JsonTest, NumberFormat) { // Test whole numbers. EXPECT_EQ("0", stringify(JSON::Number(0.0))); EXPECT_EQ("1", stringify(JSON::Number(1.0))); // Negative. EXPECT_EQ("-1", stringify(JSON::Number(-1.0))); // Expect at least 15 digits of precision. EXPECT_EQ("1234567890.12345", stringify(JSON::Number(1234567890.12345))); }
702
340
// gameconstants.cc // Bitwise functions for some of the various enums // Teemu Mäkinen <culkah@gmail.com> 2014 #include "gameconstants.h"
141
54
/**************************************************************************** * Copyright (c) 2019, CEA * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *****************************************************************************/ ////////////////////////////////////////////////////////////////////////////// // // File: Op_VEF_Face.cpp // Directory: $TRUST_ROOT/src/VEF/Operateurs // Version: /main/53 // ////////////////////////////////////////////////////////////////////////////// #include <Op_VEF_Face.h> #include <Matrice_Morse.h> #include <Equation_base.h> #include <Champ_Inc.h> #include <Sortie.h> #include <Operateur.h> #include <Probleme_base.h> #include <Champ_Don.h> #include <Champ_Uniforme.h> #include <Schema_Temps_base.h> #include <Milieu_base.h> #include <Operateur_base.h> #include <Operateur_Diff_base.h> #include <Op_Conv_VEF_base.h> #include <EcrFicPartage.h> #include <SFichier.h> #include <Debog.h> #include <communications.h> #include <DoubleTrav.h> #include <Matrice_Morse_Diag.h> // Description // Dimensionnement de la matrice qui devra recevoir les coefficients provenant de // la convection, de la diffusion pour le cas des faces. // Cette matrice a une structure de matrice morse. // Nous commencons par calculer les tailles des tableaux tab1 et tab2. void Op_VEF_Face::dimensionner(const Zone_VEF& la_zone, const Zone_Cl_VEF& la_zone_cl, Matrice_Morse& la_matrice) const { // Dimensionnement de la matrice qui devra recevoir les coefficients provenant de // la convection, de la diffusion pour le cas des faces. // Cette matrice a une structure de matrice morse. // Nous commencons par calculer les tailles des tableaux tab1 et tab2. // Pour ce faire il faut chercher les faces voisines de la face consideree. int num_face; int ndeb = 0; int nfin = la_zone.nb_faces(); int nnnn = la_zone.nb_faces_tot(); nfin=nnnn; int i,j,k,kk; int elem1,elem2; int nb_faces_elem = la_zone.zone().nb_faces_elem(); //const Conds_lim& les_cl = la_zone_cl.les_conditions_limites(); int nb_comp = 1; const DoubleTab& champ_inconnue = la_zone_cl.equation().inconnue().valeurs(); if (champ_inconnue.nb_dim() == 2) nb_comp = champ_inconnue.dimension(1); la_matrice.dimensionner(nfin*nb_comp,nfin*nb_comp,0); IntVect& tab1=la_matrice.get_set_tab1(); IntVect& tab2=la_matrice.get_set_tab2(); DoubleVect& coeff = la_matrice.get_set_coeff(); coeff=0; const IntTab& elem_faces = la_zone.elem_faces(); const IntTab& face_voisins = la_zone.face_voisins(); // A chaque face on associe un tableau d'entiers et une liste de reels: // voisines[i] = {j t.q j>i et M(i,j) est non nul } // IntVect rang_voisin(nfin*nb_comp); IntVect rang_voisin(nnnn*nb_comp); rang_voisin=nb_comp; // On traite toutes les faces for (num_face= 0; num_face<nfin; num_face++) { elem1 = face_voisins(num_face,0); elem2 = face_voisins(num_face,1); for (i=0; i<nb_faces_elem; i++) { if ( (j=elem_faces(elem1,i)) != num_face ) { for (k=0; k<nb_comp; k++) { rang_voisin(num_face*nb_comp+k)+=nb_comp; } } if (elem2!=-1) if ( (j=elem_faces(elem2,i)) != num_face ) { for (k=0; k<nb_comp; k++) { rang_voisin(num_face*nb_comp+k)+=nb_comp; } } } } // les faces voisines de num_face etant desormais comtabilisees // nous dimensionnons tab1 et tab2 au nombre de faces tab1(0)=1; for (num_face=ndeb; num_face<nfin; num_face++) { for (k=0; k< nb_comp; k++) { tab1(num_face*nb_comp+1+k)=rang_voisin(num_face*nb_comp+k)+tab1(num_face*nb_comp+k); } } la_matrice.dimensionner(nfin*nb_comp,tab1(nfin*nb_comp)-1); for (num_face = 0; num_face < nfin; num_face++ ) { for (k=0; k< nb_comp; k++) { for (kk=0; kk<nb_comp; kk++) { int modulo = (k+kk)%nb_comp; tab2[tab1[num_face*nb_comp+k]-1+kk]=num_face*nb_comp+1+modulo; } rang_voisin[num_face*nb_comp+k]=tab1[num_face*nb_comp+k]+nb_comp-1; } } // On traite toutes les faces for (num_face= 0; num_face<nfin; num_face++) { elem1 = face_voisins(num_face,0); elem2 = face_voisins(num_face,1); for (i=0; i<nb_faces_elem; i++) { if ( (j=elem_faces(elem1,i)) != num_face ) { for (k=0; k<nb_comp; k++) { for (kk=0; kk<nb_comp; kk++) { int modulo = (k+kk)%nb_comp; tab2[rang_voisin[num_face*nb_comp+k]+kk]=j*nb_comp+1+modulo; } rang_voisin[num_face*nb_comp+k]+=nb_comp; } } if (elem2!=-1) if ( (j=elem_faces(elem2,i)) != num_face ) { for (k=0; k<nb_comp; k++) { for (kk=0; kk<nb_comp; kk++) { int modulo = (k+kk)%nb_comp; tab2[rang_voisin[num_face*nb_comp+k]+kk]=j*nb_comp+1+modulo; } rang_voisin[num_face*nb_comp+k]+=nb_comp; } } } } } // Description // Modification des coef de la matrice et du second membre pour les conditions // de Dirichlet void Op_VEF_Face::modifier_pour_Cl(const Zone_VEF& la_zone, const Zone_Cl_VEF& la_zone_cl, Matrice_Morse& la_matrice, DoubleTab& secmem) const { // Dimensionnement de la matrice qui devra recevoir les coefficients provenant de // la convection, de la diffusion pour le cas des faces. // Cette matrice a une structure de matrice morse. // Nous commencons par calculer les tailles des tableaux tab1 et tab2. const Conds_lim& les_cl = la_zone_cl.les_conditions_limites(); const IntVect& tab1=la_matrice.get_tab1(); DoubleVect& coeff = la_matrice.get_set_coeff(); int nb_comp = 1; const DoubleTab& champ_inconnue = la_zone_cl.equation().inconnue().valeurs(); if (champ_inconnue.nb_dim() == 2) nb_comp = champ_inconnue.dimension(1); ArrOfDouble normale(nb_comp); int size = les_cl.size(); for (int i=0; i<size; i++) { const Cond_lim& la_cl = les_cl[i]; if (sub_type(Dirichlet,la_cl.valeur())) { const Dirichlet& la_cl_Dirichlet = ref_cast(Dirichlet,la_cl.valeur()); const Front_VF& la_front_dis = ref_cast(Front_VF,la_cl.frontiere_dis()); int nfaces = la_front_dis.nb_faces(); for (int ind_face=0; ind_face < nfaces; ind_face++) { int face = la_front_dis.num_face(ind_face); for (int comp=0; comp<nb_comp; comp++) { int idiag = tab1[face*nb_comp+comp]-1; coeff[idiag]=1; // pour les voisins int nbvois = tab1[face*nb_comp+1+comp] - tab1[face*nb_comp+comp]; for (int k=1; k < nbvois; k++) { coeff[idiag+k]=0; } // pour le second membre if (nb_comp == 1) secmem(face) = la_cl_Dirichlet.val_imp(ind_face,0); else secmem(face,comp)= la_cl_Dirichlet.val_imp(ind_face,comp); } } } if (sub_type(Dirichlet_homogene,la_cl.valeur())) { const Dirichlet_homogene& la_cl_Dirichlet_homogene = ref_cast(Dirichlet_homogene,la_cl.valeur()); const Front_VF& la_front_dis = ref_cast(Front_VF,la_cl.frontiere_dis()); int nfaces = la_front_dis.nb_faces_tot(); for (int ind_face=0; ind_face < nfaces; ind_face++) { int face = la_front_dis.num_face(ind_face); for (int comp=0; comp<nb_comp; comp++) { int idiag = tab1[face*nb_comp+comp]-1; coeff[idiag]=1; // pour les voisins int nbvois = tab1[face*nb_comp+1+comp] - tab1[face*nb_comp+comp]; for (int k=1; k < nbvois; k++) { coeff[idiag+k]=0; } // pour le second membre if (nb_comp == 1) secmem(face) = la_cl_Dirichlet_homogene.val_imp(ind_face,0); else secmem(face,comp)= la_cl_Dirichlet_homogene.val_imp(ind_face,comp); } } } if (sub_type(Symetrie,la_cl.valeur())) if (la_zone_cl.equation().inconnue().valeur().nature_du_champ()==vectoriel) { const IntVect& tab2=la_matrice.get_tab2(); const Front_VF& la_front_dis = ref_cast(Front_VF,la_cl.frontiere_dis()); const DoubleTab& face_normales = la_zone.face_normales(); int nfaces = la_front_dis.nb_faces_tot(); ArrOfDouble somme(la_matrice.nb_colonnes()); // On dimensionne au plus grand for (int ind_face=0; ind_face < nfaces; ind_face++) { int face = la_front_dis.num_face(ind_face); double max_coef=0; int ind_max=-1; double n2=0; for (int comp=0; comp<nb_comp; comp++) { normale[comp]=face_normales(face,comp); if (dabs(normale[comp])>dabs(max_coef)) { max_coef=normale[comp]; ind_max=comp; } n2+=normale[comp]*normale[comp]; } normale/=sqrt(n2); max_coef=normale[ind_max]; // On commence par recalculer secmem=secmem-A *present pour pouvoir modifier A (on en profite pour projeter) int nb_coeff_ligne=tab1[face*nb_comp+1] - tab1[face*nb_comp]; for (int k=0; k<nb_coeff_ligne; k++) { for (int comp=0; comp<nb_comp; comp++) { int j=tab2[tab1[face*nb_comp+comp]-1+k]-1; //assert(j!=(face*nb_comp+comp)); //if ((j>=(face*nb_comp))&&(j<(face*nb_comp+nb_comp))) const double& coef_ij=la_matrice(face*nb_comp+comp,j); int face2=j/nb_comp; int comp2=j-face2*nb_comp; secmem(face,comp)-=coef_ij*champ_inconnue(face2,comp2); } } double somme_b=0; for (int comp=0; comp<nb_comp; comp++) somme_b+=secmem(face,comp)*normale[comp]; // on retire secmem.n n for (int comp=0; comp<nb_comp; comp++) secmem(face,comp)-=somme_b*normale[comp]; // on doit remettre la meme diagonale partout on prend la moyenne double ref=0; for (int comp=0; comp<nb_comp; comp++) { int j0=face*nb_comp+comp; ref+=la_matrice(j0,j0); } ref/=nb_comp; for (int comp=0; comp<nb_comp; comp++) { int j0=face*nb_comp+comp; double rap=ref/la_matrice(j0,j0); for (int k=0; k<nb_coeff_ligne; k++) { int j=tab2[tab1[j0]-1+k]-1; la_matrice(j0,j)*=rap; } assert(est_egal(la_matrice(j0,j0),ref)); } // on annule tous les coef extra diagonaux du bloc // for (int k=1; k<nb_coeff_ligne; k++) { for (int comp=0; comp<nb_comp; comp++) { int j=tab2[tab1[face*nb_comp+comp]-1+k]-1; assert(j!=(face*nb_comp+comp)); if ((j>=(face*nb_comp))&&(j<(face*nb_comp+nb_comp))) la_matrice(face*nb_comp+comp,j)=0; } } // pour les blocs extra diagonaux on assure que Aij.ni=0 //ArrOfDouble somme(nb_coeff_ligne); for (int k=0; k<nb_coeff_ligne; k++) { somme(k)=0; int j=tab2[tab1[face*nb_comp]-1+k]-1; // le coeff j doit exister sur les nb_comp lignes double dsomme=0; for (int comp=0; comp<nb_comp; comp++) dsomme+=la_matrice(face*nb_comp+comp,j)*normale[comp]; // on retire somme ni for (int comp=0; comp<nb_comp; comp++) // on modifie que les coefficients ne faisant pas intervenir u(face,comp) if ((j<(face*nb_comp))||(j>=(face*nb_comp+nb_comp))) la_matrice(face*nb_comp+comp,j)-=(dsomme)*normale[comp]; } // Finalement on recalcule secmem=secmem+A*champ_inconnue (A a ete beaucoup modiife) for (int k=0; k<nb_coeff_ligne; k++) { for (int comp=0; comp<nb_comp; comp++) { int j=tab2[tab1[face*nb_comp+comp]-1+k]-1; int face2=j/nb_comp; int comp2=j-face2*nb_comp; const double& coef_ij=la_matrice(face*nb_comp+comp,j); secmem(face,comp)+=coef_ij*champ_inconnue(face2,comp2); } } { // verification double somme_c=0; for (int comp=0; comp<nb_comp; comp++) somme_c+=secmem(face,comp)*normale[comp]; // on retire secmem.n n for (int comp=0; comp<nb_comp; comp++) secmem(face,comp)-=somme_c*normale[comp]; } } } } } void Op_VEF_Face::modifier_flux( const Operateur_base& op) const { controle_modifier_flux_=1; DoubleTab& flux_bords_=op.flux_bords(); if (flux_bords_.nb_dim()!=2) return; const Probleme_base& pb=op.equation().probleme(); const Zone_VEF& la_zone_vef=ref_cast(Zone_VEF,op.equation().zone_dis().valeur()); int nb_compo=flux_bords_.dimension(1); // On multiplie le flux au bord par rho*Cp sauf si c'est un operateur de diffusion avec la conductivite comme champ if (op.equation().inconnue().le_nom()=="temperature" && !( sub_type(Operateur_Diff_base,op) && ref_cast(Operateur_Diff_base,op).diffusivite().le_nom() == "conductivite" ) ) { const Champ_Don& rho = (op.equation()).milieu().masse_volumique(); const Champ_Don& Cp = (op.equation()).milieu().capacite_calorifique(); int rho_uniforme=(sub_type(Champ_Uniforme,rho.valeur()) ? 1:0); int cp_uniforme=(sub_type(Champ_Uniforme,Cp.valeur()) ? 1:0); double Cp_=0,rho_=0; int is_rho_u=pb.is_QC(); if (is_rho_u) { is_rho_u=0; if (sub_type(Op_Conv_VEF_base,op)) { if (ref_cast(Op_Conv_VEF_base,op).vitesse().le_nom()=="rho_u") is_rho_u=1; } } const int& nb_faces_bords=la_zone_vef.nb_faces_bord(); for (int face=0; face<nb_faces_bords; face++) { if (cp_uniforme) Cp_=Cp(0,0); else { if (Cp.nb_comp()==1) Cp_=Cp(face); else Cp_=Cp(face,0); } if (rho_uniforme) rho_=rho(0,0); else { if (rho.nb_comp()==1) rho_=rho(face); else rho_=rho(face,0); } // si on est en QC temperature et si on a calcule div(rhou * T) // il ne faut pas remultiplier par rho if (is_rho_u) rho_=1; flux_bords_(face,0) *= (rho_*Cp_); } } // On multiplie par rho si Navier Stokes incompressible Nom nom_eqn=op.equation().que_suis_je(); if (nom_eqn.debute_par("Navier_Stokes") && pb.milieu().que_suis_je()=="Fluide_Incompressible") { const Champ_Don& rho = op.equation().milieu().masse_volumique(); if (sub_type(Champ_Uniforme,rho.valeur())) { double coef = rho(0,0); int nb_faces_bord=la_zone_vef.nb_faces_bord(); for (int face=0; face<nb_faces_bord; face++) for(int k=0; k<nb_compo; k++) flux_bords_(face,k) *= coef; } } } // Description // Impression des flux d'un operateur VEF aux faces (ie: diffusion, convection) // int Op_VEF_Face::impr(Sortie& os, const Operateur_base& op) const { const Zone_VEF& la_zone_vef=ref_cast(Zone_VEF,op.equation().zone_dis().valeur()); DoubleTab& flux_bords_=op.flux_bords(); if (flux_bords_.nb_dim()!=2) { Cout << "L'impression des flux n'est pas codee pour l'operateur " << op.que_suis_je() << finl; return 1; } if (controle_modifier_flux_==0) if (max_abs_array(flux_bords_)!=0) { Cerr<<op.que_suis_je()<<" appelle Op_VEF_Face::impr sans avoir appeler Op_VEF_Face::modifier_flux, on arrete tout "<<finl; Process::exit(); } int nb_compo=flux_bords_.dimension(1); const Probleme_base& pb=op.equation().probleme(); const Schema_Temps_base& sch=pb.schema_temps(); // On n'imprime les moments que si demande et si on traite l'operateur de diffusion de la vitesse int impr_mom=0; if (la_zone_vef.zone().Moments_a_imprimer() && sub_type(Operateur_Diff_base,op) && op.equation().inconnue().le_nom()=="vitesse") impr_mom=1; const int impr_sum=(la_zone_vef.zone().Bords_a_imprimer_sum().est_vide() ? 0:1); const int impr_bord=(la_zone_vef.zone().Bords_a_imprimer().est_vide() ? 0:1); // Calcul des moments const int nb_faces = la_zone_vef.nb_faces_tot(); DoubleTab xgr(nb_faces,Objet_U::dimension); xgr=0.; if (impr_mom) { const DoubleTab& xgrav = la_zone_vef.xv(); const ArrOfDouble& c_grav=la_zone_vef.zone().cg_moments(); for (int num_face=0; num_face <nb_faces; num_face++) for (int i=0; i<Objet_U::dimension; i++) xgr(num_face,i)=xgrav(num_face,i)-c_grav(i); } // On parcours les frontieres pour sommer les flux par frontiere dans le tableau flux_bord DoubleVect bilan(nb_compo); bilan = 0; int nb_cl = la_zone_vef.nb_front_Cl(); DoubleTrav flux_bords(4,nb_cl,nb_compo); flux_bords=0.; /* flux_bord(k) -> flux_bords(0,num_cl,k) flux_bord_perio1(k) -> flux_bords(1,num_cl,k) flux_bord_perio2(k) -> flux_bords(2,num_cl,k) moment(k) -> flux_bords(3,num_cl,k) */ for (int num_cl=0; num_cl<nb_cl; num_cl++) { const Cond_lim& la_cl = op.equation().zone_Cl_dis().les_conditions_limites(num_cl); const Front_VF& frontiere_dis = ref_cast(Front_VF,la_cl.frontiere_dis()); int ndeb = frontiere_dis.num_premiere_face(); int nfin = ndeb + frontiere_dis.nb_faces(); int perio = (sub_type(Periodique,la_cl.valeur())?1:0); for (int face=ndeb; face<nfin; face++) { for(int k=0; k<nb_compo; k++) { flux_bords(0,num_cl,k)+=flux_bords_(face, k); if(perio) { if(face<(ndeb+frontiere_dis.nb_faces()/2)) flux_bords(1,num_cl,k)+=flux_bords_(face, k); else flux_bords(2,num_cl,k)+=flux_bords_(face, k); } } if (impr_mom) { // Calcul du moment exerce par le fluide sur le bord (OM/\F) if (Objet_U::dimension==2) flux_bords(3,num_cl,0)+=flux_bords_(face,1)*xgr(face,0)-flux_bords_(face,0)*xgr(face,1); else { flux_bords(3,num_cl,0)+=flux_bords_(face,2)*xgr(face,1)-flux_bords_(face,1)*xgr(face,2); flux_bords(3,num_cl,1)+=flux_bords_(face,0)*xgr(face,2)-flux_bords_(face,2)*xgr(face,0); flux_bords(3,num_cl,2)+=flux_bords_(face,1)*xgr(face,0)-flux_bords_(face,0)*xgr(face,1); } } } // fin for face } // fin for num_cl // On somme les contributions de chaque processeur mp_sum_for_each_item(flux_bords); // Ecriture dans les fichiers if (Process::je_suis_maitre()) { // Open files if needed SFichier Flux; op.ouvrir_fichier(Flux,"",1); SFichier Flux_moment; op.ouvrir_fichier(Flux_moment,"moment",impr_mom); SFichier Flux_sum; op.ouvrir_fichier(Flux_sum,"sum",impr_sum); // Write time Flux.add_col(sch.temps_courant()); if (impr_mom) Flux_moment.add_col(sch.temps_courant()); if (impr_sum) Flux_sum.add_col(sch.temps_courant()); // Write flux on boundaries for (int num_cl=0; num_cl<nb_cl; num_cl++) { const Frontiere_dis_base& la_fr = op.equation().zone_Cl_dis().les_conditions_limites(num_cl).frontiere_dis(); const Cond_lim& la_cl = op.equation().zone_Cl_dis().les_conditions_limites(num_cl); int perio = (sub_type(Periodique,la_cl.valeur())?1:0); for(int k=0; k<nb_compo; k++) { if(perio) { Flux.add_col(flux_bords(1,num_cl,k)); Flux.add_col(flux_bords(2,num_cl,k)); } else Flux.add_col(flux_bords(0,num_cl,k)); if (impr_mom) Flux_moment.add_col(flux_bords(3,num_cl,k)); if (la_zone_vef.zone().Bords_a_imprimer_sum().contient(la_fr.le_nom())) Flux_sum.add_col(flux_bords(0,num_cl,k)); // On somme les flux de toutes les frontieres pour mettre dans le tableau bilan bilan(k)+=flux_bords(0,num_cl,k); } } // On imprime les bilans et on va a la ligne for(int k=0; k<nb_compo; k++) Flux.add_col(bilan(k)); Flux << finl; if (impr_mom) Flux_moment << finl; if (impr_sum) Flux_sum << finl; } const LIST(Nom)& Liste_Bords_a_imprimer = la_zone_vef.zone().Bords_a_imprimer(); if (!Liste_Bords_a_imprimer.est_vide()) { EcrFicPartage Flux_face; op.ouvrir_fichier_partage(Flux_face,"",impr_bord); // Impression sur chaque face si demande for (int num_cl=0; num_cl<nb_cl; num_cl++) { const Frontiere_dis_base& la_fr = op.equation().zone_Cl_dis().les_conditions_limites(num_cl).frontiere_dis(); const Cond_lim& la_cl = op.equation().zone_Cl_dis().les_conditions_limites(num_cl); const Front_VF& frontiere_dis = ref_cast(Front_VF,la_cl.frontiere_dis()); int ndeb = frontiere_dis.num_premiere_face(); int nfin = ndeb + frontiere_dis.nb_faces(); // Impression sur chaque face if (Liste_Bords_a_imprimer.contient(la_fr.le_nom())) { Flux_face << "# Flux par face sur " << la_fr.le_nom() << " au temps "; sch.imprimer_temps_courant(Flux_face); Flux_face << " : " << finl; const DoubleTab& xv=la_zone_vef.xv(); for (int face=ndeb; face<nfin; face++) { if (Objet_U::dimension==2) Flux_face << "# Face a x= " << xv(face,0) << " y= " << xv(face,1) ; else if (Objet_U::dimension==3) Flux_face << "# Face a x= " << xv(face,0) << " y= " << xv(face,1) << " z= " << xv(face,2) ; for(int k=0; k<nb_compo; k++) Flux_face << " surface_face(m2)= " << la_zone_vef.face_surfaces(face) << " flux_par_surface(W/m2)= " << flux_bords_(face, k)/la_zone_vef.face_surfaces(face) << " flux(W)= " << flux_bords_(face, k) ; Flux_face << finl; } Flux_face.syncfile(); } } } return 1; } ///////////////////////////////////////// // Methode pour l'implicite ///////////////////////////////////////// void modif_matrice_pour_periodique_avant_contribuer(Matrice_Morse& matrice,const Equation_base& eqn) { int nb_comp=1; { const DoubleTab& inconnue=eqn.inconnue().valeurs(); int nb_dim=inconnue.nb_dim(); if(nb_dim==2) nb_comp=inconnue.dimension(1); } const Zone_Cl_dis_base& zone_Cl_VEF=eqn.zone_Cl_dis().valeur(); const Zone_VF& zone_VEF= ref_cast(Zone_VF,eqn.zone_dis().valeur()); int nb_bords=zone_VEF.nb_front_Cl(); const IntTab& elem_faces = zone_VEF.elem_faces(); const IntTab& face_voisins = zone_VEF.face_voisins(); int nb_faces_elem = elem_faces.dimension(1); for (int n_bord=0; n_bord<nb_bords; n_bord++) { const Cond_lim& la_cl = zone_Cl_VEF.les_conditions_limites(n_bord); if (sub_type(Periodique,la_cl.valeur())) { const Periodique& la_cl_perio = ref_cast(Periodique,la_cl.valeur()); // on ne parcourt que la moitie des faces periodiques // on copiera a la fin le resultat dans la face associe.. const Front_VF& le_bord = ref_cast(Front_VF,la_cl.frontiere_dis()); int num1 = le_bord.num_premiere_face(); int num2=num1+le_bord.nb_faces()/2; for (int dir=0; dir<2; dir++) for (int num_face=num1; num_face<num2; num_face++) { int elem1 = face_voisins(num_face,dir); int fac_asso = la_cl_perio.face_associee(num_face-num1)+num1; for (int i=0; i<nb_faces_elem; i++) { int j=elem_faces(elem1,i); for (int nc=0; nc<nb_comp; nc++) { int n0=num_face*nb_comp+nc; int n0perio=fac_asso*nb_comp+nc; if (((j==num_face)||(j==fac_asso))) { if (dir==0) { assert(matrice(n0,n0perio)==0); assert(matrice(n0perio,n0)==0); assert(matrice(n0,n0)==matrice(n0perio,n0perio)); double titi=(matrice(n0,n0))/2.; matrice(n0,n0)=titi; matrice(n0perio,n0perio)=titi; } } else { for (int nc2=0; nc2<nb_comp; nc2++) { int j20=j*nb_comp+nc2; assert(matrice(n0,j20)==matrice(n0perio,j20)); double titi=(matrice(n0,j20)/2.); matrice(n0,j20)=titi; matrice(n0perio,j20)=titi; } } } } } } } // matrice.imprimer(Cerr); } void modif_matrice_pour_periodique_apres_contribuer(Matrice_Morse& matrice,const Equation_base& eqn) { int nb_comp=1; { const DoubleTab& inconnue=eqn.inconnue().valeurs(); int nb_dim=inconnue.nb_dim(); if(nb_dim==2) nb_comp=inconnue.dimension(1); } const Zone_Cl_dis_base& zone_Cl_VEF=eqn.zone_Cl_dis().valeur(); const Zone_VF& zone_VEF= ref_cast(Zone_VF,eqn.zone_dis().valeur()); int nb_bords=zone_VEF.nb_front_Cl(); const IntTab& elem_faces = zone_VEF.elem_faces(); const IntTab& face_voisins = zone_VEF.face_voisins(); int nb_faces_elem = elem_faces.dimension(1); for (int n_bord=0; n_bord<nb_bords; n_bord++) { const Cond_lim& la_cl = zone_Cl_VEF.les_conditions_limites(n_bord); if (sub_type(Periodique,la_cl.valeur())) { const Periodique& la_cl_perio = ref_cast(Periodique,la_cl.valeur()); // on ne parcourt que la moitie des faces periodiques // on copiera a la fin le resultat dans la face associe.. const Front_VF& le_bord = ref_cast(Front_VF,la_cl.frontiere_dis()); int num1 = le_bord.num_premiere_face(); int num2 = num1+le_bord.nb_faces()/2; for (int dir=0; dir<2; dir++) for (int num_face=num1; num_face<num2; num_face++) { int elem1 = face_voisins(num_face,dir); int fac_asso = la_cl_perio.face_associee(num_face-num1)+num1; for (int i=0; i<nb_faces_elem; i++) { int j=elem_faces(elem1,i); //if (j!=num_face) for (int nc=0; nc<nb_comp; nc++) { int n0=num_face*nb_comp+nc; // int j0=j*nb_comp+nc; int n0perio=fac_asso*nb_comp+nc; if (((j==num_face)||(j==fac_asso))) { if (dir==0) { for (int nc2=0; nc2<nb_comp; nc2++) { int j0=num_face*nb_comp+nc2; int j0perio=fac_asso*nb_comp+nc2; matrice(n0,j0)+=matrice(n0,j0perio); matrice(n0,j0perio)=0; matrice(n0perio,j0perio)+=matrice(n0perio,j0); matrice(n0perio,j0)=0; double titi=(matrice(n0,j0)+matrice(n0perio,j0perio)); matrice(n0,j0)=titi; if (nc!=nc2) { matrice(n0perio,j0)=titi; matrice(n0perio,j0perio)=0; } else matrice(n0perio,j0perio)=titi; } } } else { for (int nc2=0; nc2<nb_comp; nc2++) { int j20=j*nb_comp+nc2; double titi=(matrice(n0,j20)+matrice(n0perio,j20)); matrice(n0,j20)=titi; matrice(n0perio,j20)=titi; } } } } } } } // matrice.imprimer(Cerr); } // Description: divise les coefficients sur les ligne des faces periodiques par 2 en prevision // de l'application modifier_matrice_pour_periodique_apres_contribuer qui va sommer les 2 lignes des faces periodiques associees void Op_VEF_Face::modifier_matrice_pour_periodique_avant_contribuer(Matrice_Morse& matrice,const Equation_base& eqn) const { // si matrice_morse_diag pas de contribution n0 n0perio if (sub_type(Matrice_Morse_Diag,matrice)) return; modif_matrice_pour_periodique_avant_contribuer(matrice,eqn); } // Description: Somme les 2 lignes des faces periodiques associees // permet de calculer dans le code sans se poser de question pour retrouver la face_associee // on ne parcourt que la moitiee des faces periodiques dans contribuer_a_avec (en general). void Op_VEF_Face::modifier_matrice_pour_periodique_apres_contribuer(Matrice_Morse& matrice,const Equation_base& eqn) const { // si matrice_morse_diag pas de contribution n0 n0perio if (sub_type(Matrice_Morse_Diag,matrice)) return; modif_matrice_pour_periodique_apres_contribuer(matrice,eqn); // verification que la matrice est bien periodique #ifndef NDEBUG // int nb_comp=1; { const DoubleTab& inconnue=eqn.inconnue().valeurs(); int nb_dim=inconnue.nb_dim(); if(nb_dim==2) nb_comp=inconnue.dimension(1); } const Zone_Cl_dis_base& zone_Cl_VEF=eqn.zone_Cl_dis().valeur(); const Zone_VF& zone_VEF= ref_cast(Zone_VF,eqn.zone_dis().valeur()); int nb_bords=zone_VEF.nb_front_Cl(); const IntVect& tab1=matrice.get_tab1(); const IntVect& tab2=matrice.get_tab2(); for (int n_bord=0; n_bord<nb_bords; n_bord++) { const Cond_lim& la_cl = zone_Cl_VEF.les_conditions_limites(n_bord); const Front_VF& le_bord = ref_cast(Front_VF,la_cl.frontiere_dis()); int num1 = le_bord.num_premiere_face(); // int num2 = num1 + le_bord.nb_faces(); if (sub_type(Periodique,la_cl.valeur())) { const Periodique& la_cl_perio = ref_cast(Periodique,la_cl.valeur()); int fac_asso; // on ne parcourt que la moitie des faces periodiques // on copiera a la fin le resultat dans la face associe.. int num2=num1+le_bord.nb_faces()/2; for (int num_face=num1; num_face<num2; num_face++) for (int nc=0; nc<nb_comp; nc++) { fac_asso = la_cl_perio.face_associee(num_face-num1)+num1; int n0=num_face*nb_comp+nc; int n0perio=fac_asso*nb_comp+nc; // on verifie que les 2 lignes sont identiques ( sauf la case diagonale qui n'est pas au meme endroit) for (int j=tab1[n0]-1; j<tab1[n0+1]-1; j++) { int c=tab2[j]-1; if ((c!=n0)&&(c!=n0perio)) { double test=matrice(n0,c)-matrice(n0perio,c); if (test!=0) { Cerr<< "Pb matrice non periodique face"<<num_face<<" composante "<<nc<<" colonne " <<c<<finl; Cerr<<" diff "<<test<<" coef1 "<<matrice(n0,c)<<" coef2 "<<matrice(n0perio,c)<<finl; Process::exit(); } } } if ((matrice(n0,n0perio)!=0)||(matrice(n0perio,n0)!=0)) { Cerr<< "Pb matrice non periodique face"<<num_face<<" composante "<<nc<<finl; Cerr<<" coef non nul"<<matrice(n0,n0perio)<<" "<<matrice(n0perio,n0)<<finl; Process::exit(); } if (matrice(n0,n0)!=matrice(n0perio,n0perio)) { double test= matrice(n0,n0perio)-matrice(n0perio,n0); Cerr<< "Pb matrice non periodique face"<<num_face<<" composante "<<nc<<finl; Cerr<<" diff "<<test<<" coef different "<<matrice(n0,n0)<<" "<<matrice(n0perio,n0perio)<<finl; Process::exit(); } } } } /* Matrice_Morse es(matrice); modif_matrice_pour_periodique_avant_contribuer(es,eqn); modif_matrice_pour_periodique_apres_contribuer(es,eqn); es.coeff_-=(matrice.coeff_); Cerr<<" erreur apres modifier_matrice_pour_periodique_apres_contribuer"<< mp_max_abs_vect(es.coeff_)<<finl; assert(mp_max_abs_vect(es.coeff_)<1e-9); */ #endif }
37,161
13,190
/* * Copyright 2021 Niket Naidu. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "target/target.h" namespace buildcc::base { void Target::AddPchAbsolute(const fs::path &absolute_filepath) { LockedAfterBuild(); const auto file_ext_type = ext_.GetType(absolute_filepath); env::assert_fatal(FileExt::IsValidHeader(file_ext_type), fmt::format("{} does not have a valid header extension", absolute_filepath.string())); state_.contains_pch = true; const fs::path absolute_pch = fs::path(absolute_filepath).make_preferred(); storer_.current_pch_files.user.insert(absolute_pch); } void Target::AddPch(const fs::path &relative_filename, const fs::path &relative_to_target_path) { env::log_trace(name_, __FUNCTION__); // Compute the absolute source path fs::path absolute_pch = target_root_dir_ / relative_to_target_path / relative_filename; AddPchAbsolute(absolute_pch); } } // namespace buildcc::base
1,544
471
#include "Stdafx.h" #include "GameObject/GameObject.h" #include "Core/GameScene.h" using namespace Phoenix; FGameObject::FGameObject() { } FGameObject::FGameObject(FGameScene& inGameScene, ID inId) : Id(inId), GameScene(&inGameScene) { } FGameObject::~FGameObject() { } void FGameObject::AddComponent(BaseComponent* inComponent, TypeId inComponentTypeId) { GameScene->GameObjectAttributes.Storage.AddComponent(this, inComponent, inComponentTypeId); } const FGameObject::ID& FGameObject::GetId() const { return Id; } BaseComponent& FGameObject::GetComponent(TypeId InTypeId) const { return GameScene->GameObjectAttributes.Storage.GetComponent(*this, InTypeId); } void FGameObject::SetActive(const bool InActive) { GameScene->ActivateGameObject(*this, InActive); } bool FGameObject::operator==(const FGameObject& GameObject) const { return Id == GameObject.Id && GameObject.GameScene == GameScene; } void FGameObject::RemoveComponent(TypeId InComponentTypeId) { GameScene->GameObjectAttributes.Storage.RemoveComponent(*this, InComponentTypeId); }
1,063
351
#include <atcoder/all> #include <iostream> #include <random> #include <iostream> #include <algorithm> #include <vector> #include <queue> #include <set> #include <map> #include <math.h> #include <unistd.h> #include <unordered_set> #include <unordered_map> #define rep(i,n) for(int i=0;i<n;i++) #define rep2(i,s,n) for(int i=s;i<n;i++) #define repd(i,s,n,d) for(int i=s;i<n;i+=d) #define repit(col) for(auto it = std::begin(col); it != std::end(col); ++it) using namespace std; using namespace atcoder; using mint = static_modint<377487361>; typedef long long ll; int main() { int n = 1 << 24;; n >>= 2; vector<mint> a(n), b(n); for (int i = 0; i < n; i++) { a[i] = i + 1234; b[i] = i + 5678; } auto c = convolution(a, b); printf("%d\n", c[0].val()); return 0; }
779
372
// Copyright 2020-2022 The Defold Foundation // Copyright 2014-2020 King // Copyright 2009-2014 Ragnar Svensson, Christian Murray // Licensed under the Defold License version 1.0 (the "License"); you may not use // this file except in compliance with the License. // // You may obtain a copy of the License, together with FAQs at // https://www.defold.com/license // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #include <assert.h> #include "lz4.h" #include "../lz4/lz4.h" #include "../lz4/lz4hc.h" namespace dmLZ4 { Result DecompressBuffer(const void* buffer, uint32_t buffer_size, void* decompressed_buffer, uint32_t max_output, int *decompressed_size) { Result r; // When we set an output size larger than 1G (or closer to 2G) lz4 fails for some reason... if(max_output <= DMLZ4_MAX_OUTPUT_SIZE) { *decompressed_size = LZ4_decompress_safe((const char*)buffer, (char *)decompressed_buffer, buffer_size, max_output); if(*decompressed_size < 0) r = dmLZ4::RESULT_OUTBUFFER_TOO_SMALL; else r = dmLZ4::RESULT_OK; } else { *decompressed_size = -1; r = dmLZ4::RESULT_OUTPUT_SIZE_TOO_LARGE; } return r; } Result DecompressBufferFast(const void* buffer, uint32_t buffer_size, void* decompressed_buffer, uint32_t decompressed_size) { Result r; // When we set an output size larger than 1G (or closer to 2G) lz4 fails for some reason... if(decompressed_size <= DMLZ4_MAX_OUTPUT_SIZE) { int result = LZ4_decompress_fast((const char*)buffer, (char *)decompressed_buffer, decompressed_size); if(result < 0) r = dmLZ4::RESULT_OUTBUFFER_TOO_SMALL; else r = dmLZ4::RESULT_OK; } else { r = dmLZ4::RESULT_OUTPUT_SIZE_TOO_LARGE; } return r; } Result CompressBuffer(const void* buffer, uint32_t buffer_size, void *compressed_buffer, int *compressed_size) { *compressed_size = LZ4_compress_HC((const char *)buffer, (char *)compressed_buffer, buffer_size, LZ4_compressBound(buffer_size), 9); Result r; if(*compressed_size == 0) r = dmLZ4::RESULT_COMPRESSION_FAILED; else r = dmLZ4::RESULT_OK; return r; } Result MaxCompressedSize(int uncompressed_size, int *max_compressed_size) { *max_compressed_size = LZ4_compressBound(uncompressed_size); Result r; if(*max_compressed_size == 0) r = dmLZ4::RESULT_INPUT_SIZE_TOO_LARGE; else r = dmLZ4::RESULT_OK; return r; } } extern "C" { DM_DLLEXPORT int LZ4DecompressBuffer(const void* buffer, uint32_t buffer_size, void* decompressed_buffer, uint32_t max_output, int* decompressed_size) { return dmLZ4::DecompressBuffer(buffer, buffer_size, decompressed_buffer, max_output, decompressed_size); } DM_DLLEXPORT int LZ4CompressBuffer(const void* buffer, uint32_t buffer_size, void* compressed_buffer, int* compressed_size) { return dmLZ4::CompressBuffer(buffer, buffer_size, compressed_buffer, compressed_size); } DM_DLLEXPORT int LZ4MaxCompressedSize(int uncompressed_size, int* max_compressed_size) { return dmLZ4::MaxCompressedSize(uncompressed_size, max_compressed_size); } }
3,738
1,296
#include "GUI.h" #include <map> #include <functional> #include <string> #include <set> #define MAX_LOADSTRING 50 #define BORDER_MARGIN 50 #define BORDER_MARGIN_LEFT 150 #define BORDER_MARGIN_BOTTOM 100 #define BORDER_WIDTH 3 #define MARK_AXIS_SIZE 10 #define MARK_AXIS_TEXT_WIDTH 50 WCHAR szTitle[MAX_LOADSTRING] = L"GKS"; WCHAR szWindowClass[MAX_LOADSTRING] = L"MainWindowClass"; static const WCHAR msc_fontName[] = L"Verdana"; static const FLOAT msc_fontSize = 20; LRESULT CALLBACK WndProcG(HWND, UINT, WPARAM, LPARAM); std::map<HWND, GUIForm*> wnd_proc_list; GUIForm::GUIForm(Timetable* t) : m_Timetable(t) { _ASSERT(t); } bool GUIForm::InitD2D(HWND hwnd) { HRESULT hr = D2D1CreateFactory( D2D1_FACTORY_TYPE_SINGLE_THREADED, pD2DFactory.GetAddressOf() ); if (FAILED(hr)) { return false; } hr = DWriteCreateFactory( DWRITE_FACTORY_TYPE_SHARED, __uuidof(m_pDWriteFactory), reinterpret_cast<IUnknown**>(m_pDWriteFactory.GetAddressOf()) ); if (FAILED(hr)) { return false; } hr = m_pDWriteFactory->CreateTextFormat( msc_fontName, NULL, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, msc_fontSize, L"", //locale &m_pTextFormat ); if (FAILED(hr)) { return false; } m_pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER); m_pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER); return InitD2DHWResources(hwnd); } bool GUIForm::InitD2DHWResources(HWND hwnd) { RECT rc; GetClientRect(hwnd, &rc); HRESULT hr = pD2DFactory->CreateHwndRenderTarget( D2D1::RenderTargetProperties(), D2D1::HwndRenderTargetProperties( hwnd, D2D1::SizeU( rc.right - rc.left, rc.bottom - rc.top) ), pRT.GetAddressOf() ); if (FAILED(hr)) { return false; } pRT->CreateSolidColorBrush( D2D1::ColorF(D2D1::ColorF::Black), &pBrushBorder ); D2D1_COLOR_F colors[5]{ D2D1::ColorF(D2D1::ColorF::Orange), D2D1::ColorF(D2D1::ColorF::Red), D2D1::ColorF(D2D1::ColorF::Green), D2D1::ColorF(D2D1::ColorF::Blue), D2D1::ColorF(D2D1::ColorF::Green) }; for (int a = 0; a < 5; a++) { pRT->CreateSolidColorBrush( colors[a], pBrushDetail[a].GetAddressOf() ); } return true; } LRESULT GUIForm::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps); EndPaint(hWnd, &ps); DrawGantasDiagram(); } break; case WM_SIZE: InitD2DHWResources(hWnd); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } } int TimeToPixels(int t, RECT rc, int last_time) { float koef = t; koef /= last_time; koef *= (rc.right - BORDER_MARGIN - BORDER_MARGIN_LEFT); return koef; } void GUIForm::DrawGantasDiagram() { _ASSERT(pRT); RECT rc{ 0 }; GetClientRect(hWnd, &rc); pRT->BeginDraw(); pRT->Clear(D2D1::ColorF(D2D1::ColorF::White)); pRT->DrawLine(D2D1::Point2F(BORDER_MARGIN_LEFT - BORDER_WIDTH / 2, BORDER_MARGIN), D2D1::Point2F(BORDER_MARGIN_LEFT - BORDER_WIDTH / 2, rc.bottom - BORDER_MARGIN_BOTTOM), pBrushBorder.Get(), BORDER_WIDTH); pRT->DrawLine(D2D1::Point2F(BORDER_MARGIN_LEFT, rc.bottom - BORDER_MARGIN_BOTTOM + BORDER_WIDTH / 2), D2D1::Point2F(rc.right - BORDER_MARGIN, rc.bottom - BORDER_MARGIN_BOTTOM + BORDER_WIDTH / 2), pBrushBorder.Get(), BORDER_WIDTH); auto tt = m_Timetable->GetTimetable(); for (int a = 0; a < tt.size(); a++) { std::wstring row_cap = L"Верстат "; wchar_t row_cap_id[2]{ 0 }; _itow_s(a + 1, row_cap_id, 10); row_cap += row_cap_id; pRT->DrawTextW( row_cap.c_str(), wcslen(row_cap.c_str()), m_pTextFormat.Get(), D2D1::RectF(0, (rc.bottom - BORDER_MARGIN_BOTTOM - BORDER_MARGIN) / 3 * a + BORDER_MARGIN, BORDER_MARGIN_LEFT, (rc.bottom - BORDER_MARGIN_BOTTOM - BORDER_MARGIN) / 3 * (a + 1) + BORDER_MARGIN),//(rc.bottom - BORDER_MARGIN_BOTTOM - BORDER_MARGIN) / 3 pBrushBorder.Get() ); } int oper = 0; std::set<int> existing_times; for (auto& i : tt) { for (auto& ps : i) { if (ps.detail != -1) { float x_1 = TimeToPixels(ps.start_time, rc, m_Timetable->GetLastTime()), x_2 = TimeToPixels(ps.start_time + ps.duration, rc, m_Timetable->GetLastTime()); pRT->FillRectangle(D2D1::RectF( BORDER_MARGIN_LEFT + x_1, (rc.bottom - BORDER_MARGIN_BOTTOM - BORDER_MARGIN) / (tt.size()) * oper + BORDER_MARGIN, BORDER_MARGIN_LEFT + x_2, (rc.bottom - BORDER_MARGIN_BOTTOM - BORDER_MARGIN) / (tt.size()) * (oper + 1) + BORDER_MARGIN) , pBrushDetail[ps.detail].Get()); wchar_t det_w[3]{ 0 }; _itow_s(ps.detail + 1, det_w, 10); pRT->DrawTextW(det_w, wcslen(det_w), m_pTextFormat.Get(), D2D1::RectF( BORDER_MARGIN_LEFT + x_1, (rc.bottom - BORDER_MARGIN_BOTTOM - BORDER_MARGIN) / 3 * oper + BORDER_MARGIN, BORDER_MARGIN_LEFT + x_2, (rc.bottom - BORDER_MARGIN_BOTTOM - BORDER_MARGIN) / 3 * (oper + 1) + BORDER_MARGIN) , pBrushBorder.Get()); if (existing_times.find(ps.start_time) == existing_times.end()) { existing_times.insert(ps.start_time); int markX = TimeToPixels(ps.start_time, rc, m_Timetable->GetLastTime()); wchar_t start_time_w[4]{ 0 }; _itow_s(ps.start_time, start_time_w, 10); pRT->DrawLine(D2D1::Point2F(BORDER_MARGIN_LEFT + markX, rc.bottom - BORDER_MARGIN_BOTTOM), D2D1::Point2F(BORDER_MARGIN_LEFT + markX, rc.bottom - BORDER_MARGIN_BOTTOM + MARK_AXIS_SIZE), pBrushBorder.Get(), BORDER_WIDTH); pRT->DrawTextW(start_time_w, wcslen(start_time_w), m_pTextFormat.Get(), D2D1::RectF( BORDER_MARGIN_LEFT + markX - MARK_AXIS_TEXT_WIDTH, rc.bottom - BORDER_MARGIN_BOTTOM + MARK_AXIS_SIZE, BORDER_MARGIN_LEFT + markX + MARK_AXIS_TEXT_WIDTH, rc.bottom ), pBrushBorder.Get()); } } } oper++; } pRT->EndDraw(); } ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEXW wcex{ 0 }; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProcG; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hCursor = LoadCursor(nullptr, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcex.lpszClassName = szWindowClass; return RegisterClassExW(&wcex); } BOOL GUIForm::InitWindow() { hInstance = GetModuleHandle(NULL); MyRegisterClass(hInstance); hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr); wnd_proc_list[hWnd] = this; InitD2D(hWnd); ShowWindow(hWnd, SW_NORMAL); UpdateWindow(hWnd); return true; } void GUIForm::Show() { InitWindow(); MSG msg; while (GetMessage(&msg, nullptr, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } } LRESULT CALLBACK WndProcG(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { return wnd_proc_list[hWnd]->WndProc(hWnd, message, wParam, lParam); }
6,874
3,418
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #define EIGEN_USE_THREADS // See docs in ../ops/spectral_ops.cc. #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/util/env_var.h" #include "tensorflow/core/util/work_sharder.h" #if GOOGLE_CUDA || TENSORFLOW_USE_ROCM #include "tensorflow/core/platform/stream_executor.h" #endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM namespace tensorflow { class FFTBase : public OpKernel { public: explicit FFTBase(OpKernelConstruction* ctx) : OpKernel(ctx) {} void Compute(OpKernelContext* ctx) override { const Tensor& in = ctx->input(0); const TensorShape& input_shape = in.shape(); const int fft_rank = Rank(); OP_REQUIRES( ctx, input_shape.dims() >= fft_rank, errors::InvalidArgument("Input must have rank of at least ", fft_rank, " but got: ", input_shape.DebugString())); Tensor* out; TensorShape output_shape = input_shape; uint64 fft_shape[3] = {0, 0, 0}; // In R2C or C2R mode, we use a second input to specify the FFT length // instead of inferring it from the input shape. if (IsReal()) { const Tensor& fft_length = ctx->input(1); OP_REQUIRES(ctx, fft_length.shape().dims() == 1 && fft_length.shape().dim_size(0) == fft_rank, errors::InvalidArgument("fft_length must have shape [", fft_rank, "]")); auto fft_length_as_vec = fft_length.vec<int32>(); for (int i = 0; i < fft_rank; ++i) { fft_shape[i] = fft_length_as_vec(i); // Each input dimension must have length of at least fft_shape[i]. For // IRFFTs, the inner-most input dimension must have length of at least // fft_shape[i] / 2 + 1. bool inner_most = (i == fft_rank - 1); uint64 min_input_dim_length = !IsForward() && inner_most ? fft_shape[i] / 2 + 1 : fft_shape[i]; auto input_index = input_shape.dims() - fft_rank + i; OP_REQUIRES( ctx, // We pass through empty tensors, so special case them here. input_shape.dim_size(input_index) == 0 || input_shape.dim_size(input_index) >= min_input_dim_length, errors::InvalidArgument( "Input dimension ", input_index, " must have length of at least ", min_input_dim_length, " but got: ", input_shape.dim_size(input_index))); uint64 dim = IsForward() && inner_most && fft_shape[i] != 0 ? fft_shape[i] / 2 + 1 : fft_shape[i]; output_shape.set_dim(output_shape.dims() - fft_rank + i, dim); } } else { for (int i = 0; i < fft_rank; ++i) { fft_shape[i] = output_shape.dim_size(output_shape.dims() - fft_rank + i); } } OP_REQUIRES_OK(ctx, ctx->allocate_output(0, output_shape, &out)); if (input_shape.num_elements() == 0) { return; } DoFFT(ctx, in, fft_shape, out); } protected: virtual int Rank() const = 0; virtual bool IsForward() const = 0; virtual bool IsReal() const = 0; // The function that actually computes the FFT. virtual void DoFFT(OpKernelContext* ctx, const Tensor& in, uint64* fft_shape, Tensor* out) = 0; }; typedef Eigen::ThreadPoolDevice CPUDevice; template <bool Forward, bool _Real, int FFTRank> class FFTCPU : public FFTBase { public: using FFTBase::FFTBase; protected: int Rank() const override { return FFTRank; } bool IsForward() const override { return Forward; } bool IsReal() const override { return _Real; } void DoFFT(OpKernelContext* ctx, const Tensor& in, uint64* fft_shape, Tensor* out) override { // Create the axes (which are always trailing). const auto axes = Eigen::ArrayXi::LinSpaced(FFTRank, 1, FFTRank); auto device = ctx->eigen_device<CPUDevice>(); if (!IsReal()) { // Compute the FFT using Eigen. constexpr auto direction = Forward ? Eigen::FFT_FORWARD : Eigen::FFT_REVERSE; if (in.dtype() == DT_COMPLEX64) { DCHECK_EQ(out->dtype(), DT_COMPLEX64); auto input = Tensor(in).flat_inner_dims<complex64, FFTRank + 1>(); auto output = out->flat_inner_dims<complex64, FFTRank + 1>(); output.device(device) = input.template fft<Eigen::BothParts, direction>(axes); } else { DCHECK_EQ(DT_COMPLEX128, in.dtype()); DCHECK_EQ(DT_COMPLEX128, out->dtype()); auto input = Tensor(in).flat_inner_dims<complex128, FFTRank + 1>(); auto output = out->flat_inner_dims<complex128, FFTRank + 1>(); output.device(device) = input.template fft<Eigen::BothParts, direction>(axes); } } else { if (IsForward()) { auto input = Tensor(in).flat_inner_dims<float, FFTRank + 1>(); const auto input_dims = input.dimensions(); // Slice input to fft_shape on its inner-most dimensions. Eigen::DSizes<Eigen::DenseIndex, FFTRank + 1> input_slice_sizes; input_slice_sizes[0] = input_dims[0]; TensorShape temp_shape{input_dims[0]}; for (int i = 1; i <= FFTRank; ++i) { input_slice_sizes[i] = fft_shape[i - 1]; temp_shape.AddDim(fft_shape[i - 1]); } auto output = out->flat_inner_dims<complex64, FFTRank + 1>(); const Eigen::DSizes<Eigen::DenseIndex, FFTRank + 1> zero_start_indices; // Compute the full FFT using a temporary tensor. Tensor temp; OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<complex64>::v(), temp_shape, &temp)); auto full_fft = temp.flat_inner_dims<complex64, FFTRank + 1>(); full_fft.device(device) = input.slice(zero_start_indices, input_slice_sizes) .template fft<Eigen::BothParts, Eigen::FFT_FORWARD>(axes); // Slice away the negative frequency components. output.device(device) = full_fft.slice(zero_start_indices, output.dimensions()); } else { // Reconstruct the full FFT and take the inverse. auto input = Tensor(in).flat_inner_dims<complex64, FFTRank + 1>(); auto output = out->flat_inner_dims<float, FFTRank + 1>(); const auto input_dims = input.dimensions(); // Calculate the shape of the temporary tensor for the full FFT and the // region we will slice from input given fft_shape. We slice input to // fft_shape on its inner-most dimensions, except the last (which we // slice to fft_shape[-1] / 2 + 1). Eigen::DSizes<Eigen::DenseIndex, FFTRank + 1> input_slice_sizes; input_slice_sizes[0] = input_dims[0]; TensorShape full_fft_shape; full_fft_shape.AddDim(input_dims[0]); for (auto i = 1; i <= FFTRank; i++) { input_slice_sizes[i] = i == FFTRank ? fft_shape[i - 1] / 2 + 1 : fft_shape[i - 1]; full_fft_shape.AddDim(fft_shape[i - 1]); } Tensor temp; OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<complex64>::v(), full_fft_shape, &temp)); auto full_fft = temp.flat_inner_dims<complex64, FFTRank + 1>(); // Calculate the starting point and range of the source of // negative frequency part. auto neg_sizes = input_slice_sizes; neg_sizes[FFTRank] = fft_shape[FFTRank - 1] - input_slice_sizes[FFTRank]; Eigen::DSizes<Eigen::DenseIndex, FFTRank + 1> neg_target_indices; neg_target_indices[FFTRank] = input_slice_sizes[FFTRank]; const Eigen::DSizes<Eigen::DenseIndex, FFTRank + 1> start_indices; Eigen::DSizes<Eigen::DenseIndex, FFTRank + 1> neg_start_indices; neg_start_indices[FFTRank] = 1; full_fft.slice(start_indices, input_slice_sizes).device(device) = input.slice(start_indices, input_slice_sizes); // First, conduct IFFTs on outer dimensions. We save computation (and // avoid touching uninitialized memory) by slicing full_fft to the // subregion we wrote input to. if (FFTRank > 1) { const auto outer_axes = Eigen::ArrayXi::LinSpaced(FFTRank - 1, 1, FFTRank - 1); full_fft.slice(start_indices, input_slice_sizes).device(device) = full_fft.slice(start_indices, input_slice_sizes) .template fft<Eigen::BothParts, Eigen::FFT_REVERSE>( outer_axes); } // Reconstruct the full FFT by appending reversed and conjugated // spectrum as the negative frequency part. Eigen::array<bool, FFTRank + 1> reverse_last_axis; for (auto i = 0; i <= FFTRank; i++) { reverse_last_axis[i] = i == FFTRank; } if (neg_sizes[FFTRank] != 0) { full_fft.slice(neg_target_indices, neg_sizes).device(device) = full_fft.slice(neg_start_indices, neg_sizes) .reverse(reverse_last_axis) .conjugate(); } auto inner_axis = Eigen::array<int, 1>{FFTRank}; output.device(device) = full_fft.template fft<Eigen::RealPart, Eigen::FFT_REVERSE>( inner_axis); } } } }; // Use labels to distinguish between internal and open source versions // of these kernels. #ifdef PLATFORM_GOOGLE #define FFT_LABEL "eigen" #else #define FFT_LABEL "" #endif REGISTER_KERNEL_BUILDER(Name("FFT").Device(DEVICE_CPU).Label(FFT_LABEL), FFTCPU<true, false, 1>); REGISTER_KERNEL_BUILDER(Name("IFFT").Device(DEVICE_CPU).Label(FFT_LABEL), FFTCPU<false, false, 1>); REGISTER_KERNEL_BUILDER(Name("FFT2D").Device(DEVICE_CPU).Label(FFT_LABEL), FFTCPU<true, false, 2>); REGISTER_KERNEL_BUILDER(Name("IFFT2D").Device(DEVICE_CPU).Label(FFT_LABEL), FFTCPU<false, false, 2>); REGISTER_KERNEL_BUILDER(Name("FFT3D").Device(DEVICE_CPU).Label(FFT_LABEL), FFTCPU<true, false, 3>); REGISTER_KERNEL_BUILDER(Name("IFFT3D").Device(DEVICE_CPU).Label(FFT_LABEL), FFTCPU<false, false, 3>); REGISTER_KERNEL_BUILDER(Name("RFFT").Device(DEVICE_CPU).Label(FFT_LABEL), FFTCPU<true, true, 1>); REGISTER_KERNEL_BUILDER(Name("IRFFT").Device(DEVICE_CPU).Label(FFT_LABEL), FFTCPU<false, true, 1>); REGISTER_KERNEL_BUILDER(Name("RFFT2D").Device(DEVICE_CPU).Label(FFT_LABEL), FFTCPU<true, true, 2>); REGISTER_KERNEL_BUILDER(Name("IRFFT2D").Device(DEVICE_CPU).Label(FFT_LABEL), FFTCPU<false, true, 2>); REGISTER_KERNEL_BUILDER(Name("RFFT3D").Device(DEVICE_CPU).Label(FFT_LABEL), FFTCPU<true, true, 3>); REGISTER_KERNEL_BUILDER(Name("IRFFT3D").Device(DEVICE_CPU).Label(FFT_LABEL), FFTCPU<false, true, 3>); #undef FFT_LABEL #if GOOGLE_CUDA || TENSORFLOW_USE_ROCM namespace { template <typename T> se::DeviceMemory<T> AsDeviceMemory(const T* cuda_memory) { se::DeviceMemoryBase wrapped(const_cast<T*>(cuda_memory)); se::DeviceMemory<T> typed(wrapped); return typed; } template <typename T> se::DeviceMemory<T> AsDeviceMemory(const T* cuda_memory, uint64 size) { se::DeviceMemoryBase wrapped(const_cast<T*>(cuda_memory), size * sizeof(T)); se::DeviceMemory<T> typed(wrapped); return typed; } // A class to provide scratch-space allocator for Stream-Executor Cufft // callback. Tensorflow is responsible for releasing the temporary buffers after // the kernel finishes. // TODO(yangzihao): Refactor redundant code in subclasses of ScratchAllocator // into base class. class CufftScratchAllocator : public se::ScratchAllocator { public: ~CufftScratchAllocator() override {} CufftScratchAllocator(int64 memory_limit, OpKernelContext* context) : memory_limit_(memory_limit), total_byte_size_(0), context_(context) {} int64 GetMemoryLimitInBytes(se::Stream* stream) override { return memory_limit_; } se::port::StatusOr<se::DeviceMemory<uint8>> AllocateBytes( se::Stream* stream, int64 byte_size) override { Tensor temporary_memory; if (byte_size > memory_limit_) { return se::port::StatusOr<se::DeviceMemory<uint8>>(); } AllocationAttributes allocation_attr; allocation_attr.no_retry_on_failure = true; Status allocation_status(context_->allocate_temp( DT_UINT8, TensorShape({byte_size}), &temporary_memory, AllocatorAttributes(), allocation_attr)); if (!allocation_status.ok()) { return se::port::StatusOr<se::DeviceMemory<uint8>>(); } // Hold the reference of the allocated tensors until the end of the // allocator. allocated_tensors_.push_back(temporary_memory); total_byte_size_ += byte_size; return se::port::StatusOr<se::DeviceMemory<uint8>>( AsDeviceMemory(temporary_memory.flat<uint8>().data(), temporary_memory.flat<uint8>().size())); } int64 TotalByteSize() { return total_byte_size_; } private: int64 memory_limit_; int64 total_byte_size_; OpKernelContext* context_; std::vector<Tensor> allocated_tensors_; }; } // end namespace int64 GetCufftWorkspaceLimit(const string& envvar_in_mb, int64 default_value_in_bytes) { const char* workspace_limit_in_mb_str = getenv(envvar_in_mb.c_str()); if (workspace_limit_in_mb_str != nullptr && strcmp(workspace_limit_in_mb_str, "") != 0) { int64 scratch_limit_in_mb = -1; Status status = ReadInt64FromEnvVar(envvar_in_mb, default_value_in_bytes, &scratch_limit_in_mb); if (!status.ok()) { LOG(WARNING) << "Invalid value for env-var " << envvar_in_mb << ": " << workspace_limit_in_mb_str; } else { return scratch_limit_in_mb * (1 << 20); } } return default_value_in_bytes; } class FFTGPUBase : public FFTBase { public: using FFTBase::FFTBase; protected: static int64 CufftScratchSize; void DoFFT(OpKernelContext* ctx, const Tensor& in, uint64* fft_shape, Tensor* out) override { auto* stream = ctx->op_device_context()->stream(); OP_REQUIRES(ctx, stream, errors::Internal("No GPU stream available.")); const TensorShape& input_shape = in.shape(); const TensorShape& output_shape = out->shape(); const int fft_rank = Rank(); int batch_size = 1; for (int i = 0; i < input_shape.dims() - fft_rank; ++i) { batch_size *= input_shape.dim_size(i); } uint64 input_embed[3]; const uint64 input_stride = 1; uint64 input_distance = 1; uint64 output_embed[3]; const uint64 output_stride = 1; uint64 output_distance = 1; for (int i = 0; i < fft_rank; ++i) { auto dim_offset = input_shape.dims() - fft_rank + i; input_embed[i] = input_shape.dim_size(dim_offset); input_distance *= input_shape.dim_size(dim_offset); output_embed[i] = output_shape.dim_size(dim_offset); output_distance *= output_shape.dim_size(dim_offset); } constexpr bool kInPlaceFft = false; const bool is_complex128 = in.dtype() == DT_COMPLEX128; // complex128 real FFT is not supported yet. DCHECK(!IsReal() || !is_complex128); const auto kFftType = IsReal() ? (IsForward() ? se::fft::Type::kR2C : se::fft::Type::kC2R) : (IsForward() ? (is_complex128 ? se::fft::Type::kZ2ZForward : se::fft::Type::kC2CForward) : (is_complex128 ? se::fft::Type::kZ2ZInverse : se::fft::Type::kC2CInverse)); CufftScratchAllocator scratch_allocator(CufftScratchSize, ctx); auto plan = stream->parent()->AsFft()->CreateBatchedPlanWithScratchAllocator( stream, fft_rank, fft_shape, input_embed, input_stride, input_distance, output_embed, output_stride, output_distance, kFftType, kInPlaceFft, batch_size, &scratch_allocator); if (IsReal()) { if (IsForward()) { auto src = AsDeviceMemory<float>(in.flat<float>().data()); auto dst = AsDeviceMemory<complex64>(out->flat<complex64>().data()); OP_REQUIRES( ctx, stream->ThenFft(plan.get(), src, &dst).ok(), errors::Internal("fft failed : type=", static_cast<int>(kFftType), " in.shape=", input_shape.DebugString())); } else { auto src = AsDeviceMemory<complex64>(in.flat<complex64>().data()); auto dst = AsDeviceMemory<float>(out->flat<float>().data()); OP_REQUIRES( ctx, stream->ThenFft(plan.get(), src, &dst).ok(), errors::Internal("fft failed : type=", static_cast<int>(kFftType), " in.shape=", input_shape.DebugString())); auto alpha = 1.f / output_distance; OP_REQUIRES( ctx, stream->ThenBlasScal(output_shape.num_elements(), alpha, &dst, 1) .ok(), errors::Internal("BlasScal failed : in.shape=", input_shape.DebugString())); } } else { if (!is_complex128) { DCHECK_EQ(in.dtype(), DT_COMPLEX64); DCHECK_EQ(out->dtype(), DT_COMPLEX64); auto src = AsDeviceMemory<complex64>(in.flat<complex64>().data()); auto dst = AsDeviceMemory<complex64>(out->flat<complex64>().data()); OP_REQUIRES( ctx, stream->ThenFft(plan.get(), src, &dst).ok(), errors::Internal("fft failed : type=", static_cast<int>(kFftType), " in.shape=", input_shape.DebugString())); if (!IsForward()) { float alpha = 1.f / output_distance; OP_REQUIRES( ctx, stream->ThenBlasScal(output_shape.num_elements(), alpha, &dst, 1) .ok(), errors::Internal("BlasScal failed : in.shape=", input_shape.DebugString())); } } else { DCHECK_EQ(in.dtype(), DT_COMPLEX128); DCHECK_EQ(out->dtype(), DT_COMPLEX128); auto src = AsDeviceMemory<complex128>(in.flat<complex128>().data()); auto dst = AsDeviceMemory<complex128>(out->flat<complex128>().data()); OP_REQUIRES( ctx, stream->ThenFft(plan.get(), src, &dst).ok(), errors::Internal("fft failed : type=", static_cast<int>(kFftType), " in.shape=", input_shape.DebugString())); if (!IsForward()) { double alpha = 1.0 / output_distance; OP_REQUIRES( ctx, stream->ThenBlasScal(output_shape.num_elements(), alpha, &dst, 1) .ok(), errors::Internal("BlasScal failed : in.shape=", input_shape.DebugString())); } } } } }; int64 FFTGPUBase::CufftScratchSize = GetCufftWorkspaceLimit( // default value is in bytes despite the name of the environment variable "TF_CUFFT_WORKSPACE_LIMIT_IN_MB", 1LL << 32 // 4GB ); template <bool Forward, bool _Real, int FFTRank> class FFTGPU : public FFTGPUBase { public: static_assert(FFTRank >= 1 && FFTRank <= 3, "Only 1D, 2D and 3D FFTs supported."); explicit FFTGPU(OpKernelConstruction* ctx) : FFTGPUBase(ctx) {} protected: int Rank() const override { return FFTRank; } bool IsForward() const override { return Forward; } bool IsReal() const override { return _Real; } }; REGISTER_KERNEL_BUILDER(Name("FFT").Device(DEVICE_GPU), FFTGPU<true, false, 1>); REGISTER_KERNEL_BUILDER(Name("IFFT").Device(DEVICE_GPU), FFTGPU<false, false, 1>); REGISTER_KERNEL_BUILDER(Name("FFT2D").Device(DEVICE_GPU), FFTGPU<true, false, 2>); REGISTER_KERNEL_BUILDER(Name("IFFT2D").Device(DEVICE_GPU), FFTGPU<false, false, 2>); REGISTER_KERNEL_BUILDER(Name("FFT3D").Device(DEVICE_GPU), FFTGPU<true, false, 3>); REGISTER_KERNEL_BUILDER(Name("IFFT3D").Device(DEVICE_GPU), FFTGPU<false, false, 3>); REGISTER_KERNEL_BUILDER( Name("RFFT").Device(DEVICE_GPU).HostMemory("fft_length"), FFTGPU<true, true, 1>); REGISTER_KERNEL_BUILDER( Name("IRFFT").Device(DEVICE_GPU).HostMemory("fft_length"), FFTGPU<false, true, 1>); REGISTER_KERNEL_BUILDER( Name("RFFT2D").Device(DEVICE_GPU).HostMemory("fft_length"), FFTGPU<true, true, 2>); REGISTER_KERNEL_BUILDER( Name("IRFFT2D").Device(DEVICE_GPU).HostMemory("fft_length"), FFTGPU<false, true, 2>); REGISTER_KERNEL_BUILDER( Name("RFFT3D").Device(DEVICE_GPU).HostMemory("fft_length"), FFTGPU<true, true, 3>); REGISTER_KERNEL_BUILDER( Name("IRFFT3D").Device(DEVICE_GPU).HostMemory("fft_length"), FFTGPU<false, true, 3>); // Deprecated kernels. REGISTER_KERNEL_BUILDER(Name("BatchFFT").Device(DEVICE_GPU), FFTGPU<true, false, 1>); REGISTER_KERNEL_BUILDER(Name("BatchIFFT").Device(DEVICE_GPU), FFTGPU<false, false, 1>); REGISTER_KERNEL_BUILDER(Name("BatchFFT2D").Device(DEVICE_GPU), FFTGPU<true, false, 2>); REGISTER_KERNEL_BUILDER(Name("BatchIFFT2D").Device(DEVICE_GPU), FFTGPU<false, false, 2>); REGISTER_KERNEL_BUILDER(Name("BatchFFT3D").Device(DEVICE_GPU), FFTGPU<true, false, 3>); REGISTER_KERNEL_BUILDER(Name("BatchIFFT3D").Device(DEVICE_GPU), FFTGPU<false, false, 3>); #endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM } // end namespace tensorflow
22,796
8,042
/*========================================================================= Program: Visualization Toolkit Module: vtkQtView.cxx =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2009 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ #include "vtkQtView.h" #include <QApplication> #include <QPixmap> #include <QWidget> #include "vtkObjectFactory.h" //---------------------------------------------------------------------------- vtkQtView::vtkQtView() { } //---------------------------------------------------------------------------- vtkQtView::~vtkQtView() { } //---------------------------------------------------------------------------- void vtkQtView::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } //---------------------------------------------------------------------------- void vtkQtView::ProcessQtEvents() { QApplication::processEvents(); } //---------------------------------------------------------------------------- void vtkQtView::ProcessQtEventsNoUserInput() { QApplication::processEvents(QEventLoop::ExcludeUserInputEvents); } //---------------------------------------------------------------------------- bool vtkQtView::SaveImage(const char* filename) { return this->GetWidget() != 0 ? this->GetWidget()->grab().save(filename) : false; }
1,622
384
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010 Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include <runtime/eval/strict_mode.h> #include <runtime/base/runtime_option.h> namespace HPHP { using namespace Eval; using namespace std; /////////////////////////////////////////////////////////////////////////////// void throw_strict(const ExtendedException &exn, int strict_level_exn) { if (strict_level_exn <= RuntimeOption::StrictLevel) { if (RuntimeOption::StrictFatal) { throw exn; } else { raise_strict_warning(exn.getMessage()); } } } /////////////////////////////////////////////////////////////////////////////// }
1,572
385
#include <dir2/file2.hpp> #include <dir1/file1.hpp> #include <iostream> namespace Namespace2 { void method() { Namespace1::method(); std::cout << "method - 2" << std::endl; } } // namespace Namespace2
213
82
// Copyright (C) 2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include <ngraph/opsets/opset8.hpp> #include <vector> #include <memory> namespace GNAPluginNS { namespace ngraph_util { template <typename T> static bool get_constant_value(const std::shared_ptr<ngraph::opset8::Constant>& constant, std::vector<double>& values) { using A = typename ov::element_type_traits<T::value>::value_type; const auto& v = constant->get_vector<A>(); std::copy(v.begin(), v.end(), std::back_inserter(values)); return true; } static bool get_constant_value(std::tuple<>&&, const std::shared_ptr<ngraph::opset8::Constant>&, std::vector<double>&) { return false; } template<typename T, typename ...Types> static bool get_constant_value(std::tuple<T, Types...>&&, const std::shared_ptr<ngraph::opset8::Constant>& constant, std::vector<double>& values) { return constant->get_element_type() == T::value && get_constant_value<T>(constant, values) || get_constant_value(std::tuple<Types...>(), constant, values); } static bool get_constant_value(const std::shared_ptr<ngraph::opset8::Constant>& constant, std::vector<double>& values) { return get_constant_value(std::tuple<std::integral_constant<ov::element::Type_t, ov::element::i32>, std::integral_constant<ov::element::Type_t, ov::element::i64>, std::integral_constant<ov::element::Type_t, ov::element::u32>, std::integral_constant<ov::element::Type_t, ov::element::u64>, std::integral_constant<ov::element::Type_t, ov::element::f16>, std::integral_constant<ov::element::Type_t, ov::element::f32>, std::integral_constant<ov::element::Type_t, ov::element::f64>>(), constant, values); } static bool get_constant_value(const std::shared_ptr<ngraph::opset8::Constant>& constant, double& value) { std::vector<double> values; if (!get_constant_value(constant, values)) { return false; } if (values.empty() || values.size() > 1) { throw std::runtime_error("The size of values is more than 1."); } value = values[0]; return true; } } // namespace ngraph_util } // namespace GNAPluginNS
2,469
752
/* * Copyright Andrey Semashev 2007 - 2014. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ /*! * \file text_ostream_backend.hpp * \author Andrey Semashev * \date 22.04.2007 * * The header contains implementation of a text output stream sink backend. */ #ifndef BOOST_LOG_SINKS_TEXT_OSTREAM_BACKEND_HPP_INCLUDED_ #define BOOST_LOG_SINKS_TEXT_OSTREAM_BACKEND_HPP_INCLUDED_ #include <ostream> #include <boost/smart_ptr/shared_ptr.hpp> #include <boost/log/detail/config.hpp> #include <boost/log/sinks/basic_sink_backend.hpp> #include <boost/log/sinks/frontend_requirements.hpp> #include <boost/log/detail/header.hpp> #ifdef BOOST_HAS_PRAGMA_ONCE #pragma once #endif namespace boost { BOOST_LOG_OPEN_NAMESPACE namespace sinks { /*! * \brief An implementation of a text output stream logging sink backend * * The sink backend puts formatted log records to one or more text streams. */ template< typename CharT > class basic_text_ostream_backend : public basic_formatted_sink_backend< CharT, combine_requirements< synchronized_feeding, flushing >::type > { //! Base type typedef basic_formatted_sink_backend< CharT, combine_requirements< synchronized_feeding, flushing >::type > base_type; public: //! Character type typedef typename base_type::char_type char_type; //! String type to be used as a message text holder typedef typename base_type::string_type string_type; //! Output stream type typedef std::basic_ostream< char_type > stream_type; private: //! \cond struct implementation; implementation* m_pImpl; //! \endcond public: /*! * Constructor. No streams attached to the constructed backend, auto flush feature disabled. */ BOOST_LOG_API basic_text_ostream_backend(); /*! * Destructor */ BOOST_LOG_API ~basic_text_ostream_backend(); /*! * The method adds a new stream to the sink. * * \param strm Pointer to the stream. Must not be NULL. */ BOOST_LOG_API void add_stream(shared_ptr< stream_type > const& strm); /*! * The method removes a stream from the sink. If the stream is not attached to the sink, * the method has no effect. * * \param strm Pointer to the stream. Must not be NULL. */ BOOST_LOG_API void remove_stream(shared_ptr< stream_type > const& strm); /*! * Sets the flag to automatically flush buffers of all attached streams after each log record */ BOOST_LOG_API void auto_flush(bool f = true); /*! * The method writes the message to the sink */ BOOST_LOG_API void consume(record_view const& rec, string_type const& formatted_message); /*! * The method flushes the associated streams */ BOOST_LOG_API void flush(); }; #ifdef BOOST_LOG_USE_CHAR typedef basic_text_ostream_backend< char > text_ostream_backend; //!< Convenience typedef for narrow-character logging #endif #ifdef BOOST_LOG_USE_WCHAR_T typedef basic_text_ostream_backend< wchar_t > wtext_ostream_backend; //!< Convenience typedef for wide-character logging #endif } // namespace sinks BOOST_LOG_CLOSE_NAMESPACE // namespace log } // namespace boost #include <boost/log/detail/footer.hpp> #endif // BOOST_LOG_SINKS_TEXT_OSTREAM_BACKEND_HPP_INCLUDED_
3,578
1,223
/*********************************************************************************** * Basic bitext alignment algorithm implementations * * * * Authors: Philippe Ferreira De Sousa, Victoriya Kashtanova, Nada Soussi (c) 2017 * ***********************************************************************************/ #include <limits> #include <cmath> #include "dtw.h" using namespace std; float mu(float a, float b) { return abs(a-b); } float dtw(const vector& rec1, const vector& rec2, float freq, threshold) { n = rec1.length; m = rec2.length; tableau tab(n, m); for (int j=0; j<n; j++) { for (int i=0; i<m; i++) { weight(i, j) = numeric_limits<float>::infinity(); } } weight(0, 0) = mu(rec1[0], rec2[0]) tab.ancestor(0, 0) = 0; tab.weight(1, 0) = mu(rec2[0], rec1[0]+rec1[1]); tab.ancestor(1, 0) = 1; tab.weight(0, 1) = mu(rec1[0], rec2[0]+rec2[1]); tab.ancestor(0, 1) = 2; for (int j=1; j<n; j++) { int inf = max(ceil((i-1.)/2.), m-2*(n-i)+1); int sup = min(2*i+2, m-floor((n-i)/2.)); for (int i=inf; i<sup; i++) { float min_val = tab.weight(i-1, j-1)+mu(rec1[i], rec2[j]); int min_ancestor = 0; if (i>=2) { float cost = tab.weight(i-2, j-1)+mu(rec1[i]+rec1[i-1], rec2[j]); if (cost < min_val) { min_val = cost; min_ancestor = 1; } } if (j>=2) { float cost = tab.weight(i-1, j-2)+mu(rec2[j]+rec2[j-1], rec1[i]); if (cost < min_val) { min_val = cost; min_ancestor = 2; } } tab.weight(i, j) = min_val; tab.ancestor(i, j) = min_ancestor; } } if tab.weight(n-1, m-1)/freq <= threshold: backtracking = vector<pair<int,int>>(n-1, m-1); ///////////////////////////////// A convertir / merge while backtracking[-1] != (-1, -1): #print(backtracking[-1]) backtracking.append((warp_ancestor[0][backtracking[-1]], warp_ancestor[1][backtracking[-1]])) backtracking.reverse() print(word1, "|", word2, "(", freq, "):", value) if graph: adjustedrec1 = [sum([rec1[k] for k in range(backtracking[idx-1][0]+1, backtracking[idx][0]+1)]) for idx in range(1, len(backtracking))] adjustedrec2 = [sum([rec2[k] for k in range(backtracking[idx-1][1]+1, backtracking[idx][1]+1)]) for idx in range(1, len(backtracking))] plot(adjustedrec1) plot(adjustedrec2) show() return value, backtracking[:-1] int d_L = tab[(m+1)*(n+1)-1][0]; int k = m, l = n; int* backtrack = new int[m+1+n+1]; int pathLen = 0; while (k != 0 || l != 0) { int valPath = tab[l*(m+1)+k][1]; backtrack[pathLen] = valPath; pathLen++; switch (valPath) { case -1: k--; l--; break; case 0: k--; break; case 1: l--; break; case 2: k--; l--; } } ////////////////////////////////////////////////////////////: } void free_mem(double* a) { delete[] a; }
3,164
1,295
// HashCon.cpp #include "../../../Common/IntToString.h" #include "ConsoleClose.h" #include "HashCon.h" static const wchar_t *kEmptyFileAlias = L"[Content]"; static const char *kScanningMessage = "Scanning"; static HRESULT CheckBreak2() { return NConsoleClose::TestBreakSignal() ? E_ABORT : S_OK; } HRESULT CHashCallbackConsole::CheckBreak() { return CheckBreak2(); } HRESULT CHashCallbackConsole::StartScanning() { if (PrintHeaders && _so) *_so << kScanningMessage << endl; if (NeedPercents()) { _percent.ClearCurState(); _percent.Command = "Scan"; } return CheckBreak2(); } HRESULT CHashCallbackConsole::ScanProgress(const CDirItemsStat &st, const FString &path, bool /* isDir */) { if (NeedPercents()) { _percent.Files = st.NumDirs + st.NumFiles + st.NumAltStreams; _percent.Completed = st.GetTotalBytes(); _percent.FileName = fs2us(path); _percent.Print(); } return CheckBreak2(); } HRESULT CHashCallbackConsole::ScanError(const FString &path, DWORD systemError) { return ScanError_Base(path, systemError); } void Print_DirItemsStat(AString &s, const CDirItemsStat &st); HRESULT CHashCallbackConsole::FinishScanning(const CDirItemsStat &st) { if (NeedPercents()) { _percent.ClosePrint(true); _percent.ClearCurState(); } if (PrintHeaders && _so) { Print_DirItemsStat(_s, st); *_so << _s << endl << endl; } return CheckBreak2(); } HRESULT CHashCallbackConsole::SetNumFiles(UInt64 /* numFiles */) { return CheckBreak2(); } HRESULT CHashCallbackConsole::SetTotal(UInt64 size) { if (NeedPercents()) { _percent.Total = size; _percent.Print(); } return CheckBreak2(); } HRESULT CHashCallbackConsole::SetCompleted(const UInt64 *completeValue) { if (completeValue && NeedPercents()) { _percent.Completed = *completeValue; _percent.Print(); } return CheckBreak2(); } static void AddMinuses(AString &s, unsigned num) { for (unsigned i = 0; i < num; i++) s += '-'; } static void AddSpaces_if_Positive(AString &s, int num) { for (int i = 0; i < num; i++) s.Add_Space(); } static void SetSpacesAndNul(char *s, unsigned num) { for (unsigned i = 0; i < num; i++) s[i] = ' '; s[num] = 0; } static const unsigned kSizeField_Len = 13; static const unsigned kNameField_Len = 12; static const unsigned kHashColumnWidth_Min = 4 * 2; static unsigned GetColumnWidth(unsigned digestSize) { unsigned width = digestSize * 2; return width < kHashColumnWidth_Min ? kHashColumnWidth_Min: width; } void CHashCallbackConsole::PrintSeparatorLine(const CObjectVector<CHasherState> &hashers) { _s.Empty(); for (unsigned i = 0; i < hashers.Size(); i++) { if (i != 0) _s.Add_Space(); const CHasherState &h = hashers[i]; AddMinuses(_s, GetColumnWidth(h.DigestSize)); } if (PrintSize) { _s.Add_Space(); AddMinuses(_s, kSizeField_Len); } if (PrintName) { AddSpacesBeforeName(); AddMinuses(_s, kNameField_Len); } *_so << _s << endl; } HRESULT CHashCallbackConsole::BeforeFirstFile(const CHashBundle &hb) { if (PrintHeaders && _so) { _s.Empty(); ClosePercents_for_so(); FOR_VECTOR (i, hb.Hashers) { if (i != 0) _s.Add_Space(); const CHasherState &h = hb.Hashers[i]; _s += h.Name; AddSpaces_if_Positive(_s, (int)GetColumnWidth(h.DigestSize) - (int)h.Name.Len()); } if (PrintSize) { _s.Add_Space(); const AString s2 = "Size"; AddSpaces_if_Positive(_s, (int)kSizeField_Len - (int)s2.Len()); _s += s2; } if (PrintName) { AddSpacesBeforeName(); _s += "Name"; } *_so << _s << endl; PrintSeparatorLine(hb.Hashers); } return CheckBreak2(); } HRESULT CHashCallbackConsole::OpenFileError(const FString &path, DWORD systemError) { return OpenFileError_Base(path, systemError); } HRESULT CHashCallbackConsole::GetStream(const wchar_t *name, bool /* isFolder */) { _fileName = name; if (NeedPercents()) { if (PrintNameInPercents) { _percent.FileName.Empty(); if (name) _percent.FileName = name; } _percent.Print(); } return CheckBreak2(); } void CHashCallbackConsole::PrintResultLine(UInt64 fileSize, const CObjectVector<CHasherState> &hashers, unsigned digestIndex, bool showHash) { ClosePercents_for_so(); _s.Empty(); FOR_VECTOR (i, hashers) { const CHasherState &h = hashers[i]; char s[k_HashCalc_DigestSize_Max * 2 + 64]; s[0] = 0; if (showHash) AddHashHexToString(s, h.Digests[digestIndex], h.DigestSize); SetSpacesAndNul(s + strlen(s), (int)GetColumnWidth(h.DigestSize) - (int)strlen(s)); if (i != 0) _s.Add_Space(); _s += s; } if (PrintSize) { _s.Add_Space(); char s[kSizeField_Len + 32]; char *p = s; if (showHash) { p = s + kSizeField_Len; ConvertUInt64ToString(fileSize, p); int numSpaces = kSizeField_Len - (int)strlen(p); if (numSpaces > 0) { p -= (unsigned)numSpaces; for (unsigned i = 0; i < (unsigned)numSpaces; i++) p[i] = ' '; } } else SetSpacesAndNul(s, kSizeField_Len); _s += p; } if (PrintName) AddSpacesBeforeName(); *_so << _s; } HRESULT CHashCallbackConsole::SetOperationResult(UInt64 fileSize, const CHashBundle &hb, bool showHash) { if (_so) { PrintResultLine(fileSize, hb.Hashers, k_HashCalc_Index_Current, showHash); if (PrintName) { if (_fileName.IsEmpty()) *_so << kEmptyFileAlias; else *_so << _fileName; } *_so << endl; } if (NeedPercents()) { _percent.Files++; _percent.Print(); } return CheckBreak2(); } static const char * const k_DigestTitles[] = { " : " , " for data: " , " for data and names: " , " for streams and names: " }; static void PrintSum(CStdOutStream &so, const CHasherState &h, unsigned digestIndex) { so << h.Name; { AString temp; AddSpaces_if_Positive(temp, 6 - (int)h.Name.Len()); so << temp; } so << k_DigestTitles[digestIndex]; char s[k_HashCalc_DigestSize_Max * 2 + 64]; s[0] = 0; AddHashHexToString(s, h.Digests[digestIndex], h.DigestSize); so << s << endl; } void PrintHashStat(CStdOutStream &so, const CHashBundle &hb) { FOR_VECTOR (i, hb.Hashers) { const CHasherState &h = hb.Hashers[i]; PrintSum(so, h, k_HashCalc_Index_DataSum); if (hb.NumFiles != 1 || hb.NumDirs != 0) PrintSum(so, h, k_HashCalc_Index_NamesSum); if (hb.NumAltStreams != 0) PrintSum(so, h, k_HashCalc_Index_StreamsSum); so << endl; } } void CHashCallbackConsole::PrintProperty(const char *name, UInt64 value) { char s[32]; s[0] = ':'; s[1] = ' '; ConvertUInt64ToString(value, s + 2); *_so << name << s << endl; } HRESULT CHashCallbackConsole::AfterLastFile(const CHashBundle &hb) { ClosePercents2(); if (PrintHeaders && _so) { PrintSeparatorLine(hb.Hashers); PrintResultLine(hb.FilesSize, hb.Hashers, k_HashCalc_Index_DataSum, true); *_so << endl << endl; if (hb.NumFiles != 1 || hb.NumDirs != 0) { if (hb.NumDirs != 0) PrintProperty("Folders", hb.NumDirs); PrintProperty("Files", hb.NumFiles); } PrintProperty("Size", hb.FilesSize); if (hb.NumAltStreams != 0) { PrintProperty("Alternate streams", hb.NumAltStreams); PrintProperty("Alternate streams size", hb.AltStreamsSize); } *_so << endl; PrintHashStat(*_so, hb); } return S_OK; }
7,640
2,988
#pragma once #include "compilation_pack.hh" #include "refactor_adapter/files_keeper.hh" #include "clang/Tooling/CommonOptionsParser.h" #include <memory> class FilesKeeperForRegressionTests : public FilesKeeper { public: FilesKeeperForRegressionTests( CompilationPack *pack, std::shared_ptr<OptionsAdapter> options_adapter); static std::unique_ptr<FilesKeeperForRegressionTests> create(CompilationPack *pack, std::shared_ptr<OptionsAdapter> options_adapter); bool isOk() override; llvm::Error getError() override; const std::vector<std::string> *getSourcePathList() override; clang::tooling::CompilationDatabase *getCompilations() override; bool isInplace() const override; private: std::unique_ptr<clang::tooling::CompilationDatabase> compilation_database_; CompilationPack *pack_; };
822
252
/* * Copyright (c) 2003-2018, John Wiegley. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of New Artisans LLC nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <system.hh> #include "account.h" #include "post.h" #include "xact.h" namespace ledger { account_t::~account_t() { TRACE_DTOR(account_t); foreach (accounts_map::value_type& pair, accounts) { if (! pair.second->has_flags(ACCOUNT_TEMP) || has_flags(ACCOUNT_TEMP)) { checked_delete(pair.second); } } } account_t * account_t::find_account(const string& acct_name, const bool auto_create) { accounts_map::const_iterator i = accounts.find(acct_name); if (i != accounts.end()) return (*i).second; char buf[8192]; string::size_type sep = acct_name.find(':'); assert(sep < 256|| sep == string::npos); const char * first, * rest; if (sep == string::npos) { first = acct_name.c_str(); rest = NULL; } else { std::strncpy(buf, acct_name.c_str(), sep); buf[sep] = '\0'; first = buf; rest = acct_name.c_str() + sep + 1; } account_t * account; i = accounts.find(first); if (i == accounts.end()) { if (! auto_create) return NULL; account = new account_t(this, first); // An account created within a temporary or generated account is itself // temporary or generated, so that the whole tree has the same status. if (has_flags(ACCOUNT_TEMP)) account->add_flags(ACCOUNT_TEMP); if (has_flags(ACCOUNT_GENERATED)) account->add_flags(ACCOUNT_GENERATED); #if DEBUG_ON std::pair<accounts_map::iterator, bool> result = #endif accounts.insert(accounts_map::value_type(first, account)); #if DEBUG_ON assert(result.second); #endif } else { account = (*i).second; } if (rest) account = account->find_account(rest, auto_create); return account; } namespace { account_t * find_account_re_(account_t * account, const mask_t& regexp) { if (regexp.match(account->fullname())) return account; foreach (accounts_map::value_type& pair, account->accounts) if (account_t * a = find_account_re_(pair.second, regexp)) return a; return NULL; } } account_t * account_t::find_account_re(const string& regexp) { return find_account_re_(this, mask_t(regexp)); } void account_t::add_post(post_t * post) { posts.push_back(post); // Adding a new post changes the possible totals that may have been // computed before. if (xdata_) { xdata_->self_details.gathered = false; xdata_->self_details.calculated = false; xdata_->family_details.gathered = false; xdata_->family_details.calculated = false; if (! xdata_->family_details.total.is_null()) { xdata_->family_details.total = ledger::value_t(); } account_t *ancestor = this; while (ancestor->parent) { ancestor = ancestor->parent; if (ancestor->has_xdata()) { xdata_t &xdata = ancestor->xdata(); xdata.family_details.gathered = false; xdata.family_details.calculated = false; xdata.family_details.total = ledger::value_t(); } } } } void account_t::add_deferred_post(const string& uuid, post_t * post) { if (! deferred_posts) deferred_posts = deferred_posts_map_t(); deferred_posts_map_t::iterator i = deferred_posts->find(uuid); if (i == deferred_posts->end()) { posts_list lst; lst.push_back(post); deferred_posts->insert(deferred_posts_map_t::value_type(uuid, lst)); } else { (*i).second.push_back(post); } } void account_t::apply_deferred_posts() { if (deferred_posts) { foreach (deferred_posts_map_t::value_type& pair, *deferred_posts) { foreach (post_t * post, pair.second) post->account->add_post(post); } deferred_posts = none; } // Also apply in child accounts foreach (const accounts_map::value_type& pair, accounts) pair.second->apply_deferred_posts(); } bool account_t::remove_post(post_t * post) { // It's possible that 'post' wasn't yet in this account, but try to // remove it anyway. This can happen if there is an error during // parsing, when the posting knows what it's account is, but // xact_t::finalize has not yet added that posting to the account. posts.remove(post); post->account = NULL; return true; } string account_t::fullname() const { if (! _fullname.empty()) { return _fullname; } else { const account_t * first = this; string fullname = name; while (first->parent) { first = first->parent; if (! first->name.empty()) fullname = first->name + ":" + fullname; } _fullname = fullname; return fullname; } } string account_t::partial_name(bool flat) const { string pname = name; for (const account_t * acct = parent; acct && acct->parent; acct = acct->parent) { if (! flat) { std::size_t count = acct->children_with_flags(ACCOUNT_EXT_TO_DISPLAY); assert(count > 0); if (count > 1 || acct->has_xflags(ACCOUNT_EXT_TO_DISPLAY)) break; } pname = acct->name + ":" + pname; } return pname; } std::ostream& operator<<(std::ostream& out, const account_t& account) { out << account.fullname(); return out; } namespace { value_t get_partial_name(call_scope_t& args) { return string_value(args.context<account_t>() .partial_name(args.has<bool>(0) && args.get<bool>(0))); } value_t get_account(call_scope_t& args) { // this gets the name account_t& account(args.context<account_t>()); if (args.has<string>(0)) { account_t * acct = account.parent; for (; acct && acct->parent; acct = acct->parent) ; if (args[0].is_string()) return scope_value(acct->find_account(args.get<string>(0), false)); else if (args[0].is_mask()) return scope_value(acct->find_account_re(args.get<mask_t>(0).str())); else return NULL_VALUE; } else if (args.type_context() == value_t::SCOPE) { return scope_value(&account); } else { return string_value(account.fullname()); } } value_t get_account_base(account_t& account) { return string_value(account.name); } value_t get_amount(account_t& account) { return SIMPLIFIED_VALUE_OR_ZERO(account.amount()); } value_t get_total(account_t& account) { return SIMPLIFIED_VALUE_OR_ZERO(account.total()); } value_t get_subcount(account_t& account) { return long(account.self_details().posts_count); } value_t get_count(account_t& account) { return long(account.family_details().posts_count); } value_t get_cost(account_t&) { throw_(calc_error, _("An account does not have a 'cost' value")); return false; } value_t get_depth(account_t& account) { return long(account.depth); } value_t get_note(account_t& account) { return account.note ? string_value(*account.note) : NULL_VALUE; } value_t ignore(account_t&) { return false; } value_t get_true(account_t&) { return true; } value_t get_addr(account_t& account) { return long(&account); } value_t get_depth_parent(account_t& account) { std::size_t depth = 0; for (const account_t * acct = account.parent; acct && acct->parent; acct = acct->parent) { std::size_t count = acct->children_with_flags(ACCOUNT_EXT_TO_DISPLAY); assert(count > 0); if (count > 1 || acct->has_xflags(ACCOUNT_EXT_TO_DISPLAY)) depth++; } return long(depth); } value_t get_depth_spacer(account_t& account) { std::size_t depth = 0; for (const account_t * acct = account.parent; acct && acct->parent; acct = acct->parent) { std::size_t count = acct->children_with_flags(ACCOUNT_EXT_TO_DISPLAY); assert(count > 0); if (count > 1 || acct->has_xflags(ACCOUNT_EXT_TO_DISPLAY)) depth++; } std::ostringstream out; for (std::size_t i = 0; i < depth; i++) out << " "; return string_value(out.str()); } value_t get_latest_cleared(account_t& account) { return account.self_details().latest_cleared_post; } value_t get_earliest(account_t& account) { return account.self_details().earliest_post; } value_t get_earliest_checkin(account_t& account) { return (! account.self_details().earliest_checkin.is_not_a_date_time() ? value_t(account.self_details().earliest_checkin) : NULL_VALUE); } value_t get_latest(account_t& account) { return account.self_details().latest_post; } value_t get_latest_checkout(account_t& account) { return (! account.self_details().latest_checkout.is_not_a_date_time() ? value_t(account.self_details().latest_checkout) : NULL_VALUE); } value_t get_latest_checkout_cleared(account_t& account) { return account.self_details().latest_checkout_cleared; } template <value_t (*Func)(account_t&)> value_t get_wrapper(call_scope_t& args) { return (*Func)(args.context<account_t>()); } value_t get_parent(account_t& account) { return scope_value(account.parent); } value_t fn_any(call_scope_t& args) { account_t& account(args.context<account_t>()); expr_t::ptr_op_t expr(args.get<expr_t::ptr_op_t>(0)); foreach (post_t * p, account.posts) { bind_scope_t bound_scope(args, *p); if (expr->calc(bound_scope, args.locus, args.depth).to_boolean()) return true; } return false; } value_t fn_all(call_scope_t& args) { account_t& account(args.context<account_t>()); expr_t::ptr_op_t expr(args.get<expr_t::ptr_op_t>(0)); foreach (post_t * p, account.posts) { bind_scope_t bound_scope(args, *p); if (! expr->calc(bound_scope, args.locus, args.depth).to_boolean()) return false; } return true; } } expr_t::ptr_op_t account_t::lookup(const symbol_t::kind_t kind, const string& fn_name) { if (kind != symbol_t::FUNCTION) return NULL; switch (fn_name[0]) { case 'a': if (fn_name[1] == '\0' || fn_name == "amount") return WRAP_FUNCTOR(get_wrapper<&get_amount>); else if (fn_name == "account") return WRAP_FUNCTOR(&get_account); else if (fn_name == "account_base") return WRAP_FUNCTOR(get_wrapper<&get_account_base>); else if (fn_name == "addr") return WRAP_FUNCTOR(get_wrapper<&get_addr>); else if (fn_name == "any") return WRAP_FUNCTOR(&fn_any); else if (fn_name == "all") return WRAP_FUNCTOR(&fn_all); break; case 'c': if (fn_name == "count") return WRAP_FUNCTOR(get_wrapper<&get_count>); else if (fn_name == "cost") return WRAP_FUNCTOR(get_wrapper<&get_cost>); break; case 'd': if (fn_name == "depth") return WRAP_FUNCTOR(get_wrapper<&get_depth>); else if (fn_name == "depth_parent") return WRAP_FUNCTOR(get_wrapper<&get_depth_parent>); else if (fn_name == "depth_spacer") return WRAP_FUNCTOR(get_wrapper<&get_depth_spacer>); break; case 'e': if (fn_name == "earliest") return WRAP_FUNCTOR(get_wrapper<&get_earliest>); else if (fn_name == "earliest_checkin") return WRAP_FUNCTOR(get_wrapper<&get_earliest_checkin>); break; case 'i': if (fn_name == "is_account") return WRAP_FUNCTOR(get_wrapper<&get_true>); else if (fn_name == "is_index") return WRAP_FUNCTOR(get_wrapper<&get_subcount>); break; case 'l': if (fn_name[1] == '\0') return WRAP_FUNCTOR(get_wrapper<&get_depth>); else if (fn_name == "latest_cleared") return WRAP_FUNCTOR(get_wrapper<&get_latest_cleared>); else if (fn_name == "latest") return WRAP_FUNCTOR(get_wrapper<&get_latest>); else if (fn_name == "latest_checkout") return WRAP_FUNCTOR(get_wrapper<&get_latest_checkout>); else if (fn_name == "latest_checkout_cleared") return WRAP_FUNCTOR(get_wrapper<&get_latest_checkout_cleared>); break; case 'n': if (fn_name[1] == '\0') return WRAP_FUNCTOR(get_wrapper<&get_subcount>); else if (fn_name == "note") return WRAP_FUNCTOR(get_wrapper<&get_note>); break; case 'p': if (fn_name == "partial_account") return WRAP_FUNCTOR(get_partial_name); else if (fn_name == "parent") return WRAP_FUNCTOR(get_wrapper<&get_parent>); break; case 's': if (fn_name == "subcount") return WRAP_FUNCTOR(get_wrapper<&get_subcount>); break; case 't': if (fn_name == "total") return WRAP_FUNCTOR(get_wrapper<&get_total>); break; case 'u': if (fn_name == "use_direct_amount") return WRAP_FUNCTOR(get_wrapper<&ignore>); break; case 'N': if (fn_name[1] == '\0') return WRAP_FUNCTOR(get_wrapper<&get_count>); break; case 'O': if (fn_name[1] == '\0') return WRAP_FUNCTOR(get_wrapper<&get_total>); break; } return NULL; } bool account_t::valid() const { if (depth > 256) { DEBUG("ledger.validate", "account_t: depth > 256"); return false; } foreach (const accounts_map::value_type& pair, accounts) { if (this == pair.second) { DEBUG("ledger.validate", "account_t: parent refers to itself!"); return false; } if (! pair.second->valid()) { DEBUG("ledger.validate", "account_t: child not valid"); return false; } } return true; } bool account_t::children_with_xdata() const { foreach (const accounts_map::value_type& pair, accounts) if (pair.second->has_xdata() || pair.second->children_with_xdata()) return true; return false; } std::size_t account_t::children_with_flags(xdata_t::flags_t flags) const { std::size_t count = 0; bool grandchildren_visited = false; foreach (const accounts_map::value_type& pair, accounts) if (pair.second->has_xflags(flags) || pair.second->children_with_flags(flags)) count++; // Although no immediately children were visited, if any progeny at all were // visited, it counts as one. if (count == 0 && grandchildren_visited) count = 1; return count; } account_t::xdata_t::details_t& account_t::xdata_t::details_t::operator+=(const details_t& other) { posts_count += other.posts_count; posts_virtuals_count += other.posts_virtuals_count; posts_cleared_count += other.posts_cleared_count; posts_last_7_count += other.posts_last_7_count; posts_last_30_count += other.posts_last_30_count; posts_this_month_count += other.posts_this_month_count; if (! is_valid(earliest_post) || (is_valid(other.earliest_post) && other.earliest_post < earliest_post)) earliest_post = other.earliest_post; if (! is_valid(earliest_cleared_post) || (is_valid(other.earliest_cleared_post) && other.earliest_cleared_post < earliest_cleared_post)) earliest_cleared_post = other.earliest_cleared_post; if (! is_valid(latest_post) || (is_valid(other.latest_post) && other.latest_post > latest_post)) latest_post = other.latest_post; if (! is_valid(latest_cleared_post) || (is_valid(other.latest_cleared_post) && other.latest_cleared_post > latest_cleared_post)) latest_cleared_post = other.latest_cleared_post; filenames.insert(other.filenames.begin(), other.filenames.end()); accounts_referenced.insert(other.accounts_referenced.begin(), other.accounts_referenced.end()); payees_referenced.insert(other.payees_referenced.begin(), other.payees_referenced.end()); return *this; } void account_t::clear_xdata() { xdata_ = none; foreach (accounts_map::value_type& pair, accounts) if (! pair.second->has_flags(ACCOUNT_TEMP)) pair.second->clear_xdata(); } value_t account_t::amount(const optional<expr_t&>& expr) const { if (xdata_ && xdata_->has_flags(ACCOUNT_EXT_VISITED)) { posts_list::const_iterator i; if (xdata_->self_details.last_post) i = *xdata_->self_details.last_post; else i = posts.begin(); for (; i != posts.end(); i++) { if ((*i)->xdata().has_flags(POST_EXT_VISITED)) { if (! (*i)->xdata().has_flags(POST_EXT_CONSIDERED)) { (*i)->add_to_value(xdata_->self_details.total, expr); (*i)->xdata().add_flags(POST_EXT_CONSIDERED); } } xdata_->self_details.last_post = i; } if (xdata_->self_details.last_reported_post) i = *xdata_->self_details.last_reported_post; else i = xdata_->reported_posts.begin(); for (; i != xdata_->reported_posts.end(); i++) { if ((*i)->xdata().has_flags(POST_EXT_VISITED)) { if (! (*i)->xdata().has_flags(POST_EXT_CONSIDERED)) { (*i)->add_to_value(xdata_->self_details.total, expr); (*i)->xdata().add_flags(POST_EXT_CONSIDERED); } } xdata_->self_details.last_reported_post = i; } return xdata_->self_details.total; } else { return NULL_VALUE; } } value_t account_t::total(const optional<expr_t&>& expr) const { if (! (xdata_ && xdata_->family_details.calculated)) { const_cast<account_t&>(*this).xdata().family_details.calculated = true; value_t temp; foreach (const accounts_map::value_type& pair, accounts) { temp = pair.second->total(expr); if (! temp.is_null()) add_or_set_value(xdata_->family_details.total, temp); } temp = amount(expr); if (! temp.is_null()) add_or_set_value(xdata_->family_details.total, temp); } return xdata_->family_details.total; } const account_t::xdata_t::details_t& account_t::self_details(bool gather_all) const { if (! (xdata_ && xdata_->self_details.gathered)) { const_cast<account_t&>(*this).xdata().self_details.gathered = true; foreach (const post_t * post, posts) xdata_->self_details.update(const_cast<post_t&>(*post), gather_all); } return xdata_->self_details; } const account_t::xdata_t::details_t& account_t::family_details(bool gather_all) const { if (! (xdata_ && xdata_->family_details.gathered)) { const_cast<account_t&>(*this).xdata().family_details.gathered = true; foreach (const accounts_map::value_type& pair, accounts) xdata_->family_details += pair.second->family_details(gather_all); xdata_->family_details += self_details(gather_all); } return xdata_->family_details; } void account_t::xdata_t::details_t::update(post_t& post, bool gather_all) { posts_count++; if (post.has_flags(POST_VIRTUAL)) posts_virtuals_count++; if (gather_all && post.pos) filenames.insert(post.pos->pathname); date_t date = post.date(); if (date.year() == CURRENT_DATE().year() && date.month() == CURRENT_DATE().month()) posts_this_month_count++; if ((CURRENT_DATE() - date).days() <= 30) posts_last_30_count++; if ((CURRENT_DATE() - date).days() <= 7) posts_last_7_count++; if (! is_valid(earliest_post) || post.date() < earliest_post) earliest_post = post.date(); if (! is_valid(latest_post) || post.date() > latest_post) latest_post = post.date(); if (post.checkin && (earliest_checkin.is_not_a_date_time() || *post.checkin < earliest_checkin)) earliest_checkin = *post.checkin; if (post.checkout && (latest_checkout.is_not_a_date_time() || *post.checkout > latest_checkout)) { latest_checkout = *post.checkout; latest_checkout_cleared = post.state() == item_t::CLEARED; } if (post.state() == item_t::CLEARED) { posts_cleared_count++; if (! is_valid(earliest_cleared_post) || post.date() < earliest_cleared_post) earliest_cleared_post = post.date(); if (! is_valid(latest_cleared_post) || post.date() > latest_cleared_post) latest_cleared_post = post.date(); } if (gather_all) { accounts_referenced.insert(post.account->fullname()); payees_referenced.insert(post.payee()); } } void put_account(property_tree::ptree& st, const account_t& acct, function<bool(const account_t&)> pred) { if (pred(acct)) { std::ostringstream buf; buf.width(sizeof(unsigned long) * 2); buf.fill('0'); buf << std::hex << reinterpret_cast<unsigned long>(&acct); st.put("<xmlattr>.id", buf.str()); st.put("name", acct.name); st.put("fullname", acct.fullname()); value_t total = acct.amount(); if (! total.is_null()) put_value(st.put("account-amount", ""), total); total = acct.total(); if (! total.is_null()) put_value(st.put("account-total", ""), total); foreach (const accounts_map::value_type& pair, acct.accounts) put_account(st.add("account", ""), *pair.second, pred); } } } // namespace ledger
22,298
8,126
//===- LoopInterchange.cpp - Code to perform loop interchange --------------------===// // // Copyright 2019 The MLIR Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================= // // This file implements loop unrolling. // //===----------------------------------------------------------------------===// #include "mlir/Transforms/Passes.h" #include "mlir/Analysis/LoopAnalysis.h" #include "mlir/Dialect/AffineOps/AffineOps.h" #include "mlir/IR/AffineExpr.h" #include "mlir/IR/AffineMap.h" #include "mlir/IR/Builders.h" #include "mlir/Pass/Pass.h" #include "mlir/Transforms/LoopUtils.h" #include "llvm/ADT/DenseMap.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include <iostream> using namespace mlir; using namespace std; #define DEBUG_TYPE "affine-loop-interchange" static llvm::cl::OptionCategory clOptionsCategory(DEBUG_TYPE " options"); namespace { struct LoopInterchange : public FunctionPass<LoopInterchange> { void runOnFunction() override; /// Unroll this for op. Returns failure if nothing was done. LogicalResult runOnAffineForOp(AffineForOp forOp); }; } // end anonymous namespace void LoopInterchange::runOnFunction() { cout << "In LoopInterchange's runOnFunction()" << endl; // Gathers all innermost loops through a post order pruned walk. struct InnermostLoopGatherer { // Store innermost loops as we walk. std::vector<AffineForOp> loops; void walkPostOrder(FuncOp f) { for (auto &b : f) walkPostOrder(b.begin(), b.end()); } bool walkPostOrder(Block::iterator Start, Block::iterator End) { bool hasInnerLoops = false; // We need to walk all elements since all innermost loops need to be // gathered as opposed to determining whether this list has any inner // loops or not. while (Start != End) hasInnerLoops |= walkPostOrder(&(*Start++)); return hasInnerLoops; } bool walkPostOrder(Operation *opInst) { bool hasInnerLoops = false; for (auto &region : opInst->getRegions()) for (auto &block : region) hasInnerLoops |= walkPostOrder(block.begin(), block.end()); if (isa<AffineForOp>(opInst)) { if (!hasInnerLoops) loops.push_back(cast<AffineForOp>(opInst)); return true; } return hasInnerLoops; } }; { // Store short loops as we walk. std::vector<AffineForOp> loops; getFunction().walk([&](AffineForOp forOp) { loops.push_back(forOp); }); if (loops.size() >= 2) { interchangeLoops(loops.at(1), loops.at(0)); } return; } } /// Unrolls a 'affine.for' op. Returns success if the loop was unrolled, /// failure otherwise. The default unroll factor is 4. LogicalResult LoopInterchange::runOnAffineForOp(AffineForOp forOp) { cout << "In LoopInterchange's runOnAffineForOp()" << endl; return success(); } std::unique_ptr<OpPassBase<FuncOp>> mlir::createLoopInterchangePass() { return std::make_unique<LoopInterchange>(); } static PassRegistration<LoopInterchange> pass("affine-loop-interchange", "Interchange loops");
3,691
1,267
////////////////////////////////////////////////////////////////////////////// // // Copyright (C) Microsoft Corporation. All Rights Reserved. // // File: EffectVariable.inl // Content: D3DX11 Effects Variable reflection template // These templates define the many Effect variable types. // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // Invalid variable forward defines ////////////////////////////////////////////////////////////////////////// struct SEffectInvalidScalarVariable; struct SEffectInvalidVectorVariable; struct SEffectInvalidMatrixVariable; struct SEffectInvalidStringVariable; struct SEffectInvalidClassInstanceVariable; struct SEffectInvalidInterfaceVariable; struct SEffectInvalidShaderResourceVariable; struct SEffectInvalidUnorderedAccessViewVariable; struct SEffectInvalidRenderTargetViewVariable; struct SEffectInvalidDepthStencilViewVariable; struct SEffectInvalidConstantBuffer; struct SEffectInvalidShaderVariable; struct SEffectInvalidBlendVariable; struct SEffectInvalidDepthStencilVariable; struct SEffectInvalidRasterizerVariable; struct SEffectInvalidSamplerVariable; struct SEffectInvalidTechnique; struct SEffectInvalidPass; struct SEffectInvalidType; extern SEffectInvalidScalarVariable g_InvalidScalarVariable; extern SEffectInvalidVectorVariable g_InvalidVectorVariable; extern SEffectInvalidMatrixVariable g_InvalidMatrixVariable; extern SEffectInvalidStringVariable g_InvalidStringVariable; extern SEffectInvalidClassInstanceVariable g_InvalidClassInstanceVariable; extern SEffectInvalidInterfaceVariable g_InvalidInterfaceVariable; extern SEffectInvalidShaderResourceVariable g_InvalidShaderResourceVariable; extern SEffectInvalidUnorderedAccessViewVariable g_InvalidUnorderedAccessViewVariable; extern SEffectInvalidRenderTargetViewVariable g_InvalidRenderTargetViewVariable; extern SEffectInvalidDepthStencilViewVariable g_InvalidDepthStencilViewVariable; extern SEffectInvalidConstantBuffer g_InvalidConstantBuffer; extern SEffectInvalidShaderVariable g_InvalidShaderVariable; extern SEffectInvalidBlendVariable g_InvalidBlendVariable; extern SEffectInvalidDepthStencilVariable g_InvalidDepthStencilVariable; extern SEffectInvalidRasterizerVariable g_InvalidRasterizerVariable; extern SEffectInvalidSamplerVariable g_InvalidSamplerVariable; extern SEffectInvalidTechnique g_InvalidTechnique; extern SEffectInvalidPass g_InvalidPass; extern SEffectInvalidType g_InvalidType; enum ETemplateVarType { ETVT_Bool, ETVT_Int, ETVT_Float }; ////////////////////////////////////////////////////////////////////////// // Invalid effect variable struct definitions ////////////////////////////////////////////////////////////////////////// struct SEffectInvalidType : public ID3DX11EffectType { STDMETHOD_(BOOL, IsValid)() { return FALSE; } STDMETHOD(GetDesc)(D3DX11_EFFECT_TYPE_DESC *pDesc) { return E_FAIL; } STDMETHOD_(ID3DX11EffectType*, GetMemberTypeByIndex)(UINT Index) { return &g_InvalidType; } STDMETHOD_(ID3DX11EffectType*, GetMemberTypeByName)(LPCSTR Name) { return &g_InvalidType; } STDMETHOD_(ID3DX11EffectType*, GetMemberTypeBySemantic)(LPCSTR Semanti) { return &g_InvalidType; } STDMETHOD_(LPCSTR, GetMemberName)(UINT Index) { return NULL; } STDMETHOD_(LPCSTR, GetMemberSemantic)(UINT Index) { return NULL; } }; template<typename IBaseInterface> struct TEffectInvalidVariable : public IBaseInterface { public: STDMETHOD_(BOOL, IsValid)() { return FALSE; } STDMETHOD_(ID3DX11EffectType*, GetType)() { return &g_InvalidType; } STDMETHOD(GetDesc)(D3DX11_EFFECT_VARIABLE_DESC *pDesc) { return E_FAIL; } STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(UINT Index) { return &g_InvalidScalarVariable; } STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(LPCSTR Name) { return &g_InvalidScalarVariable; } STDMETHOD_(ID3DX11EffectVariable*, GetMemberByIndex)(UINT Index) { return &g_InvalidScalarVariable; } STDMETHOD_(ID3DX11EffectVariable*, GetMemberByName)(LPCSTR Name) { return &g_InvalidScalarVariable; } STDMETHOD_(ID3DX11EffectVariable*, GetMemberBySemantic)(LPCSTR Semantic) { return &g_InvalidScalarVariable; } STDMETHOD_(ID3DX11EffectVariable*, GetElement)(UINT Index) { return &g_InvalidScalarVariable; } STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)() { return &g_InvalidConstantBuffer; } STDMETHOD_(ID3DX11EffectScalarVariable*, AsScalar)() { return &g_InvalidScalarVariable; } STDMETHOD_(ID3DX11EffectVectorVariable*, AsVector)() { return &g_InvalidVectorVariable; } STDMETHOD_(ID3DX11EffectMatrixVariable*, AsMatrix)() { return &g_InvalidMatrixVariable; } STDMETHOD_(ID3DX11EffectStringVariable*, AsString)() { return &g_InvalidStringVariable; } STDMETHOD_(ID3DX11EffectClassInstanceVariable*, AsClassInstance)() { return &g_InvalidClassInstanceVariable; } STDMETHOD_(ID3DX11EffectInterfaceVariable*, AsInterface)() { return &g_InvalidInterfaceVariable; } STDMETHOD_(ID3DX11EffectShaderResourceVariable*, AsShaderResource)() { return &g_InvalidShaderResourceVariable; } STDMETHOD_(ID3DX11EffectUnorderedAccessViewVariable*, AsUnorderedAccessView)() { return &g_InvalidUnorderedAccessViewVariable; } STDMETHOD_(ID3DX11EffectRenderTargetViewVariable*, AsRenderTargetView)() { return &g_InvalidRenderTargetViewVariable; } STDMETHOD_(ID3DX11EffectDepthStencilViewVariable*, AsDepthStencilView)() { return &g_InvalidDepthStencilViewVariable; } STDMETHOD_(ID3DX11EffectConstantBuffer*, AsConstantBuffer)() { return &g_InvalidConstantBuffer; } STDMETHOD_(ID3DX11EffectShaderVariable*, AsShader)() { return &g_InvalidShaderVariable; } STDMETHOD_(ID3DX11EffectBlendVariable*, AsBlend)() { return &g_InvalidBlendVariable; } STDMETHOD_(ID3DX11EffectDepthStencilVariable*, AsDepthStencil)() { return &g_InvalidDepthStencilVariable; } STDMETHOD_(ID3DX11EffectRasterizerVariable*, AsRasterizer)() { return &g_InvalidRasterizerVariable; } STDMETHOD_(ID3DX11EffectSamplerVariable*, AsSampler)() { return &g_InvalidSamplerVariable; } STDMETHOD(SetRawValue)(CONST void *pData, UINT Offset, UINT Count) { return E_FAIL; } STDMETHOD(GetRawValue)(void *pData, UINT Offset, UINT Count) { return E_FAIL; } }; struct SEffectInvalidScalarVariable : public TEffectInvalidVariable<ID3DX11EffectScalarVariable> { public: STDMETHOD(SetFloat)(CONST float Value) { return E_FAIL; } STDMETHOD(GetFloat)(float *pValue) { return E_FAIL; } STDMETHOD(SetFloatArray)(CONST float *pData, UINT Offset, UINT Count) { return E_FAIL; } STDMETHOD(GetFloatArray)(float *pData, UINT Offset, UINT Count) { return E_FAIL; } STDMETHOD(SetInt)(CONST int Value) { return E_FAIL; } STDMETHOD(GetInt)(int *pValue) { return E_FAIL; } STDMETHOD(SetIntArray)(CONST int *pData, UINT Offset, UINT Count) { return E_FAIL; } STDMETHOD(GetIntArray)(int *pData, UINT Offset, UINT Count) { return E_FAIL; } STDMETHOD(SetBool)(CONST BOOL Value) { return E_FAIL; } STDMETHOD(GetBool)(BOOL *pValue) { return E_FAIL; } STDMETHOD(SetBoolArray)(CONST BOOL *pData, UINT Offset, UINT Count) { return E_FAIL; } STDMETHOD(GetBoolArray)(BOOL *pData, UINT Offset, UINT Count) { return E_FAIL; } }; struct SEffectInvalidVectorVariable : public TEffectInvalidVariable<ID3DX11EffectVectorVariable> { public: STDMETHOD(SetFloatVector)(CONST float *pData) { return E_FAIL; }; STDMETHOD(SetIntVector)(CONST int *pData) { return E_FAIL; }; STDMETHOD(SetBoolVector)(CONST BOOL *pData) { return E_FAIL; }; STDMETHOD(GetFloatVector)(float *pData) { return E_FAIL; }; STDMETHOD(GetIntVector)(int *pData) { return E_FAIL; }; STDMETHOD(GetBoolVector)(BOOL *pData) { return E_FAIL; }; STDMETHOD(SetBoolVectorArray) (CONST BOOL *pData, UINT Offset, UINT Count) { return E_FAIL; }; STDMETHOD(SetIntVectorArray) (CONST int *pData, UINT Offset, UINT Count) { return E_FAIL; }; STDMETHOD(SetFloatVectorArray)(CONST float *pData, UINT Offset, UINT Count) { return E_FAIL; }; STDMETHOD(GetBoolVectorArray) (BOOL *pData, UINT Offset, UINT Count) { return E_FAIL; }; STDMETHOD(GetIntVectorArray) (int *pData, UINT Offset, UINT Count) { return E_FAIL; }; STDMETHOD(GetFloatVectorArray)(float *pData, UINT Offset, UINT Count) { return E_FAIL; }; }; struct SEffectInvalidMatrixVariable : public TEffectInvalidVariable<ID3DX11EffectMatrixVariable> { public: STDMETHOD(SetMatrix)(CONST float *pData) { return E_FAIL; } STDMETHOD(GetMatrix)(float *pData) { return E_FAIL; } STDMETHOD(SetMatrixArray)(CONST float *pData, UINT Offset, UINT Count) { return E_FAIL; } STDMETHOD(GetMatrixArray)(float *pData, UINT Offset, UINT Count) { return E_FAIL; } STDMETHOD(SetMatrixPointerArray)(CONST float **ppData, UINT Offset, UINT Count) { return E_FAIL; } STDMETHOD(GetMatrixPointerArray)(float **ppData, UINT Offset, UINT Count) { return E_FAIL; } STDMETHOD(SetMatrixTranspose)(CONST float *pData) { return E_FAIL; } STDMETHOD(GetMatrixTranspose)(float *pData) { return E_FAIL; } STDMETHOD(SetMatrixTransposeArray)(CONST float *pData, UINT Offset, UINT Count) { return E_FAIL; } STDMETHOD(GetMatrixTransposeArray)(float *pData, UINT Offset, UINT Count) { return E_FAIL; } STDMETHOD(SetMatrixTransposePointerArray)(CONST float **ppData, UINT Offset, UINT Count) { return E_FAIL; } STDMETHOD(GetMatrixTransposePointerArray)(float **ppData, UINT Offset, UINT Count) { return E_FAIL; } }; struct SEffectInvalidStringVariable : public TEffectInvalidVariable<ID3DX11EffectStringVariable> { public: STDMETHOD(GetString)(LPCSTR *ppString) { return E_FAIL; } STDMETHOD(GetStringArray)(LPCSTR *ppStrings, UINT Offset, UINT Count) { return E_FAIL; } }; struct SEffectInvalidClassInstanceVariable : public TEffectInvalidVariable<ID3DX11EffectClassInstanceVariable> { public: STDMETHOD(GetClassInstance)(ID3D11ClassInstance **ppClassInstance) { return E_FAIL; } }; struct SEffectInvalidInterfaceVariable : public TEffectInvalidVariable<ID3DX11EffectInterfaceVariable> { public: STDMETHOD(SetClassInstance)(ID3DX11EffectClassInstanceVariable *pEffectClassInstance) { return E_FAIL; } STDMETHOD(GetClassInstance)(ID3DX11EffectClassInstanceVariable **ppEffectClassInstance) { return E_FAIL; } }; struct SEffectInvalidShaderResourceVariable : public TEffectInvalidVariable<ID3DX11EffectShaderResourceVariable> { public: STDMETHOD(SetResource)(ID3D11ShaderResourceView *pResource) { return E_FAIL; } STDMETHOD(GetResource)(ID3D11ShaderResourceView **ppResource) { return E_FAIL; } STDMETHOD(SetResourceArray)(ID3D11ShaderResourceView **ppResources, UINT Offset, UINT Count) { return E_FAIL; } STDMETHOD(GetResourceArray)(ID3D11ShaderResourceView **ppResources, UINT Offset, UINT Count) { return E_FAIL; } }; struct SEffectInvalidUnorderedAccessViewVariable : public TEffectInvalidVariable<ID3DX11EffectUnorderedAccessViewVariable> { public: STDMETHOD(SetUnorderedAccessView)(ID3D11UnorderedAccessView *pResource) { return E_FAIL; } STDMETHOD(GetUnorderedAccessView)(ID3D11UnorderedAccessView **ppResource) { return E_FAIL; } STDMETHOD(SetUnorderedAccessViewArray)(ID3D11UnorderedAccessView **ppResources, UINT Offset, UINT Count) { return E_FAIL; } STDMETHOD(GetUnorderedAccessViewArray)(ID3D11UnorderedAccessView **ppResources, UINT Offset, UINT Count) { return E_FAIL; } }; struct SEffectInvalidRenderTargetViewVariable : public TEffectInvalidVariable<ID3DX11EffectRenderTargetViewVariable> { public: STDMETHOD(SetRenderTarget)(ID3D11RenderTargetView *pResource) { return E_FAIL; } STDMETHOD(GetRenderTarget)(ID3D11RenderTargetView **ppResource) { return E_FAIL; } STDMETHOD(SetRenderTargetArray)(ID3D11RenderTargetView **ppResources, UINT Offset, UINT Count) { return E_FAIL; } STDMETHOD(GetRenderTargetArray)(ID3D11RenderTargetView **ppResources, UINT Offset, UINT Count) { return E_FAIL; } }; struct SEffectInvalidDepthStencilViewVariable : public TEffectInvalidVariable<ID3DX11EffectDepthStencilViewVariable> { public: STDMETHOD(SetDepthStencil)(ID3D11DepthStencilView *pResource) { return E_FAIL; } STDMETHOD(GetDepthStencil)(ID3D11DepthStencilView **ppResource) { return E_FAIL; } STDMETHOD(SetDepthStencilArray)(ID3D11DepthStencilView **ppResources, UINT Offset, UINT Count) { return E_FAIL; } STDMETHOD(GetDepthStencilArray)(ID3D11DepthStencilView **ppResources, UINT Offset, UINT Count) { return E_FAIL; } }; struct SEffectInvalidConstantBuffer : public TEffectInvalidVariable<ID3DX11EffectConstantBuffer> { public: STDMETHOD(SetConstantBuffer)(ID3D11Buffer *pConstantBuffer) { return E_FAIL; } STDMETHOD(GetConstantBuffer)(ID3D11Buffer **ppConstantBuffer) { return E_FAIL; } STDMETHOD(UndoSetConstantBuffer)() { return E_FAIL; } STDMETHOD(SetTextureBuffer)(ID3D11ShaderResourceView *pTextureBuffer) { return E_FAIL; } STDMETHOD(GetTextureBuffer)(ID3D11ShaderResourceView **ppTextureBuffer) { return E_FAIL; } STDMETHOD(UndoSetTextureBuffer)() { return E_FAIL; } }; struct SEffectInvalidShaderVariable : public TEffectInvalidVariable<ID3DX11EffectShaderVariable> { public: STDMETHOD(GetShaderDesc)(UINT ShaderIndex, D3DX11_EFFECT_SHADER_DESC *pDesc) { return E_FAIL; } STDMETHOD(GetVertexShader)(UINT ShaderIndex, ID3D11VertexShader **ppVS) { return E_FAIL; } STDMETHOD(GetGeometryShader)(UINT ShaderIndex, ID3D11GeometryShader **ppGS) { return E_FAIL; } STDMETHOD(GetPixelShader)(UINT ShaderIndex, ID3D11PixelShader **ppPS) { return E_FAIL; } STDMETHOD(GetHullShader)(UINT ShaderIndex, ID3D11HullShader **ppPS) { return E_FAIL; } STDMETHOD(GetDomainShader)(UINT ShaderIndex, ID3D11DomainShader **ppPS) { return E_FAIL; } STDMETHOD(GetComputeShader)(UINT ShaderIndex, ID3D11ComputeShader **ppPS) { return E_FAIL; } STDMETHOD(GetInputSignatureElementDesc)(UINT ShaderIndex, UINT Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc) { return E_FAIL; } STDMETHOD(GetOutputSignatureElementDesc)(UINT ShaderIndex, UINT Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc) { return E_FAIL; } STDMETHOD(GetPatchConstantSignatureElementDesc)(UINT ShaderIndex, UINT Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc) { return E_FAIL; } }; struct SEffectInvalidBlendVariable : public TEffectInvalidVariable<ID3DX11EffectBlendVariable> { public: STDMETHOD(GetBlendState)(UINT Index, ID3D11BlendState **ppBlendState) { return E_FAIL; } STDMETHOD(SetBlendState)(UINT Index, ID3D11BlendState *pBlendState) { return E_FAIL; } STDMETHOD(UndoSetBlendState)(UINT Index) { return E_FAIL; } STDMETHOD(GetBackingStore)(UINT Index, D3D11_BLEND_DESC *pBlendDesc) { return E_FAIL; } }; struct SEffectInvalidDepthStencilVariable : public TEffectInvalidVariable<ID3DX11EffectDepthStencilVariable> { public: STDMETHOD(GetDepthStencilState)(UINT Index, ID3D11DepthStencilState **ppDepthStencilState) { return E_FAIL; } STDMETHOD(SetDepthStencilState)(UINT Index, ID3D11DepthStencilState *pDepthStencilState) { return E_FAIL; } STDMETHOD(UndoSetDepthStencilState)(UINT Index) { return E_FAIL; } STDMETHOD(GetBackingStore)(UINT Index, D3D11_DEPTH_STENCIL_DESC *pDepthStencilDesc) { return E_FAIL; } }; struct SEffectInvalidRasterizerVariable : public TEffectInvalidVariable<ID3DX11EffectRasterizerVariable> { public: STDMETHOD(GetRasterizerState)(UINT Index, ID3D11RasterizerState **ppRasterizerState) { return E_FAIL; } STDMETHOD(SetRasterizerState)(UINT Index, ID3D11RasterizerState *pRasterizerState) { return E_FAIL; } STDMETHOD(UndoSetRasterizerState)(UINT Index) { return E_FAIL; } STDMETHOD(GetBackingStore)(UINT Index, D3D11_RASTERIZER_DESC *pRasterizerDesc) { return E_FAIL; } }; struct SEffectInvalidSamplerVariable : public TEffectInvalidVariable<ID3DX11EffectSamplerVariable> { public: STDMETHOD(GetSampler)(UINT Index, ID3D11SamplerState **ppSampler) { return E_FAIL; } STDMETHOD(SetSampler)(UINT Index, ID3D11SamplerState *pSampler) { return E_FAIL; } STDMETHOD(UndoSetSampler)(UINT Index) { return E_FAIL; } STDMETHOD(GetBackingStore)(UINT Index, D3D11_SAMPLER_DESC *pSamplerDesc) { return E_FAIL; } }; struct SEffectInvalidPass : public ID3DX11EffectPass { public: STDMETHOD_(BOOL, IsValid)() { return FALSE; } STDMETHOD(GetDesc)(D3DX11_PASS_DESC *pDesc) { return E_FAIL; } STDMETHOD(GetVertexShaderDesc)(D3DX11_PASS_SHADER_DESC *pDesc) { return E_FAIL; } STDMETHOD(GetGeometryShaderDesc)(D3DX11_PASS_SHADER_DESC *pDesc) { return E_FAIL; } STDMETHOD(GetPixelShaderDesc)(D3DX11_PASS_SHADER_DESC *pDesc) { return E_FAIL; } STDMETHOD(GetHullShaderDesc)(D3DX11_PASS_SHADER_DESC *pDesc) { return E_FAIL; } STDMETHOD(GetDomainShaderDesc)(D3DX11_PASS_SHADER_DESC *pDesc) { return E_FAIL; } STDMETHOD(GetComputeShaderDesc)(D3DX11_PASS_SHADER_DESC *pDesc) { return E_FAIL; } STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(UINT Index) { return &g_InvalidScalarVariable; } STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(LPCSTR Name) { return &g_InvalidScalarVariable; } STDMETHOD(Apply)(UINT Flags, ID3D11DeviceContext* pContext) { return E_FAIL; } STDMETHOD(Commit)(ID3D11DeviceContext* pContext) { return E_FAIL; } STDMETHOD(ComputeStateBlockMask)(D3DX11_STATE_BLOCK_MASK *pStateBlockMask) { return E_FAIL; } }; struct SEffectInvalidTechnique : public ID3DX11EffectTechnique { public: STDMETHOD_(BOOL, IsValid)() { return FALSE; } STDMETHOD(GetDesc)(D3DX11_TECHNIQUE_DESC *pDesc) { return E_FAIL; } STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(UINT Index) { return &g_InvalidScalarVariable; } STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(LPCSTR Name) { return &g_InvalidScalarVariable; } STDMETHOD_(ID3DX11EffectPass*, GetPassByIndex)(UINT Index) { return &g_InvalidPass; } STDMETHOD_(ID3DX11EffectPass*, GetPassByName)(LPCSTR Name) { return &g_InvalidPass; } STDMETHOD(ComputeStateBlockMask)(D3DX11_STATE_BLOCK_MASK *pStateBlockMask) { return E_FAIL; } }; struct SEffectInvalidGroup : public ID3DX11EffectGroup { public: STDMETHOD_(BOOL, IsValid)() { return FALSE; } STDMETHOD(GetDesc)(D3DX11_GROUP_DESC *pDesc) { return E_FAIL; } STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(UINT Index) { return &g_InvalidScalarVariable; } STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(LPCSTR Name) { return &g_InvalidScalarVariable; } STDMETHOD_(ID3DX11EffectTechnique*, GetTechniqueByIndex)(UINT Index) { return &g_InvalidTechnique; } STDMETHOD_(ID3DX11EffectTechnique*, GetTechniqueByName)(LPCSTR Name) { return &g_InvalidTechnique; } }; ////////////////////////////////////////////////////////////////////////// // Helper routines ////////////////////////////////////////////////////////////////////////// // This is an annoying warning that pops up in retail builds because // the code that jumps to "lExit" is conditionally not compiled. // The only alternative is more #ifdefs in every function #pragma warning( disable : 4102 ) // 'label' : unreferenced label #define VERIFYPARAMETER(x) \ { if (!(x)) { DPF(0, "%s: Parameter " #x " was NULL.", pFuncName); \ __BREAK_ON_FAIL; hr = E_INVALIDARG; goto lExit; } } static HRESULT AnnotationInvalidSetCall(LPCSTR pFuncName) { DPF(0, "%s: Annotations are readonly", pFuncName); return D3DERR_INVALIDCALL; } static HRESULT ObjectSetRawValue() { DPF(0, "ID3DX11EffectVariable::SetRawValue: Objects do not support ths call; please use the specific object accessors instead."); return D3DERR_INVALIDCALL; } static HRESULT ObjectGetRawValue() { DPF(0, "ID3DX11EffectVariable::GetRawValue: Objects do not support ths call; please use the specific object accessors instead."); return D3DERR_INVALIDCALL; } ID3DX11EffectConstantBuffer * NoParentCB(); ID3DX11EffectVariable * GetAnnotationByIndexHelper(const char *pClassName, UINT Index, UINT AnnotationCount, SAnnotation *pAnnotations); ID3DX11EffectVariable * GetAnnotationByNameHelper(const char *pClassName, LPCSTR Name, UINT AnnotationCount, SAnnotation *pAnnotations); template<typename SVarType> BOOL GetVariableByIndexHelper(UINT Index, UINT VariableCount, SVarType *pVariables, BYTE *pBaseAddress, SVarType **ppMember, void **ppDataPtr) { LPCSTR pFuncName = "ID3DX11EffectVariable::GetMemberByIndex"; if (Index >= VariableCount) { DPF(0, "%s: Invalid index (%d, total: %d)", pFuncName, Index, VariableCount); return FALSE; } *ppMember = pVariables + Index; *ppDataPtr = pBaseAddress + (*ppMember)->Data.Offset; return TRUE; } template<typename SVarType> BOOL GetVariableByNameHelper(LPCSTR Name, UINT VariableCount, SVarType *pVariables, BYTE *pBaseAddress, SVarType **ppMember, void **ppDataPtr, UINT* pIndex) { LPCSTR pFuncName = "ID3DX11EffectVariable::GetMemberByName"; if (NULL == Name) { DPF(0, "%s: Parameter Name was NULL.", pFuncName); return FALSE; } UINT i; bool bHasSuper = false; for (i = 0; i < VariableCount; ++ i) { *ppMember = pVariables + i; D3DXASSERT(NULL != (*ppMember)->pName); if (strcmp((*ppMember)->pName, Name) == 0) { *ppDataPtr = pBaseAddress + (*ppMember)->Data.Offset; *pIndex = i; return TRUE; } else if (i == 0 && (*ppMember)->pName[0] == '$' && strcmp((*ppMember)->pName, "$super") == 0) { bHasSuper = true; } } if (bHasSuper) { SVarType* pSuper = pVariables; return GetVariableByNameHelper<SVarType>(Name, pSuper->pType->StructType.Members, (SVarType*)pSuper->pType->StructType.pMembers, pBaseAddress + pSuper->Data.Offset, ppMember, ppDataPtr, pIndex); } DPF(0, "%s: Variable [%s] not found", pFuncName, Name); return FALSE; } template<typename SVarType> BOOL GetVariableBySemanticHelper(LPCSTR Semantic, UINT VariableCount, SVarType *pVariables, BYTE *pBaseAddress, SVarType **ppMember, void **ppDataPtr, UINT* pIndex) { LPCSTR pFuncName = "ID3DX11EffectVariable::GetMemberBySemantic"; if (NULL == Semantic) { DPF(0, "%s: Parameter Semantic was NULL.", pFuncName); return FALSE; } UINT i; for (i = 0; i < VariableCount; ++ i) { *ppMember = pVariables + i; if (NULL != (*ppMember)->pSemantic && _stricmp((*ppMember)->pSemantic, Semantic) == 0) { *ppDataPtr = pBaseAddress + (*ppMember)->Data.Offset; *pIndex = i; return TRUE; } } DPF(0, "%s: Variable with semantic [%s] not found", pFuncName, Semantic); return FALSE; } D3DX11INLINE BOOL AreBoundsValid(UINT Offset, UINT Count, CONST void *pData, CONST SType *pType, UINT TotalUnpackedSize) { if (Count == 0) return TRUE; UINT singleElementSize = pType->GetTotalUnpackedSize(TRUE); D3DXASSERT(singleElementSize <= pType->Stride); return ((Offset + Count >= Offset) && ((Offset + Count) < ((UINT)-1) / pType->Stride) && (Count * pType->Stride + (BYTE*)pData >= (BYTE*)pData) && ((Offset + Count - 1) * pType->Stride + singleElementSize <= TotalUnpackedSize)); } // Note that the branches in this code is based on template parameters and will be compiled out template<ETemplateVarType SourceType, ETemplateVarType DestType, typename SRC_TYPE, BOOL ValidatePtr> __forceinline HRESULT CopyScalarValue(SRC_TYPE SrcValue, void *pDest, const char *pFuncName) { HRESULT hr = S_OK; #ifdef _DEBUG if (ValidatePtr) VERIFYPARAMETER(pDest); #endif switch (SourceType) { case ETVT_Bool: switch (DestType) { case ETVT_Bool: *(int*)pDest = (SrcValue != 0) ? -1 : 0; break; case ETVT_Int: *(int*)pDest = SrcValue ? 1 : 0; break; case ETVT_Float: *(float*)pDest = SrcValue ? 1.0f : 0.0f; break; default: D3DXASSERT(0); } break; case ETVT_Int: switch (DestType) { case ETVT_Bool: *(int*)pDest = (SrcValue != 0) ? -1 : 0; break; case ETVT_Int: *(int*)pDest = (int) SrcValue; break; case ETVT_Float: *(float*)pDest = (float)(SrcValue); break; default: D3DXASSERT(0); } break; case ETVT_Float: switch (DestType) { case ETVT_Bool: *(int*)pDest = (SrcValue != 0.0f) ? -1 : 0; break; case ETVT_Int: *(int*)pDest = (int) (SrcValue); break; case ETVT_Float: *(float*)pDest = (float) SrcValue; break; default: D3DXASSERT(0); } break; default: D3DXASSERT(0); } lExit: return S_OK; } template<ETemplateVarType SourceType, ETemplateVarType DestType, typename SRC_TYPE, typename DEST_TYPE> D3DX11INLINE HRESULT SetScalarArray(CONST SRC_TYPE *pSrcValues, DEST_TYPE *pDestValues, UINT Offset, UINT Count, SType *pType, UINT TotalUnpackedSize, const char *pFuncName) { HRESULT hr = S_OK; #ifdef _DEBUG VERIFYPARAMETER(pSrcValues); if (!AreBoundsValid(Offset, Count, pSrcValues, pType, TotalUnpackedSize)) { DPF(0, "%s: Invalid range specified", pFuncName); VH(E_INVALIDARG); } #endif UINT i, j, delta = pType->NumericType.IsPackedArray ? 1 : SType::c_ScalarsPerRegister; pDestValues += Offset * delta; for (i = 0, j = 0; j < Count; i += delta, ++ j) { // pDestValues[i] = (DEST_TYPE)pSrcValues[j]; CopyScalarValue<SourceType, DestType, SRC_TYPE, FALSE>(pSrcValues[j], &pDestValues[i], "SetScalarArray"); } lExit: return hr; } template<ETemplateVarType SourceType, ETemplateVarType DestType, typename SRC_TYPE, typename DEST_TYPE> D3DX11INLINE HRESULT GetScalarArray(SRC_TYPE *pSrcValues, DEST_TYPE *pDestValues, UINT Offset, UINT Count, SType *pType, UINT TotalUnpackedSize, const char *pFuncName) { HRESULT hr = S_OK; #ifdef _DEBUG VERIFYPARAMETER(pDestValues); if (!AreBoundsValid(Offset, Count, pDestValues, pType, TotalUnpackedSize)) { DPF(0, "%s: Invalid range specified", pFuncName); VH(E_INVALIDARG); } #endif UINT i, j, delta = pType->NumericType.IsPackedArray ? 1 : SType::c_ScalarsPerRegister; pSrcValues += Offset * delta; for (i = 0, j = 0; j < Count; i += delta, ++ j) { // pDestValues[j] = (DEST_TYPE)pSrcValues[i]; CopyScalarValue<SourceType, DestType, SRC_TYPE, FALSE>(pSrcValues[i], &pDestValues[j], "GetScalarArray"); } lExit: return hr; } ////////////////////////////////////////////////////////////////////////// // TVariable - implements type casting and member/element retrieval ////////////////////////////////////////////////////////////////////////// // requires that IBaseInterface contain SVariable's fields and support ID3DX11EffectVariable template<typename IBaseInterface> struct TVariable : public IBaseInterface { STDMETHOD_(BOOL, IsValid)() { return TRUE; } STDMETHOD_(ID3DX11EffectVariable*, GetMemberByIndex)(UINT Index) { SVariable *pMember; UDataPointer dataPtr; TTopLevelVariable<ID3DX11EffectVariable> *pTopLevelEntity = GetTopLevelEntity(); if (((ID3DX11Effect*)pTopLevelEntity->pEffect)->IsOptimized()) { DPF(0, "ID3DX11EffectVariable::GetMemberByIndex: Cannot get members; effect has been Optimize()'ed"); return &g_InvalidScalarVariable; } if (pType->VarType != EVT_Struct) { DPF(0, "ID3DX11EffectVariable::GetMemberByIndex: Variable is not a structure"); return &g_InvalidScalarVariable; } if (!GetVariableByIndexHelper<SVariable>(Index, pType->StructType.Members, pType->StructType.pMembers, Data.pNumeric, &pMember, &dataPtr.pGeneric)) { return &g_InvalidScalarVariable; } return pTopLevelEntity->pEffect->CreatePooledVariableMemberInterface(pTopLevelEntity, pMember, dataPtr, FALSE, Index); } STDMETHOD_(ID3DX11EffectVariable*, GetMemberByName)(LPCSTR Name) { SVariable *pMember; UDataPointer dataPtr; UINT index; TTopLevelVariable<ID3DX11EffectVariable> *pTopLevelEntity = GetTopLevelEntity(); if (pTopLevelEntity->pEffect->IsOptimized()) { DPF(0, "ID3DX11EffectVariable::GetMemberByName: Cannot get members; effect has been Optimize()'ed"); return &g_InvalidScalarVariable; } if (pType->VarType != EVT_Struct) { DPF(0, "ID3DX11EffectVariable::GetMemberByName: Variable is not a structure"); return &g_InvalidScalarVariable; } if (!GetVariableByNameHelper<SVariable>(Name, pType->StructType.Members, pType->StructType.pMembers, Data.pNumeric, &pMember, &dataPtr.pGeneric, &index)) { return &g_InvalidScalarVariable; } return pTopLevelEntity->pEffect->CreatePooledVariableMemberInterface(pTopLevelEntity, pMember, dataPtr, FALSE, index); } STDMETHOD_(ID3DX11EffectVariable*, GetMemberBySemantic)(LPCSTR Semantic) { SVariable *pMember; UDataPointer dataPtr; UINT index; TTopLevelVariable<ID3DX11EffectVariable> *pTopLevelEntity = GetTopLevelEntity(); if (pTopLevelEntity->pEffect->IsOptimized()) { DPF(0, "ID3DX11EffectVariable::GetMemberBySemantic: Cannot get members; effect has been Optimize()'ed"); return &g_InvalidScalarVariable; } if (pType->VarType != EVT_Struct) { DPF(0, "ID3DX11EffectVariable::GetMemberBySemantic: Variable is not a structure"); return &g_InvalidScalarVariable; } if (!GetVariableBySemanticHelper<SVariable>(Semantic, pType->StructType.Members, pType->StructType.pMembers, Data.pNumeric, &pMember, &dataPtr.pGeneric, &index)) { return &g_InvalidScalarVariable; } return pTopLevelEntity->pEffect->CreatePooledVariableMemberInterface(pTopLevelEntity, pMember, dataPtr, FALSE, index); } STDMETHOD_(ID3DX11EffectVariable*, GetElement)(UINT Index) { LPCSTR pFuncName = "ID3DX11EffectVariable::GetElement"; TTopLevelVariable<ID3DX11EffectVariable> *pTopLevelEntity = GetTopLevelEntity(); UDataPointer dataPtr; if (pTopLevelEntity->pEffect->IsOptimized()) { DPF(0, "ID3DX11EffectVariable::GetElement: Cannot get element; effect has been Optimize()'ed"); return &g_InvalidScalarVariable; } if (!IsArray()) { DPF(0, "%s: This interface does not refer to an array", pFuncName); return &g_InvalidScalarVariable; } if (Index >= pType->Elements) { DPF(0, "%s: Invalid element index (%d, total: %d)", pFuncName, Index, pType->Elements); return &g_InvalidScalarVariable; } if (pType->BelongsInConstantBuffer()) { dataPtr.pGeneric = Data.pNumeric + pType->Stride * Index; } else { dataPtr.pGeneric = GetBlockByIndex(pType->VarType, pType->ObjectType, Data.pGeneric, Index); if (NULL == dataPtr.pGeneric) { DPF(0, "%s: Internal error", pFuncName); return &g_InvalidScalarVariable; } } return pTopLevelEntity->pEffect->CreatePooledVariableMemberInterface(pTopLevelEntity, (SVariable *) this, dataPtr, TRUE, Index); } STDMETHOD_(ID3DX11EffectScalarVariable*, AsScalar)() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsScalar"; if (pType->VarType != EVT_Numeric || pType->NumericType.NumericLayout != ENL_Scalar) { DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidScalarVariable; } return (ID3DX11EffectScalarVariable *) this; } STDMETHOD_(ID3DX11EffectVectorVariable*, AsVector)() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsVector"; if (pType->VarType != EVT_Numeric || pType->NumericType.NumericLayout != ENL_Vector) { DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidVectorVariable; } return (ID3DX11EffectVectorVariable *) this; } STDMETHOD_(ID3DX11EffectMatrixVariable*, AsMatrix)() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsMatrix"; if (pType->VarType != EVT_Numeric || pType->NumericType.NumericLayout != ENL_Matrix) { DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidMatrixVariable; } return (ID3DX11EffectMatrixVariable *) this; } STDMETHOD_(ID3DX11EffectStringVariable*, AsString)() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsString"; if (!pType->IsObjectType(EOT_String)) { DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidStringVariable; } return (ID3DX11EffectStringVariable *) this; } STDMETHOD_(ID3DX11EffectClassInstanceVariable*, AsClassInstance)() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsClassInstance"; if (!pType->IsClassInstance() ) { DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidClassInstanceVariable; } else if( pMemberData == NULL ) { DPF(0, "%s: Non-global class instance variables (members of structs or classes) and class instances " "inside tbuffers are not supported.", pFuncName ); return &g_InvalidClassInstanceVariable; } return (ID3DX11EffectClassInstanceVariable *) this; } STDMETHOD_(ID3DX11EffectInterfaceVariable*, AsInterface)() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsInterface"; if (!pType->IsInterface()) { DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidInterfaceVariable; } return (ID3DX11EffectInterfaceVariable *) this; } STDMETHOD_(ID3DX11EffectShaderResourceVariable*, AsShaderResource)() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsShaderResource"; if (!pType->IsShaderResource()) { DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidShaderResourceVariable; } return (ID3DX11EffectShaderResourceVariable *) this; } STDMETHOD_(ID3DX11EffectUnorderedAccessViewVariable*, AsUnorderedAccessView)() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsUnorderedAccessView"; if (!pType->IsUnorderedAccessView()) { DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidUnorderedAccessViewVariable; } return (ID3DX11EffectUnorderedAccessViewVariable *) this; } STDMETHOD_(ID3DX11EffectRenderTargetViewVariable*, AsRenderTargetView)() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsRenderTargetView"; if (!pType->IsRenderTargetView()) { DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidRenderTargetViewVariable; } return (ID3DX11EffectRenderTargetViewVariable *) this; } STDMETHOD_(ID3DX11EffectDepthStencilViewVariable*, AsDepthStencilView)() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsDepthStencilView"; if (!pType->IsDepthStencilView()) { DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidDepthStencilViewVariable; } return (ID3DX11EffectDepthStencilViewVariable *) this; } STDMETHOD_(ID3DX11EffectConstantBuffer*, AsConstantBuffer)() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsConstantBuffer"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidConstantBuffer; } STDMETHOD_(ID3DX11EffectShaderVariable*, AsShader)() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsShader"; if (!pType->IsShader()) { DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidShaderVariable; } return (ID3DX11EffectShaderVariable *) this; } STDMETHOD_(ID3DX11EffectBlendVariable*, AsBlend)() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsBlend"; if (!pType->IsObjectType(EOT_Blend)) { DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidBlendVariable; } return (ID3DX11EffectBlendVariable *) this; } STDMETHOD_(ID3DX11EffectDepthStencilVariable*, AsDepthStencil)() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsDepthStencil"; if (!pType->IsObjectType(EOT_DepthStencil)) { DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidDepthStencilVariable; } return (ID3DX11EffectDepthStencilVariable *) this; } STDMETHOD_(ID3DX11EffectRasterizerVariable*, AsRasterizer)() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsRasterizer"; if (!pType->IsObjectType(EOT_Rasterizer)) { DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidRasterizerVariable; } return (ID3DX11EffectRasterizerVariable *) this; } STDMETHOD_(ID3DX11EffectSamplerVariable*, AsSampler)() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsSampler"; if (!pType->IsSampler()) { DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidSamplerVariable; } return (ID3DX11EffectSamplerVariable *) this; } // Numeric variables should override this STDMETHOD(SetRawValue)(CONST void *pData, UINT Offset, UINT Count) { return ObjectSetRawValue(); } STDMETHOD(GetRawValue)(void *pData, UINT Offset, UINT Count) { return ObjectGetRawValue(); } }; ////////////////////////////////////////////////////////////////////////// // TTopLevelVariable - functionality for annotations and global variables ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TTopLevelVariable : public SVariable, public IBaseInterface { // Required to create member/element variable interfaces CEffect *pEffect; CEffect* GetEffect() { return pEffect; } TTopLevelVariable() { pEffect = NULL; } UINT GetTotalUnpackedSize() { return ((SType*)pType)->GetTotalUnpackedSize(FALSE); } STDMETHOD_(ID3DX11EffectType*, GetType)() { return (ID3DX11EffectType*)(SType*)pType; } TTopLevelVariable<ID3DX11EffectVariable> * GetTopLevelEntity() { return (TTopLevelVariable<ID3DX11EffectVariable> *)this; } BOOL IsArray() { return (pType->Elements > 0); } }; ////////////////////////////////////////////////////////////////////////// // TMember - functionality for structure/array members of other variables ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TMember : public SVariable, public IBaseInterface { // Indicates that this is a single element of a containing array UINT IsSingleElement : 1; // Required to create member/element variable interfaces TTopLevelVariable<ID3DX11EffectVariable> *pTopLevelEntity; TMember() { IsSingleElement = FALSE; pTopLevelEntity = NULL; } CEffect* GetEffect() { return pTopLevelEntity->pEffect; } UINT GetTotalUnpackedSize() { return pType->GetTotalUnpackedSize(IsSingleElement); } STDMETHOD_(ID3DX11EffectType*, GetType)() { if (IsSingleElement) { return pTopLevelEntity->pEffect->CreatePooledSingleElementTypeInterface( pType ); } else { return (ID3DX11EffectType*) pType; } } STDMETHOD(GetDesc)(D3DX11_EFFECT_VARIABLE_DESC *pDesc) { HRESULT hr = S_OK; LPCSTR pFuncName = "ID3DX11EffectVariable::GetDesc"; VERIFYPARAMETER(pDesc != NULL); pDesc->Name = pName; pDesc->Semantic = pSemantic; pDesc->Flags = 0; if (pTopLevelEntity->pEffect->IsReflectionData(pTopLevelEntity)) { // Is part of an annotation D3DXASSERT(pTopLevelEntity->pEffect->IsReflectionData(Data.pGeneric)); pDesc->Annotations = 0; pDesc->BufferOffset = 0; pDesc->Flags |= D3DX11_EFFECT_VARIABLE_ANNOTATION; } else { // Is part of a global variable D3DXASSERT(pTopLevelEntity->pEffect->IsRuntimeData(pTopLevelEntity)); if (!pTopLevelEntity->pType->IsObjectType(EOT_String)) { // strings are funny; their data is reflection data, so ignore those D3DXASSERT(pTopLevelEntity->pEffect->IsRuntimeData(Data.pGeneric)); } pDesc->Annotations = ((TGlobalVariable<ID3DX11Effect>*)pTopLevelEntity)->AnnotationCount; SConstantBuffer *pCB = ((TGlobalVariable<ID3DX11Effect>*)pTopLevelEntity)->pCB; if (pType->BelongsInConstantBuffer()) { D3DXASSERT(pCB != NULL); UINT_PTR offset = Data.pNumeric - pCB->pBackingStore; D3DXASSERT(offset == (UINT)offset); pDesc->BufferOffset = (UINT)offset; D3DXASSERT(pDesc->BufferOffset >= 0 && pDesc->BufferOffset + GetTotalUnpackedSize() <= pCB->Size); } else { D3DXASSERT(pCB == NULL); pDesc->BufferOffset = 0; } } lExit: return hr; } TTopLevelVariable<ID3DX11EffectVariable> * GetTopLevelEntity() { return pTopLevelEntity; } BOOL IsArray() { return (pType->Elements > 0 && !IsSingleElement); } STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(UINT Index) { return pTopLevelEntity->GetAnnotationByIndex(Index); } STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(LPCSTR Name) { return pTopLevelEntity->GetAnnotationByName(Name); } STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)() { return pTopLevelEntity->GetParentConstantBuffer(); } // Annotations should never be able to go down this codepath void DirtyVariable() { // make sure to call the global variable's version of dirty variable ((TGlobalVariable<ID3DX11EffectVariable>*)pTopLevelEntity)->DirtyVariable(); } }; ////////////////////////////////////////////////////////////////////////// // TAnnotation - functionality for top level annotations ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TAnnotation : public TVariable<TTopLevelVariable<IBaseInterface> > { STDMETHOD(GetDesc)(D3DX11_EFFECT_VARIABLE_DESC *pDesc) { HRESULT hr = S_OK; LPCSTR pFuncName = "ID3DX11EffectVariable::GetDesc"; VERIFYPARAMETER(pDesc != NULL); pDesc->Name = pName; pDesc->Semantic = pSemantic; pDesc->Flags = D3DX11_EFFECT_VARIABLE_ANNOTATION; pDesc->Annotations = 0; pDesc->BufferOffset = 0; pDesc->ExplicitBindPoint = 0; lExit: return hr; } STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(UINT Index) { LPCSTR pFuncName = "ID3DX11EffectVariable::GetAnnotationByIndex"; DPF(0, "%s: Only variables may have annotations", pFuncName); return &g_InvalidScalarVariable; } STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(LPCSTR Name) { LPCSTR pFuncName = "ID3DX11EffectVariable::GetAnnotationByName"; DPF(0, "%s: Only variables may have annotations", pFuncName); return &g_InvalidScalarVariable; } STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)() { return NoParentCB(); } void DirtyVariable() { D3DXASSERT(0); } }; ////////////////////////////////////////////////////////////////////////// // TGlobalVariable - functionality for top level global variables ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TGlobalVariable : public TVariable<TTopLevelVariable<IBaseInterface> > { Timer LastModifiedTime; // if numeric, pointer to the constant buffer where this variable lives SConstantBuffer *pCB; UINT AnnotationCount; SAnnotation *pAnnotations; TGlobalVariable() { LastModifiedTime = 0; pCB = NULL; AnnotationCount = 0; pAnnotations = NULL; } STDMETHOD(GetDesc)(D3DX11_EFFECT_VARIABLE_DESC *pDesc) { HRESULT hr = S_OK; LPCSTR pFuncName = "ID3DX11EffectVariable::GetDesc"; VERIFYPARAMETER(pDesc != NULL); pDesc->Name = pName; pDesc->Semantic = pSemantic; pDesc->Flags = 0; pDesc->Annotations = AnnotationCount; if (pType->BelongsInConstantBuffer()) { D3DXASSERT(pCB != NULL); UINT_PTR offset = Data.pNumeric - pCB->pBackingStore; D3DXASSERT(offset == (UINT)offset); pDesc->BufferOffset = (UINT)offset; D3DXASSERT(pDesc->BufferOffset >= 0 && pDesc->BufferOffset + GetTotalUnpackedSize() <= pCB->Size ); } else { D3DXASSERT(pCB == NULL); pDesc->BufferOffset = 0; } if (ExplicitBindPoint != -1) { pDesc->ExplicitBindPoint = ExplicitBindPoint; pDesc->Flags |= D3DX11_EFFECT_VARIABLE_EXPLICIT_BIND_POINT; } else { pDesc->ExplicitBindPoint = 0; } lExit: return hr; } // these are all well defined for global vars STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(UINT Index) { return GetAnnotationByIndexHelper("ID3DX11EffectVariable", Index, AnnotationCount, pAnnotations); } STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(LPCSTR Name) { return GetAnnotationByNameHelper("ID3DX11EffectVariable", Name, AnnotationCount, pAnnotations); } STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)() { if (NULL != pCB) { D3DXASSERT(pType->BelongsInConstantBuffer()); return (ID3DX11EffectConstantBuffer*)pCB; } else { D3DXASSERT(!pType->BelongsInConstantBuffer()); return &g_InvalidConstantBuffer; } } D3DX11INLINE void DirtyVariable() { D3DXASSERT(NULL != pCB); pCB->IsDirty = TRUE; LastModifiedTime = pEffect->GetCurrentTime(); } }; ////////////////////////////////////////////////////////////////////////// // TNumericVariable - implements raw set/get functionality ////////////////////////////////////////////////////////////////////////// // IMPORTANT NOTE: All of these numeric & object aspect classes MUST NOT // add data members to the base variable classes. Otherwise type sizes // will disagree between object & numeric variables and we cannot eaily // create arrays of global variables using SGlobalVariable // Requires that IBaseInterface have SVariable's members, GetTotalUnpackedSize() and DirtyVariable() template<typename IBaseInterface, BOOL IsAnnotation> struct TNumericVariable : public IBaseInterface { STDMETHOD(SetRawValue)(CONST void *pData, UINT ByteOffset, UINT ByteCount) { if (IsAnnotation) { return AnnotationInvalidSetCall("ID3DX11EffectVariable::SetRawValue"); } else { HRESULT hr = S_OK; #ifdef _DEBUG LPCSTR pFuncName = "ID3DX11EffectVariable::SetRawValue"; VERIFYPARAMETER(pData); if ((ByteOffset + ByteCount < ByteOffset) || (ByteCount + (BYTE*)pData < (BYTE*)pData) || ((ByteOffset + ByteCount) > GetTotalUnpackedSize())) { // overflow of some kind DPF(0, "%s: Invalid range specified", pFuncName); VH(E_INVALIDARG); } #endif DirtyVariable(); memcpy(Data.pNumeric + ByteOffset, pData, ByteCount); lExit: return hr; } } STDMETHOD(GetRawValue)(__out_bcount(ByteCount) void *pData, UINT ByteOffset, UINT ByteCount) { HRESULT hr = S_OK; #ifdef _DEBUG LPCSTR pFuncName = "ID3DX11EffectVariable::GetRawValue"; VERIFYPARAMETER(pData); if ((ByteOffset + ByteCount < ByteOffset) || (ByteCount + (BYTE*)pData < (BYTE*)pData) || ((ByteOffset + ByteCount) > GetTotalUnpackedSize())) { // overflow of some kind DPF(0, "%s: Invalid range specified", pFuncName); VH(E_INVALIDARG); } #endif memcpy(pData, Data.pNumeric + ByteOffset, ByteCount); lExit: return hr; } }; ////////////////////////////////////////////////////////////////////////// // ID3DX11EffectScalarVariable (TFloatScalarVariable implementation) ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface, BOOL IsAnnotation> struct TFloatScalarVariable : public TNumericVariable<IBaseInterface, IsAnnotation> { STDMETHOD(SetFloat)(CONST float Value); STDMETHOD(GetFloat)(float *pValue); STDMETHOD(SetFloatArray)(CONST float *pData, UINT Offset, UINT Count); STDMETHOD(GetFloatArray)(float *pData, UINT Offset, UINT Count); STDMETHOD(SetInt)(CONST int Value); STDMETHOD(GetInt)(int *pValue); STDMETHOD(SetIntArray)(CONST int *pData, UINT Offset, UINT Count); STDMETHOD(GetIntArray)(int *pData, UINT Offset, UINT Count); STDMETHOD(SetBool)(CONST BOOL Value); STDMETHOD(GetBool)(BOOL *pValue); STDMETHOD(SetBoolArray)(CONST BOOL *pData, UINT Offset, UINT Count); STDMETHOD(GetBoolArray)(BOOL *pData, UINT Offset, UINT Count); }; template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::SetFloat(float Value) { LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetFloat"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return CopyScalarValue<ETVT_Float, ETVT_Float, float, FALSE>(Value, Data.pNumericFloat, pFuncName); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::GetFloat(float *pValue) { return CopyScalarValue<ETVT_Float, ETVT_Float, float, TRUE>(*Data.pNumericFloat, pValue, "ID3DX11EffectScalarVariable::GetFloat"); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::SetFloatArray(CONST float *pData, UINT Offset, UINT Count) { LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetFloatArray"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return SetScalarArray<ETVT_Float, ETVT_Float, float, float>(pData, Data.pNumericFloat, Offset, Count, pType, GetTotalUnpackedSize(), pFuncName); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::GetFloatArray(float *pData, UINT Offset, UINT Count) { return GetScalarArray<ETVT_Float, ETVT_Float, float, float>(Data.pNumericFloat, pData, Offset, Count, pType, GetTotalUnpackedSize(), "ID3DX11EffectScalarVariable::GetFloatArray"); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::SetInt(CONST int Value) { LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetInt"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return CopyScalarValue<ETVT_Int, ETVT_Float, int, FALSE>(Value, Data.pNumericFloat, pFuncName); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::GetInt(int *pValue) { return CopyScalarValue<ETVT_Float, ETVT_Int, float, TRUE>(*Data.pNumericFloat, pValue, "ID3DX11EffectScalarVariable::GetInt"); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::SetIntArray(CONST int *pData, UINT Offset, UINT Count) { LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetIntArray"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return SetScalarArray<ETVT_Int, ETVT_Float, int, float>(pData, Data.pNumericFloat, Offset, Count, pType, GetTotalUnpackedSize(), pFuncName); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::GetIntArray(int *pData, UINT Offset, UINT Count) { return GetScalarArray<ETVT_Float, ETVT_Int, float, int>(Data.pNumericFloat, pData, Offset, Count, pType, GetTotalUnpackedSize(), "ID3DX11EffectScalarVariable::GetIntArray"); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::SetBool(CONST BOOL Value) { LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetBool"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return CopyScalarValue<ETVT_Bool, ETVT_Float, BOOL, FALSE>(Value, Data.pNumericFloat, pFuncName); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::GetBool(BOOL *pValue) { return CopyScalarValue<ETVT_Float, ETVT_Bool, float, TRUE>(*Data.pNumericFloat, pValue, "ID3DX11EffectScalarVariable::GetBool"); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::SetBoolArray(CONST BOOL *pData, UINT Offset, UINT Count) { LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetBoolArray"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return SetScalarArray<ETVT_Bool, ETVT_Float, BOOL, float>(pData, Data.pNumericFloat, Offset, Count, pType, GetTotalUnpackedSize(), pFuncName); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::GetBoolArray(BOOL *pData, UINT Offset, UINT Count) { return GetScalarArray<ETVT_Float, ETVT_Bool, float, BOOL>(Data.pNumericFloat, pData, Offset, Count, pType, GetTotalUnpackedSize(), "ID3DX11EffectScalarVariable::GetBoolArray"); } ////////////////////////////////////////////////////////////////////////// // ID3DX11EffectScalarVariable (TIntScalarVariable implementation) ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface, BOOL IsAnnotation> struct TIntScalarVariable : public TNumericVariable<IBaseInterface, IsAnnotation> { STDMETHOD(SetFloat)(CONST float Value); STDMETHOD(GetFloat)(float *pValue); STDMETHOD(SetFloatArray)(CONST float *pData, UINT Offset, UINT Count); STDMETHOD(GetFloatArray)(float *pData, UINT Offset, UINT Count); STDMETHOD(SetInt)(CONST int Value); STDMETHOD(GetInt)(int *pValue); STDMETHOD(SetIntArray)(CONST int *pData, UINT Offset, UINT Count); STDMETHOD(GetIntArray)(int *pData, UINT Offset, UINT Count); STDMETHOD(SetBool)(CONST BOOL Value); STDMETHOD(GetBool)(BOOL *pValue); STDMETHOD(SetBoolArray)(CONST BOOL *pData, UINT Offset, UINT Count); STDMETHOD(GetBoolArray)(BOOL *pData, UINT Offset, UINT Count); }; template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::SetFloat(float Value) { LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetFloat"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return CopyScalarValue<ETVT_Float, ETVT_Int, float, FALSE>(Value, Data.pNumericInt, pFuncName); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::GetFloat(float *pValue) { return CopyScalarValue<ETVT_Int, ETVT_Float, int, TRUE>(*Data.pNumericInt, pValue, "ID3DX11EffectScalarVariable::GetFloat"); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::SetFloatArray(CONST float *pData, UINT Offset, UINT Count) { LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetFloatArray"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return SetScalarArray<ETVT_Float, ETVT_Int, float, int>(pData, Data.pNumericInt, Offset, Count, pType, GetTotalUnpackedSize(), pFuncName); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::GetFloatArray(float *pData, UINT Offset, UINT Count) { return GetScalarArray<ETVT_Int, ETVT_Float, int, float>(Data.pNumericInt, pData, Offset, Count, pType, GetTotalUnpackedSize(), "ID3DX11EffectScalarVariable::GetFloatArray"); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::SetInt(CONST int Value) { LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetInt"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return CopyScalarValue<ETVT_Int, ETVT_Int, int, FALSE>(Value, Data.pNumericInt, pFuncName); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::GetInt(int *pValue) { return CopyScalarValue<ETVT_Int, ETVT_Int, int, TRUE>(*Data.pNumericInt, pValue, "ID3DX11EffectScalarVariable::GetInt"); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::SetIntArray(CONST int *pData, UINT Offset, UINT Count) { LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetIntArray"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return SetScalarArray<ETVT_Int, ETVT_Int, int, int>(pData, Data.pNumericInt, Offset, Count, pType, GetTotalUnpackedSize(), pFuncName); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::GetIntArray(int *pData, UINT Offset, UINT Count) { return GetScalarArray<ETVT_Int, ETVT_Int, int, int>(Data.pNumericInt, pData, Offset, Count, pType, GetTotalUnpackedSize(), "ID3DX11EffectScalarVariable::GetIntArray"); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::SetBool(CONST BOOL Value) { LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetBool"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return CopyScalarValue<ETVT_Bool, ETVT_Int, BOOL, FALSE>(Value, Data.pNumericInt, pFuncName); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::GetBool(BOOL *pValue) { return CopyScalarValue<ETVT_Int, ETVT_Bool, int, TRUE>(*Data.pNumericInt, pValue, "ID3DX11EffectScalarVariable::GetBool"); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::SetBoolArray(CONST BOOL *pData, UINT Offset, UINT Count) { LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetBoolArray"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return SetScalarArray<ETVT_Bool, ETVT_Int, BOOL, int>(pData, Data.pNumericInt, Offset, Count, pType, GetTotalUnpackedSize(), pFuncName); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::GetBoolArray(BOOL *pData, UINT Offset, UINT Count) { return GetScalarArray<ETVT_Int, ETVT_Bool, int, BOOL>(Data.pNumericInt, pData, Offset, Count, pType, GetTotalUnpackedSize(), "ID3DX11EffectScalarVariable::GetBoolArray"); } ////////////////////////////////////////////////////////////////////////// // ID3DX11EffectScalarVariable (TBoolScalarVariable implementation) ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface, BOOL IsAnnotation> struct TBoolScalarVariable : public TNumericVariable<IBaseInterface, IsAnnotation> { STDMETHOD(SetFloat)(CONST float Value); STDMETHOD(GetFloat)(float *pValue); STDMETHOD(SetFloatArray)(CONST float *pData, UINT Offset, UINT Count); STDMETHOD(GetFloatArray)(float *pData, UINT Offset, UINT Count); STDMETHOD(SetInt)(CONST int Value); STDMETHOD(GetInt)(int *pValue); STDMETHOD(SetIntArray)(CONST int *pData, UINT Offset, UINT Count); STDMETHOD(GetIntArray)(int *pData, UINT Offset, UINT Count); STDMETHOD(SetBool)(CONST BOOL Value); STDMETHOD(GetBool)(BOOL *pValue); STDMETHOD(SetBoolArray)(CONST BOOL *pData, UINT Offset, UINT Count); STDMETHOD(GetBoolArray)(BOOL *pData, UINT Offset, UINT Count); }; template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::SetFloat(float Value) { LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetFloat"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return CopyScalarValue<ETVT_Float, ETVT_Bool, float, FALSE>(Value, Data.pNumericBool, pFuncName); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::GetFloat(float *pValue) { return CopyScalarValue<ETVT_Bool, ETVT_Float, BOOL, TRUE>(*Data.pNumericBool, pValue, "ID3DX11EffectScalarVariable::GetFloat"); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::SetFloatArray(CONST float *pData, UINT Offset, UINT Count) { LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetFloatArray"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return SetScalarArray<ETVT_Float, ETVT_Bool, float, BOOL>(pData, Data.pNumericBool, Offset, Count, pType, GetTotalUnpackedSize(), pFuncName); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::GetFloatArray(float *pData, UINT Offset, UINT Count) { return GetScalarArray<ETVT_Bool, ETVT_Float, BOOL, float>(Data.pNumericBool, pData, Offset, Count, pType, GetTotalUnpackedSize(), "ID3DX11EffectScalarVariable::GetFloatArray"); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::SetInt(CONST int Value) { LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetInt"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return CopyScalarValue<ETVT_Int, ETVT_Bool, int, FALSE>(Value, Data.pNumericBool, pFuncName); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::GetInt(int *pValue) { return CopyScalarValue<ETVT_Bool, ETVT_Int, BOOL, TRUE>(*Data.pNumericBool, pValue, "ID3DX11EffectScalarVariable::GetInt"); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::SetIntArray(CONST int *pData, UINT Offset, UINT Count) { LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetIntArray"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return SetScalarArray<ETVT_Int, ETVT_Bool, int, BOOL>(pData, Data.pNumericBool, Offset, Count, pType, GetTotalUnpackedSize(), pFuncName); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::GetIntArray(int *pData, UINT Offset, UINT Count) { return GetScalarArray<ETVT_Bool, ETVT_Int, BOOL, int>(Data.pNumericBool, pData, Offset, Count, pType, GetTotalUnpackedSize(), "ID3DX11EffectScalarVariable::GetIntArray"); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::SetBool(CONST BOOL Value) { LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetBool"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return CopyScalarValue<ETVT_Bool, ETVT_Bool, BOOL, FALSE>(Value, Data.pNumericBool, pFuncName); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::GetBool(BOOL *pValue) { return CopyScalarValue<ETVT_Bool, ETVT_Bool, BOOL, TRUE>(*Data.pNumericBool, pValue, "ID3DX11EffectScalarVariable::GetBool"); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::SetBoolArray(CONST BOOL *pData, UINT Offset, UINT Count) { LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetBoolArray"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return SetScalarArray<ETVT_Bool, ETVT_Bool, BOOL, BOOL>(pData, Data.pNumericBool, Offset, Count, pType, GetTotalUnpackedSize(), pFuncName); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::GetBoolArray(BOOL *pData, UINT Offset, UINT Count) { return GetScalarArray<ETVT_Bool, ETVT_Bool, BOOL, BOOL>(Data.pNumericBool, pData, Offset, Count, pType, GetTotalUnpackedSize(), "ID3DX11EffectScalarVariable::GetBoolArray"); } ////////////////////////////////////////////////////////////////////////// // ID3DX11EffectVectorVariable (TVectorVariable implementation) ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface, BOOL IsAnnotation, ETemplateVarType BaseType > struct TVectorVariable : public TNumericVariable<IBaseInterface, IsAnnotation> { STDMETHOD(SetBoolVector) (CONST BOOL *pData); STDMETHOD(SetIntVector) (CONST int *pData); STDMETHOD(SetFloatVector)(CONST float *pData); STDMETHOD(GetBoolVector) (BOOL *pData); STDMETHOD(GetIntVector) (int *pData); STDMETHOD(GetFloatVector)(float *pData); STDMETHOD(SetBoolVectorArray) (CONST BOOL *pData, UINT Offset, UINT Count); STDMETHOD(SetIntVectorArray) (CONST int *pData, UINT Offset, UINT Count); STDMETHOD(SetFloatVectorArray)(CONST float *pData, UINT Offset, UINT Count); STDMETHOD(GetBoolVectorArray) (BOOL *pData, UINT Offset, UINT Count); STDMETHOD(GetIntVectorArray) (int *pData, UINT Offset, UINT Count); STDMETHOD(GetFloatVectorArray)(float *pData, UINT Offset, UINT Count); }; // Note that branches in this code is based on template parameters and will be compiled out template <ETemplateVarType DestType, ETemplateVarType SourceType> void __forceinline CopyDataWithTypeConversion(__out_bcount(vecCount * dstVecSize * sizeof(UINT)) void *pDest, CONST void *pSource, UINT dstVecSize, UINT srcVecSize, UINT elementCount, UINT vecCount) { UINT i, j; switch (SourceType) { case ETVT_Bool: switch (DestType) { case ETVT_Bool: for (j=0; j<vecCount; j++) { dwordMemcpy(pDest, pSource, elementCount * SType::c_ScalarSize); pDest = ((float*) pDest) + dstVecSize; pSource = ((float*) pSource) + srcVecSize; } break; case ETVT_Int: for (j=0; j<vecCount; j++) { for (i=0; i<elementCount; i++) ((int*)pDest)[i] = ((BOOL*)pSource)[i] ? -1 : 0; pDest = ((float*) pDest) + dstVecSize; pSource = ((float*) pSource) + srcVecSize; } break; case ETVT_Float: for (j=0; j<vecCount; j++) { for (i=0; i<elementCount; i++) ((float*)pDest)[i] = ((BOOL*)pSource)[i] ? -1.0f : 0.0f; pDest = ((float*) pDest) + dstVecSize; pSource = ((float*) pSource) + srcVecSize; } break; default: D3DXASSERT(0); } break; case ETVT_Int: switch (DestType) { case ETVT_Bool: for (j=0; j<vecCount; j++) { for (i=0; i<elementCount; i++) ((int*)pDest)[i] = (((int*)pSource)[i] != 0) ? -1 : 0; pDest = ((float*) pDest) + dstVecSize; pSource = ((float*) pSource) + srcVecSize; } break; case ETVT_Int: for (j=0; j<vecCount; j++) { dwordMemcpy(pDest, pSource, elementCount * SType::c_ScalarSize); pDest = ((float*) pDest) + dstVecSize; pSource = ((float*) pSource) + srcVecSize; } break; case ETVT_Float: for (j=0; j<vecCount; j++) { for (i=0; i<elementCount; i++) ((float*)pDest)[i] = (float)(((int*)pSource)[i]); pDest = ((float*) pDest) + dstVecSize; pSource = ((float*) pSource) + srcVecSize; } break; default: D3DXASSERT(0); } break; case ETVT_Float: switch (DestType) { case ETVT_Bool: for (j=0; j<vecCount; j++) { for (i=0; i<elementCount; i++) ((int*)pDest)[i] = (((float*)pSource)[i] != 0.0f) ? -1 : 0; pDest = ((float*) pDest) + dstVecSize; pSource = ((float*) pSource) + srcVecSize; } break; case ETVT_Int: for (j=0; j<vecCount; j++) { for (i=0; i<elementCount; i++) ((int*)pDest)[i] = (int)((float*)pSource)[i]; pDest = ((float*) pDest) + dstVecSize; pSource = ((float*) pSource) + srcVecSize; } break; case ETVT_Float: for (i=0; i<vecCount; i++) { dwordMemcpy( pDest, pSource, elementCount * SType::c_ScalarSize); pDest = ((float*) pDest) + dstVecSize; pSource = ((float*) pSource) + srcVecSize; } break; default: D3DXASSERT(0); } break; default: D3DXASSERT(0); } } // Float Vector template<typename IBaseInterface, BOOL IsAnnotation, ETemplateVarType BaseType> HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType >::SetFloatVector(CONST float *pData) { HRESULT hr = S_OK; LPCSTR pFuncName = "ID3DX11EffectVectorVariable::SetFloatVector"; #ifdef _DEBUG VERIFYPARAMETER(pData); #endif if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); CopyDataWithTypeConversion<BaseType, ETVT_Float>(Data.pVector, pData, 4, pType->NumericType.Columns, pType->NumericType.Columns, 1); lExit: return hr; } template<typename IBaseInterface, BOOL IsAnnotation, ETemplateVarType BaseType> HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType>::GetFloatVector(float *pData) { HRESULT hr = S_OK; LPCSTR pFuncName = "ID3DX11EffectVectorVariable::GetFloatVector"; #ifdef _DEBUG VERIFYPARAMETER(pData); #endif CopyDataWithTypeConversion<ETVT_Float, BaseType>(pData, Data.pVector, pType->NumericType.Columns, 4, pType->NumericType.Columns, 1); lExit: return hr; } // Int Vector template<typename IBaseInterface, BOOL IsAnnotation, ETemplateVarType BaseType> HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType >::SetIntVector(CONST int *pData) { HRESULT hr = S_OK; LPCSTR pFuncName = "ID3DX11EffectVectorVariable::SetIntVector"; #ifdef _DEBUG VERIFYPARAMETER(pData); #endif if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); CopyDataWithTypeConversion<BaseType, ETVT_Int>(Data.pVector, pData, 4, pType->NumericType.Columns, pType->NumericType.Columns, 1); lExit: return hr; } template<typename IBaseInterface, BOOL IsAnnotation, ETemplateVarType BaseType> HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType>::GetIntVector(int *pData) { HRESULT hr = S_OK; LPCSTR pFuncName = "ID3DX11EffectVectorVariable::GetIntVector"; #ifdef _DEBUG VERIFYPARAMETER(pData); #endif CopyDataWithTypeConversion<ETVT_Int, BaseType>(pData, Data.pVector, pType->NumericType.Columns, 4, pType->NumericType.Columns, 1); lExit: return hr; } // Bool Vector template<typename IBaseInterface, BOOL IsAnnotation, ETemplateVarType BaseType> HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType >::SetBoolVector(CONST BOOL *pData) { HRESULT hr = S_OK; LPCSTR pFuncName = "ID3DX11EffectVectorVariable::SetBoolVector"; #ifdef _DEBUG VERIFYPARAMETER(pData); #endif if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); CopyDataWithTypeConversion<BaseType, ETVT_Bool>(Data.pVector, pData, 4, pType->NumericType.Columns, pType->NumericType.Columns, 1); lExit: return hr; } template<typename IBaseInterface, BOOL IsAnnotation, ETemplateVarType BaseType> HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType>::GetBoolVector(BOOL *pData) { HRESULT hr = S_OK; LPCSTR pFuncName = "ID3DX11EffectVectorVariable::GetBoolVector"; #ifdef _DEBUG VERIFYPARAMETER(pData); #endif CopyDataWithTypeConversion<ETVT_Bool, BaseType>(pData, Data.pVector, pType->NumericType.Columns, 4, pType->NumericType.Columns, 1); lExit: return hr; } // Vector Arrays ///////////////////////////////////////////////////////// template<typename IBaseInterface, BOOL IsAnnotation, ETemplateVarType BaseType> HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType>::SetFloatVectorArray(CONST float *pData, UINT Offset, UINT Count) { HRESULT hr = S_OK; LPCSTR pFuncName = "ID3DX11EffectVectorVariable::SetFloatVectorArray"; #ifdef _DEBUG if (!AreBoundsValid(Offset, Count, pData, pType, GetTotalUnpackedSize())) { DPF(0, "%s: Invalid range specified", pFuncName); VH(E_INVALIDARG); } #endif if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); // ensure we don't write over the padding at the end of the vector array CopyDataWithTypeConversion<BaseType, ETVT_Float>(Data.pVector + Offset, pData, 4, pType->NumericType.Columns, pType->NumericType.Columns, max(min((int)Count, (int)pType->Elements - (int)Offset), 0)); lExit: return hr; } template<typename IBaseInterface, BOOL IsAnnotation, ETemplateVarType BaseType> HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType>::GetFloatVectorArray(float *pData, UINT Offset, UINT Count) { HRESULT hr = S_OK; LPCSTR pFuncName = "ID3DX11EffectVectorVariable::GetFloatVectorArray"; #ifdef _DEBUG if (!AreBoundsValid(Offset, Count, pData, pType, GetTotalUnpackedSize())) { DPF(0, "%s: Invalid range specified", pFuncName); VH(E_INVALIDARG); } #endif // ensure we don't read past the end of the vector array CopyDataWithTypeConversion<ETVT_Float, BaseType>(pData, Data.pVector + Offset, pType->NumericType.Columns, 4, pType->NumericType.Columns, max(min((int)Count, (int)pType->Elements - (int)Offset), 0)); lExit: return hr; } // int template<typename IBaseInterface, BOOL IsAnnotation, ETemplateVarType BaseType> HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType>::SetIntVectorArray(CONST int *pData, UINT Offset, UINT Count) { HRESULT hr = S_OK; LPCSTR pFuncName = "ID3DX11EffectVectorVariable::SetIntVectorArray"; #ifdef _DEBUG if (!AreBoundsValid(Offset, Count, pData, pType, GetTotalUnpackedSize())) { DPF(0, "%s: Invalid range specified", pFuncName); VH(E_INVALIDARG); } #endif if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); // ensure we don't write over the padding at the end of the vector array CopyDataWithTypeConversion<BaseType, ETVT_Int>(Data.pVector + Offset, pData, 4, pType->NumericType.Columns, pType->NumericType.Columns, max(min((int)Count, (int)pType->Elements - (int)Offset), 0)); lExit: return hr; } template<typename IBaseInterface, BOOL IsAnnotation, ETemplateVarType BaseType> HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType>::GetIntVectorArray(int *pData, UINT Offset, UINT Count) { HRESULT hr = S_OK; LPCSTR pFuncName = "ID3DX11EffectVectorVariable::GetIntVectorArray"; #ifdef _DEBUG if (!AreBoundsValid(Offset, Count, pData, pType, GetTotalUnpackedSize())) { DPF(0, "%s: Invalid range specified", pFuncName); VH(E_INVALIDARG); } #endif // ensure we don't read past the end of the vector array CopyDataWithTypeConversion<ETVT_Int, BaseType>(pData, Data.pVector + Offset, pType->NumericType.Columns, 4, pType->NumericType.Columns, max(min((int)Count, (int)pType->Elements - (int)Offset), 0)); lExit: return hr; } // bool template<typename IBaseInterface, BOOL IsAnnotation, ETemplateVarType BaseType> HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType>::SetBoolVectorArray(CONST BOOL *pData, UINT Offset, UINT Count) { HRESULT hr = S_OK; LPCSTR pFuncName = "ID3DX11EffectVectorVariable::SetBoolVectorArray"; #ifdef _DEBUG if (!AreBoundsValid(Offset, Count, pData, pType, GetTotalUnpackedSize())) { DPF(0, "%s: Invalid range specified", pFuncName); VH(E_INVALIDARG); } #endif if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); // ensure we don't write over the padding at the end of the vector array CopyDataWithTypeConversion<BaseType, ETVT_Bool>(Data.pVector + Offset, pData, 4, pType->NumericType.Columns, pType->NumericType.Columns, max(min((int)Count, (int)pType->Elements - (int)Offset), 0)); lExit: return hr; } template<typename IBaseInterface, BOOL IsAnnotation, ETemplateVarType BaseType> HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType>::GetBoolVectorArray(BOOL *pData, UINT Offset, UINT Count) { HRESULT hr = S_OK; LPCSTR pFuncName = "ID3DX11EffectVectorVariable::GetBoolVectorArray"; #ifdef _DEBUG if (!AreBoundsValid(Offset, Count, pData, pType, GetTotalUnpackedSize())) { DPF(0, "%s: Invalid range specified", pFuncName); VH(E_INVALIDARG); } #endif // ensure we don't read past the end of the vector array CopyDataWithTypeConversion<ETVT_Bool, BaseType>(pData, Data.pVector + Offset, pType->NumericType.Columns, 4, pType->NumericType.Columns, max(min((int)Count, (int)pType->Elements - (int)Offset), 0)); lExit: return hr; } ////////////////////////////////////////////////////////////////////////// // ID3DX11EffectVector4Variable (TVectorVariable implementation) [OPTIMIZED] ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TVector4Variable : public TVectorVariable<IBaseInterface, FALSE, ETVT_Float> { STDMETHOD(SetFloatVector)(CONST float *pData); STDMETHOD(GetFloatVector)(float *pData); STDMETHOD(SetFloatVectorArray)(CONST float *pData, UINT Offset, UINT Count); STDMETHOD(GetFloatVectorArray)(float *pData, UINT Offset, UINT Count); }; template<typename IBaseInterface> HRESULT TVector4Variable<IBaseInterface>::SetFloatVector(CONST float *pData) { HRESULT hr = S_OK; LPCSTR pFuncName = "ID3DX11EffectVectorVariable::SetFloatVector"; #ifdef _DEBUG VERIFYPARAMETER(pData); #endif DirtyVariable(); Data.pVector[0] = ((CEffectVector4*) pData)[0]; lExit: return hr; } template<typename IBaseInterface> HRESULT TVector4Variable<IBaseInterface>::GetFloatVector(float *pData) { HRESULT hr = S_OK; LPCSTR pFuncName = "ID3DX11EffectVectorVariable::GetFloatVector"; #ifdef _DEBUG VERIFYPARAMETER(pData); #endif dwordMemcpy(pData, Data.pVector, pType->NumericType.Columns * SType::c_ScalarSize); lExit: return hr; } template<typename IBaseInterface> HRESULT TVector4Variable<IBaseInterface>::SetFloatVectorArray(CONST float *pData, UINT Offset, UINT Count) { HRESULT hr = S_OK; LPCSTR pFuncName = "ID3DX11EffectVectorVariable::SetFloatVectorArray"; #ifdef _DEBUG if (!AreBoundsValid(Offset, Count, pData, pType, GetTotalUnpackedSize())) { DPF(0, "%s: Invalid range specified", pFuncName); VH(E_INVALIDARG); } #endif DirtyVariable(); // ensure we don't write over the padding at the end of the vector array dwordMemcpy(Data.pVector + Offset, pData, min((Offset + Count) * sizeof(CEffectVector4), pType->TotalSize)); lExit: return hr; } template<typename IBaseInterface> HRESULT TVector4Variable<IBaseInterface>::GetFloatVectorArray(float *pData, UINT Offset, UINT Count) { HRESULT hr = S_OK; LPCSTR pFuncName = "ID3DX11EffectVectorVariable::GetFloatVectorArray"; #ifdef _DEBUG if (!AreBoundsValid(Offset, Count, pData, pType, GetTotalUnpackedSize())) { DPF(0, "%s: Invalid range specified", pFuncName); VH(E_INVALIDARG); } #endif // ensure we don't read past the end of the vector array dwordMemcpy(pData, Data.pVector + Offset, min((Offset + Count) * sizeof(CEffectVector4), pType->TotalSize)); lExit: return hr; } ////////////////////////////////////////////////////////////////////////// // ID3DX11EffectMatrixVariable (TMatrixVariable implementation) ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface, BOOL IsAnnotation> struct TMatrixVariable : public TNumericVariable<IBaseInterface, IsAnnotation> { STDMETHOD(SetMatrix)(CONST float *pData); STDMETHOD(GetMatrix)(float *pData); STDMETHOD(SetMatrixArray)(CONST float *pData, UINT Offset, UINT Count); STDMETHOD(GetMatrixArray)(float *pData, UINT Offset, UINT Count); STDMETHOD(SetMatrixPointerArray)(CONST float **ppData, UINT Offset, UINT Count); STDMETHOD(GetMatrixPointerArray)(float **ppData, UINT Offset, UINT Count); STDMETHOD(SetMatrixTranspose)(CONST float *pData); STDMETHOD(GetMatrixTranspose)(float *pData); STDMETHOD(SetMatrixTransposeArray)(CONST float *pData, UINT Offset, UINT Count); STDMETHOD(GetMatrixTransposeArray)(float *pData, UINT Offset, UINT Count); STDMETHOD(SetMatrixTransposePointerArray)(CONST float **ppData, UINT Offset, UINT Count); STDMETHOD(GetMatrixTransposePointerArray)(float **ppData, UINT Offset, UINT Count); }; template<BOOL Transpose> static void SetMatrixTransposeHelper(SType *pType, __out_bcount(64) BYTE *pDestData, CONST float* pMatrix) { UINT i, j; UINT registers, entries; if (Transpose) { // row major registers = pType->NumericType.Rows; entries = pType->NumericType.Columns; } else { // column major registers = pType->NumericType.Columns; entries = pType->NumericType.Rows; } __analysis_assume( registers <= 4 ); __analysis_assume( entries <= 4 ); for (i = 0; i < registers; ++ i) { for (j = 0; j < entries; ++ j) { #pragma prefast(suppress:__WARNING_UNRELATED_LOOP_TERMINATION, "regs / entries <= 4") ((float*)pDestData)[j] = ((float*)pMatrix)[j * 4 + i]; } pDestData += SType::c_RegisterSize; } } template<BOOL Transpose> static void GetMatrixTransposeHelper(SType *pType, __in_bcount(64) BYTE *pSrcData, __out_ecount(16) float* pMatrix) { UINT i, j; UINT registers, entries; if (Transpose) { // row major registers = pType->NumericType.Rows; entries = pType->NumericType.Columns; } else { // column major registers = pType->NumericType.Columns; entries = pType->NumericType.Rows; } __analysis_assume( registers <= 4 ); __analysis_assume( entries <= 4 ); for (i = 0; i < registers; ++ i) { for (j = 0; j < entries; ++ j) { ((float*)pMatrix)[j * 4 + i] = ((float*)pSrcData)[j]; } pSrcData += SType::c_RegisterSize; } } template<BOOL Transpose, BOOL IsSetting, BOOL ExtraIndirection> HRESULT DoMatrixArrayInternal(SType *pType, UINT TotalUnpackedSize, BYTE *pEffectData, void *pMatrixData, UINT Offset, UINT Count, LPCSTR pFuncName) { HRESULT hr = S_OK; #ifdef _DEBUG if (!AreBoundsValid(Offset, Count, pMatrixData, pType, TotalUnpackedSize)) { DPF(0, "%s: Invalid range specified", pFuncName); VH(E_INVALIDARG); } #endif UINT i; if ((pType->NumericType.IsColumnMajor && Transpose) || (!pType->NumericType.IsColumnMajor && !Transpose)) { // fast path UINT dataSize; if (Transpose) { dataSize = ((pType->NumericType.Columns - 1) * 4 + pType->NumericType.Rows) * SType::c_ScalarSize; } else { dataSize = ((pType->NumericType.Rows - 1) * 4 + pType->NumericType.Columns) * SType::c_ScalarSize; } for (i = 0; i < Count; ++ i) { CEffectMatrix *pMatrix; if (ExtraIndirection) { pMatrix = ((CEffectMatrix **)pMatrixData)[i]; if (!pMatrix) { continue; } } else { pMatrix = ((CEffectMatrix *)pMatrixData) + i; } if (IsSetting) { dwordMemcpy(pEffectData + pType->Stride * (i + Offset), pMatrix, dataSize); } else { dwordMemcpy(pMatrix, pEffectData + pType->Stride * (i + Offset), dataSize); } } } else { // slow path for (i = 0; i < Count; ++ i) { CEffectMatrix *pMatrix; if (ExtraIndirection) { pMatrix = ((CEffectMatrix **)pMatrixData)[i]; if (!pMatrix) { continue; } } else { pMatrix = ((CEffectMatrix *)pMatrixData) + i; } if (IsSetting) { SetMatrixTransposeHelper<Transpose>(pType, pEffectData + pType->Stride * (i + Offset), (float*) pMatrix); } else { GetMatrixTransposeHelper<Transpose>(pType, pEffectData + pType->Stride * (i + Offset), (float*) pMatrix); } } } lExit: return hr; } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::SetMatrix(CONST float *pData) { LPCSTR pFuncName = "ID3DX11EffectMatrixVariable::SetMatrix"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return DoMatrixArrayInternal<FALSE, TRUE, FALSE>(pType, GetTotalUnpackedSize(), Data.pNumeric, const_cast<float*>(pData), 0, 1, pFuncName); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::GetMatrix(float *pData) { return DoMatrixArrayInternal<FALSE, FALSE, FALSE>(pType, GetTotalUnpackedSize(), Data.pNumeric, pData, 0, 1, "ID3DX11EffectMatrixVariable::GetMatrix"); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::SetMatrixArray(CONST float *pData, UINT Offset, UINT Count) { LPCSTR pFuncName = "ID3DX11EffectMatrixVariable::SetMatrixArray"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return DoMatrixArrayInternal<FALSE, TRUE, FALSE>(pType, GetTotalUnpackedSize(), Data.pNumeric, const_cast<float*>(pData), Offset, Count, "ID3DX11EffectMatrixVariable::SetMatrixArray"); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::GetMatrixArray(float *pData, UINT Offset, UINT Count) { return DoMatrixArrayInternal<FALSE, FALSE, FALSE>(pType, GetTotalUnpackedSize(), Data.pNumeric, pData, Offset, Count, "ID3DX11EffectMatrixVariable::GetMatrixArray"); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::SetMatrixPointerArray(CONST float **ppData, UINT Offset, UINT Count) { LPCSTR pFuncName = "ID3DX11EffectMatrixVariable::SetMatrixPointerArray"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return DoMatrixArrayInternal<FALSE, TRUE, TRUE>(pType, GetTotalUnpackedSize(), Data.pNumeric, const_cast<float**>(ppData), Offset, Count, "ID3DX11EffectMatrixVariable::SetMatrixPointerArray"); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::GetMatrixPointerArray(float **ppData, UINT Offset, UINT Count) { return DoMatrixArrayInternal<FALSE, FALSE, TRUE>(pType, GetTotalUnpackedSize(), Data.pNumeric, ppData, Offset, Count, "ID3DX11EffectMatrixVariable::GetMatrixPointerArray"); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::SetMatrixTranspose(CONST float *pData) { LPCSTR pFuncName = "ID3DX11EffectMatrixVariable::SetMatrixTranspose"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return DoMatrixArrayInternal<TRUE, TRUE, FALSE>(pType, GetTotalUnpackedSize(), Data.pNumeric, const_cast<float*>(pData), 0, 1, "ID3DX11EffectMatrixVariable::SetMatrixTranspose"); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::GetMatrixTranspose(float *pData) { return DoMatrixArrayInternal<TRUE, FALSE, FALSE>(pType, GetTotalUnpackedSize(), Data.pNumeric, pData, 0, 1, "ID3DX11EffectMatrixVariable::GetMatrixTranspose"); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::SetMatrixTransposeArray(CONST float *pData, UINT Offset, UINT Count) { LPCSTR pFuncName = "ID3DX11EffectMatrixVariable::SetMatrixTransposeArray"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return DoMatrixArrayInternal<TRUE, TRUE, FALSE>(pType, GetTotalUnpackedSize(), Data.pNumeric, const_cast<float*>(pData), Offset, Count, "ID3DX11EffectMatrixVariable::SetMatrixTransposeArray"); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::GetMatrixTransposeArray(float *pData, UINT Offset, UINT Count) { return DoMatrixArrayInternal<TRUE, FALSE, FALSE>(pType, GetTotalUnpackedSize(), Data.pNumeric, pData, Offset, Count, "ID3DX11EffectMatrixVariable::GetMatrixTransposeArray"); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::SetMatrixTransposePointerArray(CONST float **ppData, UINT Offset, UINT Count) { LPCSTR pFuncName = "ID3DX11EffectMatrixVariable::SetMatrixTransposePointerArray"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return DoMatrixArrayInternal<TRUE, TRUE, TRUE>(pType, GetTotalUnpackedSize(), Data.pNumeric, const_cast<float**>(ppData), Offset, Count, "ID3DX11EffectMatrixVariable::SetMatrixTransposePointerArray"); } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::GetMatrixTransposePointerArray(float **ppData, UINT Offset, UINT Count) { return DoMatrixArrayInternal<TRUE, FALSE, TRUE>(pType, GetTotalUnpackedSize(), Data.pNumeric, ppData, Offset, Count, "ID3DX11EffectMatrixVariable::GetMatrixTransposePointerArray"); } // Optimize commonly used fast paths // (non-annotations only!) template<typename IBaseInterface, BOOL IsColumnMajor> struct TMatrix4x4Variable : public TMatrixVariable<IBaseInterface, FALSE> { STDMETHOD(SetMatrix)(CONST float *pData); STDMETHOD(GetMatrix)(float *pData); STDMETHOD(SetMatrixArray)(CONST float *pData, UINT Offset, UINT Count); STDMETHOD(GetMatrixArray)(float *pData, UINT Offset, UINT Count); STDMETHOD(SetMatrixTranspose)(CONST float *pData); STDMETHOD(GetMatrixTranspose)(float *pData); STDMETHOD(SetMatrixTransposeArray)(CONST float *pData, UINT Offset, UINT Count); STDMETHOD(GetMatrixTransposeArray)(float *pData, UINT Offset, UINT Count); }; D3DX11INLINE static void Matrix4x4TransposeHelper(CONST void *pSrc, void *pDst) { BYTE *pDestData = (BYTE*)pDst; UINT *pMatrix = (UINT*)pSrc; ((UINT*)pDestData)[0 * 4 + 0] = pMatrix[0 * 4 + 0]; ((UINT*)pDestData)[0 * 4 + 1] = pMatrix[1 * 4 + 0]; ((UINT*)pDestData)[0 * 4 + 2] = pMatrix[2 * 4 + 0]; ((UINT*)pDestData)[0 * 4 + 3] = pMatrix[3 * 4 + 0]; ((UINT*)pDestData)[1 * 4 + 0] = pMatrix[0 * 4 + 1]; ((UINT*)pDestData)[1 * 4 + 1] = pMatrix[1 * 4 + 1]; ((UINT*)pDestData)[1 * 4 + 2] = pMatrix[2 * 4 + 1]; ((UINT*)pDestData)[1 * 4 + 3] = pMatrix[3 * 4 + 1]; ((UINT*)pDestData)[2 * 4 + 0] = pMatrix[0 * 4 + 2]; ((UINT*)pDestData)[2 * 4 + 1] = pMatrix[1 * 4 + 2]; ((UINT*)pDestData)[2 * 4 + 2] = pMatrix[2 * 4 + 2]; ((UINT*)pDestData)[2 * 4 + 3] = pMatrix[3 * 4 + 2]; ((UINT*)pDestData)[3 * 4 + 0] = pMatrix[0 * 4 + 3]; ((UINT*)pDestData)[3 * 4 + 1] = pMatrix[1 * 4 + 3]; ((UINT*)pDestData)[3 * 4 + 2] = pMatrix[2 * 4 + 3]; ((UINT*)pDestData)[3 * 4 + 3] = pMatrix[3 * 4 + 3]; } D3DX11INLINE static void Matrix4x4Copy(CONST void *pSrc, void *pDst) { #if 1 // In tests, this path ended up generating faster code both on x86 and x64 // T1 - Matrix4x4Copy - this path // T2 - Matrix4x4Transpose // T1: 1.88 T2: 1.92 - with 32 bit copies // T1: 1.85 T2: 1.80 - with 64 bit copies UINT64 *pDestData = (UINT64*)pDst; UINT64 *pMatrix = (UINT64*)pSrc; pDestData[0 * 4 + 0] = pMatrix[0 * 4 + 0]; pDestData[0 * 4 + 1] = pMatrix[0 * 4 + 1]; pDestData[0 * 4 + 2] = pMatrix[0 * 4 + 2]; pDestData[0 * 4 + 3] = pMatrix[0 * 4 + 3]; pDestData[1 * 4 + 0] = pMatrix[1 * 4 + 0]; pDestData[1 * 4 + 1] = pMatrix[1 * 4 + 1]; pDestData[1 * 4 + 2] = pMatrix[1 * 4 + 2]; pDestData[1 * 4 + 3] = pMatrix[1 * 4 + 3]; #else UINT *pDestData = (UINT*)pDst; UINT *pMatrix = (UINT*)pSrc; pDestData[0 * 4 + 0] = pMatrix[0 * 4 + 0]; pDestData[0 * 4 + 1] = pMatrix[0 * 4 + 1]; pDestData[0 * 4 + 2] = pMatrix[0 * 4 + 2]; pDestData[0 * 4 + 3] = pMatrix[0 * 4 + 3]; pDestData[1 * 4 + 0] = pMatrix[1 * 4 + 0]; pDestData[1 * 4 + 1] = pMatrix[1 * 4 + 1]; pDestData[1 * 4 + 2] = pMatrix[1 * 4 + 2]; pDestData[1 * 4 + 3] = pMatrix[1 * 4 + 3]; pDestData[2 * 4 + 0] = pMatrix[2 * 4 + 0]; pDestData[2 * 4 + 1] = pMatrix[2 * 4 + 1]; pDestData[2 * 4 + 2] = pMatrix[2 * 4 + 2]; pDestData[2 * 4 + 3] = pMatrix[2 * 4 + 3]; pDestData[3 * 4 + 0] = pMatrix[3 * 4 + 0]; pDestData[3 * 4 + 1] = pMatrix[3 * 4 + 1]; pDestData[3 * 4 + 2] = pMatrix[3 * 4 + 2]; pDestData[3 * 4 + 3] = pMatrix[3 * 4 + 3]; #endif } // Note that branches in this code is based on template parameters and will be compiled out template<BOOL IsColumnMajor, BOOL Transpose, BOOL IsSetting> D3DX11INLINE HRESULT DoMatrix4x4ArrayInternal(BYTE *pEffectData, void *pMatrixData, UINT Offset, UINT Count #ifdef _DEBUG , SType *pType, UINT TotalUnpackedSize, LPCSTR pFuncName) #else ) #endif { HRESULT hr = S_OK; #ifdef _DEBUG if (!AreBoundsValid(Offset, Count, pMatrixData, pType, TotalUnpackedSize)) { DPF(0, "%s: Invalid range specified", pFuncName); VH(E_INVALIDARG); } D3DXASSERT(pType->NumericType.IsColumnMajor == IsColumnMajor && pType->Stride == (4 * SType::c_RegisterSize)); #endif UINT i; if ((IsColumnMajor && Transpose) || (!IsColumnMajor && !Transpose)) { // fast path for (i = 0; i < Count; ++ i) { CEffectMatrix *pMatrix = ((CEffectMatrix *)pMatrixData) + i; if (IsSetting) { Matrix4x4Copy(pMatrix, pEffectData + 4 * SType::c_RegisterSize * (i + Offset)); } else { Matrix4x4Copy(pEffectData + 4 * SType::c_RegisterSize * (i + Offset), pMatrix); } } } else { // slow path for (i = 0; i < Count; ++ i) { CEffectMatrix *pMatrix = ((CEffectMatrix *)pMatrixData) + i; if (IsSetting) { Matrix4x4TransposeHelper((float*) pMatrix, pEffectData + 4 * SType::c_RegisterSize * (i + Offset)); } else { Matrix4x4TransposeHelper(pEffectData + 4 * SType::c_RegisterSize * (i + Offset), (float*) pMatrix); } } } lExit: return hr; } template<typename IBaseInterface, BOOL IsColumnMajor> HRESULT TMatrix4x4Variable<IBaseInterface, IsColumnMajor>::SetMatrix(CONST float *pData) { DirtyVariable(); return DoMatrix4x4ArrayInternal<IsColumnMajor, FALSE, TRUE>(Data.pNumeric, const_cast<float*>(pData), 0, 1 #ifdef _DEBUG , pType, GetTotalUnpackedSize(), "ID3DX11EffectMatrixVariable::SetMatrix"); #else ); #endif } template<typename IBaseInterface, BOOL IsColumnMajor> HRESULT TMatrix4x4Variable<IBaseInterface, IsColumnMajor>::GetMatrix(float *pData) { return DoMatrix4x4ArrayInternal<IsColumnMajor, FALSE, FALSE>(Data.pNumeric, pData, 0, 1 #ifdef _DEBUG , pType, GetTotalUnpackedSize(), "ID3DX11EffectMatrixVariable::GetMatrix"); #else ); #endif } template<typename IBaseInterface, BOOL IsColumnMajor> HRESULT TMatrix4x4Variable<IBaseInterface, IsColumnMajor>::SetMatrixArray(CONST float *pData, UINT Offset, UINT Count) { DirtyVariable(); return DoMatrix4x4ArrayInternal<IsColumnMajor, FALSE, TRUE>(Data.pNumeric, const_cast<float*>(pData), Offset, Count #ifdef _DEBUG , pType, GetTotalUnpackedSize(), "ID3DX11EffectMatrixVariable::SetMatrixArray"); #else ); #endif } template<typename IBaseInterface, BOOL IsColumnMajor> HRESULT TMatrix4x4Variable<IBaseInterface, IsColumnMajor>::GetMatrixArray(float *pData, UINT Offset, UINT Count) { return DoMatrix4x4ArrayInternal<IsColumnMajor, FALSE, FALSE>(Data.pNumeric, pData, Offset, Count #ifdef _DEBUG , pType, GetTotalUnpackedSize(), "ID3DX11EffectMatrixVariable::GetMatrixArray"); #else ); #endif } template<typename IBaseInterface, BOOL IsColumnMajor> HRESULT TMatrix4x4Variable<IBaseInterface, IsColumnMajor>::SetMatrixTranspose(CONST float *pData) { DirtyVariable(); return DoMatrix4x4ArrayInternal<IsColumnMajor, TRUE, TRUE>(Data.pNumeric, const_cast<float*>(pData), 0, 1 #ifdef _DEBUG , pType, GetTotalUnpackedSize(), "ID3DX11EffectMatrixVariable::SetMatrixTranspose"); #else ); #endif } template<typename IBaseInterface, BOOL IsColumnMajor> HRESULT TMatrix4x4Variable<IBaseInterface, IsColumnMajor>::GetMatrixTranspose(float *pData) { return DoMatrix4x4ArrayInternal<IsColumnMajor, TRUE, FALSE>(Data.pNumeric, pData, 0, 1 #ifdef _DEBUG , pType, GetTotalUnpackedSize(), "ID3DX11EffectMatrixVariable::GetMatrixTranspose"); #else ); #endif } template<typename IBaseInterface, BOOL IsColumnMajor> HRESULT TMatrix4x4Variable<IBaseInterface, IsColumnMajor>::SetMatrixTransposeArray(CONST float *pData, UINT Offset, UINT Count) { DirtyVariable(); return DoMatrix4x4ArrayInternal<IsColumnMajor, TRUE, TRUE>(Data.pNumeric, const_cast<float*>(pData), Offset, Count #ifdef _DEBUG , pType, GetTotalUnpackedSize(), "ID3DX11EffectMatrixVariable::SetMatrixTransposeArray"); #else ); #endif } template<typename IBaseInterface, BOOL IsColumnMajor> HRESULT TMatrix4x4Variable<IBaseInterface, IsColumnMajor>::GetMatrixTransposeArray(float *pData, UINT Offset, UINT Count) { return DoMatrix4x4ArrayInternal<IsColumnMajor, TRUE, FALSE>(Data.pNumeric, pData, Offset, Count #ifdef _DEBUG , pType, GetTotalUnpackedSize(), "ID3DX11EffectMatrixVariable::GetMatrixTransposeArray"); #else ); #endif } #ifdef _DEBUG // Useful object macro to check bounds and parameters #define CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, Pointer) \ HRESULT hr = S_OK; \ VERIFYPARAMETER(Pointer) \ UINT elements = IsArray() ? pType->Elements : 1; \ \ if ((Offset + Count < Offset) || (elements < Offset + Count)) \ { \ DPF(0, "%s: Invalid range specified", pFuncName); \ VH(E_INVALIDARG); \ } \ #define CHECK_OBJECT_SCALAR_BOUNDS(Index, Pointer) \ HRESULT hr = S_OK; \ VERIFYPARAMETER(Pointer) \ UINT elements = IsArray() ? pType->Elements : 1; \ \ if (Index >= elements) \ { \ DPF(0, "%s: Invalid index specified", pFuncName); \ VH(E_INVALIDARG); \ } \ #define CHECK_SCALAR_BOUNDS(Index) \ HRESULT hr = S_OK; \ UINT elements = IsArray() ? pType->Elements : 1; \ \ if (Index >= elements) \ { \ DPF(0, "%s: Invalid index specified", pFuncName); \ VH(E_INVALIDARG); \ } \ #else // _DEBUG #define CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, Pointer) \ HRESULT hr = S_OK; \ #define CHECK_OBJECT_SCALAR_BOUNDS(Index, Pointer) \ HRESULT hr = S_OK; \ #define CHECK_SCALAR_BOUNDS(Index) \ HRESULT hr = S_OK; \ #endif // _DEBUG ////////////////////////////////////////////////////////////////////////// // ID3DX11EffectStringVariable (TStringVariable implementation) ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface, BOOL IsAnnotation> struct TStringVariable : public IBaseInterface { STDMETHOD(GetString)(LPCSTR *ppString); STDMETHOD(GetStringArray)( __out_ecount(Count) LPCSTR *ppStrings, UINT Offset, UINT Count ); }; template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TStringVariable<IBaseInterface, IsAnnotation>::GetString(LPCSTR *ppString) { HRESULT hr = S_OK; LPCSTR pFuncName = "ID3DX11EffectStringVariable::GetString"; VERIFYPARAMETER(ppString); if (GetTopLevelEntity()->pEffect->IsOptimized()) { DPF(0, "%s: Effect has been Optimize()'ed; all string/reflection data has been deleted", pFuncName); return D3DERR_INVALIDCALL; } D3DXASSERT(NULL != Data.pString); *ppString = Data.pString->pString; lExit: return hr; } template<typename IBaseInterface, BOOL IsAnnotation> HRESULT TStringVariable<IBaseInterface, IsAnnotation>::GetStringArray( __out_ecount(Count) LPCSTR *ppStrings, UINT Offset, UINT Count) { LPCSTR pFuncName = "ID3DX11EffectStringVariable::GetStringArray"; CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, ppStrings); if (GetTopLevelEntity()->pEffect->IsOptimized()) { DPF(0, "%s: Effect has been Optimize()'ed; all string/reflection data has been deleted", pFuncName); return D3DERR_INVALIDCALL; } D3DXASSERT(NULL != Data.pString); UINT i; for (i = 0; i < Count; ++ i) { ppStrings[i] = (Data.pString + Offset + i)->pString; } lExit: return hr; } ////////////////////////////////////////////////////////////////////////// // ID3DX11EffectClassInstanceVariable (TClassInstanceVariable implementation) ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TClassInstanceVariable : public IBaseInterface { STDMETHOD(GetClassInstance)(ID3D11ClassInstance **ppClassInstance); }; template<typename IBaseClassInstance> HRESULT TClassInstanceVariable<IBaseClassInstance>::GetClassInstance(ID3D11ClassInstance** ppClassInstance) { HRESULT hr = S_OK; LPCSTR pFuncName = "ID3DX11EffectClassInstanceVariable::GetClassInstance"; D3DXASSERT( pMemberData != NULL ); *ppClassInstance = pMemberData->Data.pD3DClassInstance; SAFE_ADDREF(*ppClassInstance); lExit: return hr; } ////////////////////////////////////////////////////////////////////////// // ID3DX11EffectInterfaceeVariable (TInterfaceVariable implementation) ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TInterfaceVariable : public IBaseInterface { STDMETHOD(SetClassInstance)(ID3DX11EffectClassInstanceVariable *pEffectClassInstance); STDMETHOD(GetClassInstance)(ID3DX11EffectClassInstanceVariable **ppEffectClassInstance); }; template<typename IBaseInterface> HRESULT TInterfaceVariable<IBaseInterface>::SetClassInstance(ID3DX11EffectClassInstanceVariable *pEffectClassInstance) { HRESULT hr = S_OK; LPCSTR pFuncName = "ID3DX11EffectInterfaceVariable::SetClassInstance"; // Note that we don't check if the types are compatible. The debug layer will complain if it is. // IsValid() will not catch type mismatches. SClassInstanceGlobalVariable* pCI = (SClassInstanceGlobalVariable*)pEffectClassInstance; Data.pInterface->pClassInstance = pCI; lExit: return hr; } template<typename IBaseInterface> HRESULT TInterfaceVariable<IBaseInterface>::GetClassInstance(ID3DX11EffectClassInstanceVariable **ppEffectClassInstance) { HRESULT hr = S_OK; LPCSTR pFuncName = "ID3DX11EffectInterfaceVariable::GetClassInstance"; #ifdef _DEBUG VERIFYPARAMETER(ppEffectClassInstance); #endif *ppEffectClassInstance = Data.pInterface->pClassInstance; lExit: return hr; } ////////////////////////////////////////////////////////////////////////// // ID3DX11EffectShaderResourceVariable (TShaderResourceVariable implementation) ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TShaderResourceVariable : public IBaseInterface { STDMETHOD(SetResource)(ID3D11ShaderResourceView *pResource); STDMETHOD(GetResource)(ID3D11ShaderResourceView **ppResource); STDMETHOD(SetResourceArray)(ID3D11ShaderResourceView **ppResources, UINT Offset, UINT Count); STDMETHOD(GetResourceArray)(ID3D11ShaderResourceView **ppResources, UINT Offset, UINT Count); }; static LPCSTR GetTextureTypeNameFromEnum(EObjectType ObjectType) { switch (ObjectType) { case EOT_Buffer: return "Buffer"; case EOT_Texture: return "texture"; case EOT_Texture1D: case EOT_Texture1DArray: return "Texture1D"; case EOT_Texture2DMS: case EOT_Texture2DMSArray: return "Texture2DMS"; case EOT_Texture2D: case EOT_Texture2DArray: return "Texture2D"; case EOT_Texture3D: return "Texture3D"; case EOT_TextureCube: return "TextureCube"; case EOT_TextureCubeArray: return "TextureCubeArray"; case EOT_RWTexture1D: case EOT_RWTexture1DArray: return "RWTexture1D"; case EOT_RWTexture2D: case EOT_RWTexture2DArray: return "RWTexture2D"; case EOT_RWTexture3D: return "RWTexture3D"; case EOT_RWBuffer: return "RWBuffer"; case EOT_ByteAddressBuffer: return "ByteAddressBuffer"; case EOT_RWByteAddressBuffer: return "RWByteAddressBuffer"; case EOT_StructuredBuffer: return "StructuredBuffe"; case EOT_RWStructuredBuffer: return "RWStructuredBuffer"; case EOT_RWStructuredBufferAlloc: return "RWStructuredBufferAlloc"; case EOT_RWStructuredBufferConsume: return "RWStructuredBufferConsume"; case EOT_AppendStructuredBuffer: return "AppendStructuredBuffer"; case EOT_ConsumeStructuredBuffer: return "ConsumeStructuredBuffer"; } return "<unknown texture format>"; } static LPCSTR GetResourceDimensionNameFromEnum(D3D11_RESOURCE_DIMENSION ResourceDimension) { switch (ResourceDimension) { case D3D11_RESOURCE_DIMENSION_BUFFER: return "Buffer"; case D3D11_RESOURCE_DIMENSION_TEXTURE1D: return "Texture1D"; case D3D11_RESOURCE_DIMENSION_TEXTURE2D: return "Texture2D"; case D3D11_RESOURCE_DIMENSION_TEXTURE3D: return "Texture3D"; } return "<unknown texture format>"; } static LPCSTR GetSRVDimensionNameFromEnum(D3D11_SRV_DIMENSION ViewDimension) { switch (ViewDimension) { case D3D11_SRV_DIMENSION_BUFFER: case D3D11_SRV_DIMENSION_BUFFEREX: return "Buffer"; case D3D11_SRV_DIMENSION_TEXTURE1D: return "Texture1D"; case D3D11_SRV_DIMENSION_TEXTURE1DARRAY: return "Texture1DArray"; case D3D11_SRV_DIMENSION_TEXTURE2D: return "Texture2D"; case D3D11_SRV_DIMENSION_TEXTURE2DARRAY: return "Texture2DArray"; case D3D11_SRV_DIMENSION_TEXTURE2DMS: return "Texture2DMS"; case D3D11_SRV_DIMENSION_TEXTURE2DMSARRAY: return "Texture2DMSArray"; case D3D11_SRV_DIMENSION_TEXTURE3D: return "Texture3D"; case D3D11_SRV_DIMENSION_TEXTURECUBE: return "TextureCube"; } return "<unknown texture format>"; } static LPCSTR GetUAVDimensionNameFromEnum(D3D11_UAV_DIMENSION ViewDimension) { switch (ViewDimension) { case D3D11_UAV_DIMENSION_BUFFER: return "Buffer"; case D3D11_UAV_DIMENSION_TEXTURE1D: return "RWTexture1D"; case D3D11_UAV_DIMENSION_TEXTURE1DARRAY: return "RWTexture1DArray"; case D3D11_UAV_DIMENSION_TEXTURE2D: return "RWTexture2D"; case D3D11_UAV_DIMENSION_TEXTURE2DARRAY: return "RWTexture2DArray"; case D3D11_UAV_DIMENSION_TEXTURE3D: return "RWTexture3D"; } return "<unknown texture format>"; } static LPCSTR GetRTVDimensionNameFromEnum(D3D11_RTV_DIMENSION ViewDimension) { switch (ViewDimension) { case D3D11_RTV_DIMENSION_BUFFER: return "Buffer"; case D3D11_RTV_DIMENSION_TEXTURE1D: return "Texture1D"; case D3D11_RTV_DIMENSION_TEXTURE1DARRAY: return "Texture1DArray"; case D3D11_RTV_DIMENSION_TEXTURE2D: return "Texture2D"; case D3D11_RTV_DIMENSION_TEXTURE2DARRAY: return "Texture2DArray"; case D3D11_RTV_DIMENSION_TEXTURE2DMS: return "Texture2DMS"; case D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY: return "Texture2DMSArray"; case D3D11_RTV_DIMENSION_TEXTURE3D: return "Texture3D"; } return "<unknown texture format>"; } static LPCSTR GetDSVDimensionNameFromEnum(D3D11_DSV_DIMENSION ViewDimension) { switch (ViewDimension) { case D3D11_DSV_DIMENSION_TEXTURE1D: return "Texture1D"; case D3D11_DSV_DIMENSION_TEXTURE1DARRAY: return "Texture1DArray"; case D3D11_DSV_DIMENSION_TEXTURE2D: return "Texture2D"; case D3D11_DSV_DIMENSION_TEXTURE2DARRAY: return "Texture2DArray"; case D3D11_DSV_DIMENSION_TEXTURE2DMS: return "Texture2DMS"; case D3D11_DSV_DIMENSION_TEXTURE2DMSARRAY: return "Texture2DMSArray"; } return "<unknown texture format>"; } static HRESULT ValidateTextureType(ID3D11ShaderResourceView *pView, EObjectType ObjectType, LPCSTR pFuncName) { if (NULL != pView) { D3D11_SHADER_RESOURCE_VIEW_DESC desc; pView->GetDesc(&desc); switch (ObjectType) { case EOT_Texture: if (desc.ViewDimension != D3D11_SRV_DIMENSION_BUFFER && desc.ViewDimension != D3D11_SRV_DIMENSION_BUFFEREX) return S_OK; break; case EOT_Buffer: if (desc.ViewDimension != D3D11_SRV_DIMENSION_BUFFER && desc.ViewDimension != D3D11_SRV_DIMENSION_BUFFEREX) break; if (desc.ViewDimension == D3D11_SRV_DIMENSION_BUFFEREX && (desc.BufferEx.Flags & D3D11_BUFFEREX_SRV_FLAG_RAW)) { DPF(0, "%s: Resource type mismatch; %s expected, ByteAddressBuffer provided.", pFuncName, GetTextureTypeNameFromEnum(ObjectType)); return E_INVALIDARG; } else { ID3D11Buffer* pBuffer = NULL; pView->GetResource( (ID3D11Resource**)&pBuffer ); D3DXASSERT( pBuffer != NULL ); D3D11_BUFFER_DESC BufDesc; pBuffer->GetDesc( &BufDesc ); SAFE_RELEASE( pBuffer ); if( BufDesc.MiscFlags & D3D11_RESOURCE_MISC_BUFFER_STRUCTURED ) { DPF(0, "%s: Resource type mismatch; %s expected, StructuredBuffer provided.", pFuncName, GetTextureTypeNameFromEnum(ObjectType)); return E_INVALIDARG; } else { return S_OK; } } break; case EOT_Texture1D: case EOT_Texture1DArray: if (desc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURE1D || desc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURE1DARRAY) return S_OK; break; case EOT_Texture2D: case EOT_Texture2DArray: if (desc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURE2D || desc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURE2DARRAY) return S_OK; break; case EOT_Texture2DMS: case EOT_Texture2DMSArray: if (desc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURE2DMS || desc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURE2DMSARRAY) return S_OK; break; case EOT_Texture3D: if (desc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURE3D) return S_OK; break; case EOT_TextureCube: case EOT_TextureCubeArray: if (desc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURECUBE || desc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURECUBEARRAY) return S_OK; break; case EOT_ByteAddressBuffer: if (desc.ViewDimension == D3D11_SRV_DIMENSION_BUFFEREX && (desc.BufferEx.Flags & D3D11_BUFFEREX_SRV_FLAG_RAW)) return S_OK; break; case EOT_StructuredBuffer: if (desc.ViewDimension == D3D11_SRV_DIMENSION_BUFFEREX || desc.ViewDimension == D3D11_SRV_DIMENSION_BUFFER) { ID3D11Buffer* pBuffer = NULL; pView->GetResource( (ID3D11Resource**)&pBuffer ); D3DXASSERT( pBuffer != NULL ); D3D11_BUFFER_DESC BufDesc; pBuffer->GetDesc( &BufDesc ); SAFE_RELEASE( pBuffer ); if( BufDesc.MiscFlags & D3D11_RESOURCE_MISC_BUFFER_STRUCTURED ) { return S_OK; } else { DPF(0, "%s: Resource type mismatch; %s expected, non-structured Buffer provided.", pFuncName, GetTextureTypeNameFromEnum(ObjectType)); return E_INVALIDARG; } } break; default: D3DXASSERT(0); // internal error, should never get here return E_FAIL; } DPF(0, "%s: Resource type mismatch; %s expected, %s provided.", pFuncName, GetTextureTypeNameFromEnum(ObjectType), GetSRVDimensionNameFromEnum(desc.ViewDimension)); return E_INVALIDARG; } return S_OK; } template<typename IBaseInterface> HRESULT TShaderResourceVariable<IBaseInterface>::SetResource(ID3D11ShaderResourceView *pResource) { HRESULT hr = S_OK; #ifdef _DEBUG LPCSTR pFuncName = "ID3DX11EffectShaderResourceVariable::SetResource"; VH(ValidateTextureType(pResource, pType->ObjectType, pFuncName)); #endif // Texture variables don't need to be dirtied. SAFE_ADDREF(pResource); SAFE_RELEASE(Data.pShaderResource->pShaderResource); Data.pShaderResource->pShaderResource = pResource; lExit: return hr; } template<typename IBaseInterface> HRESULT TShaderResourceVariable<IBaseInterface>::GetResource(ID3D11ShaderResourceView **ppResource) { HRESULT hr = S_OK; #ifdef _DEBUG LPCSTR pFuncName = "ID3DX11EffectShaderResourceVariable::GetResource"; VERIFYPARAMETER(ppResource); #endif *ppResource = Data.pShaderResource->pShaderResource; SAFE_ADDREF(*ppResource); lExit: return hr; } template<typename IBaseInterface> HRESULT TShaderResourceVariable<IBaseInterface>::SetResourceArray(ID3D11ShaderResourceView **ppResources, UINT Offset, UINT Count) { LPCSTR pFuncName = "ID3DX11EffectShaderResourceVariable::SetResourceArray"; UINT i; CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, ppResources); #ifdef _DEBUG for (i = 0; i < Count; ++ i) { VH(ValidateTextureType(ppResources[i], pType->ObjectType, pFuncName)); } #endif // Texture variables don't need to be dirtied. for (i = 0; i < Count; ++ i) { SShaderResource *pResourceBlock = Data.pShaderResource + Offset + i; SAFE_ADDREF(ppResources[i]); SAFE_RELEASE(pResourceBlock->pShaderResource); pResourceBlock->pShaderResource = ppResources[i]; } lExit: return hr; } template<typename IBaseInterface> HRESULT TShaderResourceVariable<IBaseInterface>::GetResourceArray(ID3D11ShaderResourceView **ppResources, UINT Offset, UINT Count) { LPCSTR pFuncName = "ID3DX11EffectShaderResourceVariable::GetResourceArray"; CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, ppResources); UINT i; for (i = 0; i < Count; ++ i) { ppResources[i] = (Data.pShaderResource + Offset + i)->pShaderResource; SAFE_ADDREF(ppResources[i]); } lExit: return hr; } ////////////////////////////////////////////////////////////////////////// // ID3DX11EffectUnorderedAccessViewVariable (TUnorderedAccessViewVariable implementation) ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TUnorderedAccessViewVariable : public IBaseInterface { STDMETHOD(SetUnorderedAccessView)(ID3D11UnorderedAccessView *pResource); STDMETHOD(GetUnorderedAccessView)(ID3D11UnorderedAccessView **ppResource); STDMETHOD(SetUnorderedAccessViewArray)(ID3D11UnorderedAccessView **ppResources, UINT Offset, UINT Count); STDMETHOD(GetUnorderedAccessViewArray)(ID3D11UnorderedAccessView **ppResources, UINT Offset, UINT Count); }; static HRESULT ValidateTextureType(ID3D11UnorderedAccessView *pView, EObjectType ObjectType, LPCSTR pFuncName) { if (NULL != pView) { D3D11_UNORDERED_ACCESS_VIEW_DESC desc; pView->GetDesc(&desc); switch (ObjectType) { case EOT_RWBuffer: if (desc.ViewDimension != D3D11_UAV_DIMENSION_BUFFER) break; if (desc.Buffer.Flags & D3D11_BUFFER_UAV_FLAG_RAW) { DPF(0, "%s: Resource type mismatch; %s expected, RWByteAddressBuffer provided.", pFuncName, GetTextureTypeNameFromEnum(ObjectType)); return E_INVALIDARG; } else { ID3D11Buffer* pBuffer = NULL; pView->GetResource( (ID3D11Resource**)&pBuffer ); D3DXASSERT( pBuffer != NULL ); D3D11_BUFFER_DESC BufDesc; pBuffer->GetDesc( &BufDesc ); SAFE_RELEASE( pBuffer ); if( BufDesc.MiscFlags & D3D11_RESOURCE_MISC_BUFFER_STRUCTURED ) { DPF(0, "%s: Resource type mismatch; %s expected, an RWStructuredBuffer provided.", pFuncName, GetTextureTypeNameFromEnum(ObjectType)); return E_INVALIDARG; } else { return S_OK; } } break; case EOT_RWTexture1D: case EOT_RWTexture1DArray: if (desc.ViewDimension == D3D11_UAV_DIMENSION_TEXTURE1D || desc.ViewDimension == D3D11_UAV_DIMENSION_TEXTURE1DARRAY) return S_OK; break; case EOT_RWTexture2D: case EOT_RWTexture2DArray: if (desc.ViewDimension == D3D11_UAV_DIMENSION_TEXTURE2D || desc.ViewDimension == D3D11_UAV_DIMENSION_TEXTURE2DARRAY) return S_OK; break; case EOT_RWTexture3D: if (desc.ViewDimension == D3D11_UAV_DIMENSION_TEXTURE3D) return S_OK; break; case EOT_RWByteAddressBuffer: if (desc.ViewDimension == D3D11_UAV_DIMENSION_BUFFER && (desc.Buffer.Flags & D3D11_BUFFER_UAV_FLAG_RAW)) return S_OK; break; case EOT_RWStructuredBuffer: if (desc.ViewDimension == D3D11_UAV_DIMENSION_BUFFER) { ID3D11Buffer* pBuffer = NULL; pView->GetResource( (ID3D11Resource**)&pBuffer ); D3DXASSERT( pBuffer != NULL ); D3D11_BUFFER_DESC BufDesc; pBuffer->GetDesc( &BufDesc ); SAFE_RELEASE( pBuffer ); if( BufDesc.MiscFlags & D3D11_RESOURCE_MISC_BUFFER_STRUCTURED ) { return S_OK; } else { DPF(0, "%s: Resource type mismatch; %s expected, non-structured Buffer provided.", pFuncName, GetTextureTypeNameFromEnum(ObjectType)); return E_INVALIDARG; } } break; case EOT_RWStructuredBufferAlloc: case EOT_RWStructuredBufferConsume: if (desc.ViewDimension != D3D11_UAV_DIMENSION_BUFFER) break; if (desc.Buffer.Flags & D3D11_BUFFER_UAV_FLAG_COUNTER) { return S_OK; } else { DPF(0, "%s: Resource type mismatch; %s expected, non-Counter buffer provided.", pFuncName, GetTextureTypeNameFromEnum(ObjectType)); return E_INVALIDARG; } break; case EOT_AppendStructuredBuffer: case EOT_ConsumeStructuredBuffer: if (desc.ViewDimension != D3D11_UAV_DIMENSION_BUFFER) break; if (desc.Buffer.Flags & D3D11_BUFFER_UAV_FLAG_APPEND) { return S_OK; } else { DPF(0, "%s: Resource type mismatch; %s expected, non-Append buffer provided.", pFuncName, GetTextureTypeNameFromEnum(ObjectType)); return E_INVALIDARG; } break; default: D3DXASSERT(0); // internal error, should never get here return E_FAIL; } DPF(0, "%s: Resource type mismatch; %s expected, %s provided.", pFuncName, GetTextureTypeNameFromEnum(ObjectType), GetUAVDimensionNameFromEnum(desc.ViewDimension)); return E_INVALIDARG; } return S_OK; } template<typename IBaseInterface> HRESULT TUnorderedAccessViewVariable<IBaseInterface>::SetUnorderedAccessView(ID3D11UnorderedAccessView *pResource) { HRESULT hr = S_OK; #ifdef _DEBUG LPCSTR pFuncName = "ID3DX11EffectUnorderedAccessViewVariable::SetUnorderedAccessView"; VH(ValidateTextureType(pResource, pType->ObjectType, pFuncName)); #endif // UAV variables don't need to be dirtied. SAFE_ADDREF(pResource); SAFE_RELEASE(Data.pUnorderedAccessView->pUnorderedAccessView); Data.pUnorderedAccessView->pUnorderedAccessView = pResource; lExit: return hr; } template<typename IBaseInterface> HRESULT TUnorderedAccessViewVariable<IBaseInterface>::GetUnorderedAccessView(ID3D11UnorderedAccessView **ppResource) { HRESULT hr = S_OK; #ifdef _DEBUG LPCSTR pFuncName = "ID3DX11EffectUnorderedAccessViewVariable::GetUnorderedAccessView"; VERIFYPARAMETER(ppResource); #endif *ppResource = Data.pUnorderedAccessView->pUnorderedAccessView; SAFE_ADDREF(*ppResource); lExit: return hr; } template<typename IBaseInterface> HRESULT TUnorderedAccessViewVariable<IBaseInterface>::SetUnorderedAccessViewArray(ID3D11UnorderedAccessView **ppResources, UINT Offset, UINT Count) { LPCSTR pFuncName = "ID3DX11EffectUnorderedAccessViewVariable::SetUnorderedAccessViewArray"; UINT i; CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, ppResources); #ifdef _DEBUG for (i = 0; i < Count; ++ i) { VH(ValidateTextureType(ppResources[i], pType->ObjectType, pFuncName)); } #endif // Texture variables don't need to be dirtied. for (i = 0; i < Count; ++ i) { SUnorderedAccessView *pResourceBlock = Data.pUnorderedAccessView + Offset + i; SAFE_ADDREF(ppResources[i]); SAFE_RELEASE(pResourceBlock->pUnorderedAccessView); pResourceBlock->pUnorderedAccessView = ppResources[i]; } lExit: return hr; } template<typename IBaseInterface> HRESULT TUnorderedAccessViewVariable<IBaseInterface>::GetUnorderedAccessViewArray(ID3D11UnorderedAccessView **ppResources, UINT Offset, UINT Count) { LPCSTR pFuncName = "ID3DX11EffectUnorderedAccessViewVariable::GetUnorderedAccessViewArray"; CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, ppResources); UINT i; for (i = 0; i < Count; ++ i) { ppResources[i] = (Data.pUnorderedAccessView + Offset + i)->pUnorderedAccessView; SAFE_ADDREF(ppResources[i]); } lExit: return hr; } ////////////////////////////////////////////////////////////////////////// // ID3DX11EffectRenderTargetViewVariable (TRenderTargetViewVariable implementation) ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TRenderTargetViewVariable : public IBaseInterface { STDMETHOD(SetRenderTarget)(ID3D11RenderTargetView *pResource); STDMETHOD(GetRenderTarget)(ID3D11RenderTargetView **ppResource); STDMETHOD(SetRenderTargetArray)(ID3D11RenderTargetView **ppResources, UINT Offset, UINT Count); STDMETHOD(GetRenderTargetArray)(ID3D11RenderTargetView **ppResources, UINT Offset, UINT Count); }; template<typename IBaseInterface> HRESULT TRenderTargetViewVariable<IBaseInterface>::SetRenderTarget(ID3D11RenderTargetView *pResource) { HRESULT hr = S_OK; #ifdef _DEBUG LPCSTR pFuncName = "ID3DX11EffectRenderTargetVariable::SetRenderTarget"; #endif // Texture variables don't need to be dirtied. SAFE_ADDREF(pResource); SAFE_RELEASE(Data.pRenderTargetView->pRenderTargetView); Data.pRenderTargetView->pRenderTargetView = pResource; lExit: return hr; } template<typename IBaseInterface> HRESULT TRenderTargetViewVariable<IBaseInterface>::GetRenderTarget(ID3D11RenderTargetView **ppResource) { HRESULT hr = S_OK; *ppResource = Data.pRenderTargetView->pRenderTargetView; SAFE_ADDREF(*ppResource); lExit: return hr; } template<typename IBaseInterface> HRESULT TRenderTargetViewVariable<IBaseInterface>::SetRenderTargetArray(ID3D11RenderTargetView **ppResources, UINT Offset, UINT Count) { LPCSTR pFuncName = "ID3DX11EffectRenderTargetVariable::SetRenderTargetArray"; UINT i; CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, ppResources); // Texture variables don't need to be dirtied. for (i = 0; i < Count; ++ i) { SRenderTargetView *pResourceBlock = Data.pRenderTargetView + Offset + i; SAFE_ADDREF(ppResources[i]); SAFE_RELEASE(pResourceBlock->pRenderTargetView); pResourceBlock->pRenderTargetView = ppResources[i]; } lExit: return hr; } template<typename IBaseInterface> HRESULT TRenderTargetViewVariable<IBaseInterface>::GetRenderTargetArray(ID3D11RenderTargetView **ppResources, UINT Offset, UINT Count) { LPCSTR pFuncName = "ID3DX11EffectRenderTargetVariable::GetRenderTargetArray"; CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, ppResources); UINT i; for (i = 0; i < Count; ++ i) { ppResources[i] = (Data.pRenderTargetView + Offset + i)->pRenderTargetView; SAFE_ADDREF(ppResources[i]); } lExit: return hr; } ////////////////////////////////////////////////////////////////////////// // ID3DX11EffectDepthStencilViewVariable (TDepthStencilViewVariable implementation) ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TDepthStencilViewVariable : public IBaseInterface { STDMETHOD(SetDepthStencil)(ID3D11DepthStencilView *pResource); STDMETHOD(GetDepthStencil)(ID3D11DepthStencilView **ppResource); STDMETHOD(SetDepthStencilArray)(ID3D11DepthStencilView **ppResources, UINT Offset, UINT Count); STDMETHOD(GetDepthStencilArray)(ID3D11DepthStencilView **ppResources, UINT Offset, UINT Count); }; template<typename IBaseInterface> HRESULT TDepthStencilViewVariable<IBaseInterface>::SetDepthStencil(ID3D11DepthStencilView *pResource) { HRESULT hr = S_OK; #ifdef _DEBUG LPCSTR pFuncName = "ID3D11DepthStencilViewVariable::SetDepthStencil"; #endif // Texture variables don't need to be dirtied. SAFE_ADDREF(pResource); SAFE_RELEASE(Data.pDepthStencilView->pDepthStencilView); Data.pDepthStencilView->pDepthStencilView = pResource; lExit: return hr; } template<typename IBaseInterface> HRESULT TDepthStencilViewVariable<IBaseInterface>::GetDepthStencil(ID3D11DepthStencilView **ppResource) { HRESULT hr = S_OK; #ifdef _DEBUG LPCSTR pFuncName = "ID3D11DepthStencilViewVariable::GetDepthStencil"; VERIFYPARAMETER(ppResource); #endif *ppResource = Data.pDepthStencilView->pDepthStencilView; SAFE_ADDREF(*ppResource); lExit: return hr; } template<typename IBaseInterface> HRESULT TDepthStencilViewVariable<IBaseInterface>::SetDepthStencilArray(ID3D11DepthStencilView **ppResources, UINT Offset, UINT Count) { LPCSTR pFuncName = "ID3D11DepthStencilViewVariable::SetDepthStencilArray"; UINT i; CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, ppResources); // Texture variables don't need to be dirtied. for (i = 0; i < Count; ++ i) { SDepthStencilView *pResourceBlock = Data.pDepthStencilView + Offset + i; SAFE_ADDREF(ppResources[i]); SAFE_RELEASE(pResourceBlock->pDepthStencilView); pResourceBlock->pDepthStencilView = ppResources[i]; } lExit: return hr; } template<typename IBaseInterface> HRESULT TDepthStencilViewVariable<IBaseInterface>::GetDepthStencilArray(ID3D11DepthStencilView **ppResources, UINT Offset, UINT Count) { LPCSTR pFuncName = "ID3D11DepthStencilViewVariable::GetDepthStencilArray"; CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, ppResources); UINT i; for (i = 0; i < Count; ++ i) { ppResources[i] = (Data.pDepthStencilView + Offset + i)->pDepthStencilView; SAFE_ADDREF(ppResources[i]); } lExit: return hr; } //////////////////////////////////////////////////////////////////////////////// // ID3DX11EffectShaderVariable (TShaderVariable implementation) //////////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TShaderVariable : public IBaseInterface { STDMETHOD(GetShaderDesc)(UINT ShaderIndex, D3DX11_EFFECT_SHADER_DESC *pDesc); STDMETHOD(GetVertexShader)(UINT ShaderIndex, ID3D11VertexShader **ppVS); STDMETHOD(GetGeometryShader)(UINT ShaderIndex, ID3D11GeometryShader **ppGS); STDMETHOD(GetPixelShader)(UINT ShaderIndex, ID3D11PixelShader **ppPS); STDMETHOD(GetHullShader)(UINT ShaderIndex, ID3D11HullShader **ppPS); STDMETHOD(GetDomainShader)(UINT ShaderIndex, ID3D11DomainShader **ppPS); STDMETHOD(GetComputeShader)(UINT ShaderIndex, ID3D11ComputeShader **ppPS); STDMETHOD(GetInputSignatureElementDesc)(UINT ShaderIndex, UINT Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc); STDMETHOD(GetOutputSignatureElementDesc)(UINT ShaderIndex, UINT Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc); STDMETHOD(GetPatchConstantSignatureElementDesc)(UINT ShaderIndex, UINT Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc); STDMETHOD_(BOOL, IsValid)(); }; template<typename IBaseInterface> HRESULT TShaderVariable<IBaseInterface>::GetShaderDesc(UINT ShaderIndex, D3DX11_EFFECT_SHADER_DESC *pDesc) { LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetShaderDesc"; CHECK_OBJECT_SCALAR_BOUNDS(ShaderIndex, pDesc); Data.pShader[ShaderIndex].GetShaderDesc(pDesc, FALSE); lExit: return hr; } template<typename IBaseInterface> HRESULT TShaderVariable<IBaseInterface>::GetVertexShader(UINT ShaderIndex, ID3D11VertexShader **ppVS) { LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetVertexShader"; CHECK_OBJECT_SCALAR_BOUNDS(ShaderIndex, ppVS); VH( Data.pShader[ShaderIndex].GetVertexShader(ppVS) ); lExit: return hr; } template<typename IBaseInterface> HRESULT TShaderVariable<IBaseInterface>::GetGeometryShader(UINT ShaderIndex, ID3D11GeometryShader **ppGS) { LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetGeometryShader"; CHECK_OBJECT_SCALAR_BOUNDS(ShaderIndex, ppGS); VH( Data.pShader[ShaderIndex].GetGeometryShader(ppGS) ); lExit: return hr; } template<typename IBaseInterface> HRESULT TShaderVariable<IBaseInterface>::GetPixelShader(UINT ShaderIndex, ID3D11PixelShader **ppPS) { LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetPixelShader"; CHECK_OBJECT_SCALAR_BOUNDS(ShaderIndex, ppPS); VH( Data.pShader[ShaderIndex].GetPixelShader(ppPS) ); lExit: return hr; } template<typename IBaseInterface> HRESULT TShaderVariable<IBaseInterface>::GetHullShader(UINT ShaderIndex, ID3D11HullShader **ppHS) { LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetHullShader"; CHECK_OBJECT_SCALAR_BOUNDS(ShaderIndex, ppHS); VH( Data.pShader[ShaderIndex].GetHullShader(ppHS) ); lExit: return hr; } template<typename IBaseInterface> HRESULT TShaderVariable<IBaseInterface>::GetDomainShader(UINT ShaderIndex, ID3D11DomainShader **ppDS) { LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetDomainShader"; CHECK_OBJECT_SCALAR_BOUNDS(ShaderIndex, ppDS); VH( Data.pShader[ShaderIndex].GetDomainShader(ppDS) ); lExit: return hr; } template<typename IBaseInterface> HRESULT TShaderVariable<IBaseInterface>::GetComputeShader(UINT ShaderIndex, ID3D11ComputeShader **ppCS) { LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetComputeShader"; CHECK_OBJECT_SCALAR_BOUNDS(ShaderIndex, ppCS); VH( Data.pShader[ShaderIndex].GetComputeShader(ppCS) ); lExit: return hr; } template<typename IBaseInterface> HRESULT TShaderVariable<IBaseInterface>::GetInputSignatureElementDesc(UINT ShaderIndex, UINT Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc) { LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetInputSignatureElementDesc"; CHECK_OBJECT_SCALAR_BOUNDS(ShaderIndex, pDesc); VH( Data.pShader[ShaderIndex].GetSignatureElementDesc(SShaderBlock::ST_Input, Element, pDesc) ); lExit: return hr; } template<typename IBaseInterface> HRESULT TShaderVariable<IBaseInterface>::GetOutputSignatureElementDesc(UINT ShaderIndex, UINT Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc) { LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetOutputSignatureElementDesc"; CHECK_OBJECT_SCALAR_BOUNDS(ShaderIndex, pDesc); VH( Data.pShader[ShaderIndex].GetSignatureElementDesc(SShaderBlock::ST_Output, Element, pDesc) ); lExit: return hr; } template<typename IBaseInterface> HRESULT TShaderVariable<IBaseInterface>::GetPatchConstantSignatureElementDesc(UINT ShaderIndex, UINT Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc) { LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetPatchConstantSignatureElementDesc"; CHECK_OBJECT_SCALAR_BOUNDS(ShaderIndex, pDesc); VH( Data.pShader[ShaderIndex].GetSignatureElementDesc(SShaderBlock::ST_PatchConstant, Element, pDesc) ); lExit: return hr; } template<typename IBaseInterface> BOOL TShaderVariable<IBaseInterface>::IsValid() { UINT numElements = IsArray()? pType->Elements : 1; BOOL valid = TRUE; while( numElements > 0 && ( valid = Data.pShader[ numElements-1 ].IsValid ) ) numElements--; return valid; } //////////////////////////////////////////////////////////////////////////////// // ID3DX11EffectBlendVariable (TBlendVariable implementation) //////////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TBlendVariable : public IBaseInterface { public: STDMETHOD(GetBlendState)(UINT Index, ID3D11BlendState **ppBlendState); STDMETHOD(SetBlendState)(UINT Index, ID3D11BlendState *pBlendState); STDMETHOD(UndoSetBlendState)(UINT Index); STDMETHOD(GetBackingStore)(UINT Index, D3D11_BLEND_DESC *pBlendDesc); STDMETHOD_(BOOL, IsValid)(); }; template<typename IBaseInterface> HRESULT TBlendVariable<IBaseInterface>::GetBlendState(UINT Index, ID3D11BlendState **ppBlendState) { LPCSTR pFuncName = "ID3DX11EffectBlendVariable::GetBlendState"; CHECK_OBJECT_SCALAR_BOUNDS(Index, ppBlendState); *ppBlendState = Data.pBlend[Index].pBlendObject; SAFE_ADDREF(*ppBlendState); lExit: return hr; } template<typename IBaseInterface> HRESULT TBlendVariable<IBaseInterface>::SetBlendState(UINT Index, ID3D11BlendState *pBlendState) { LPCSTR pFuncName = "ID3DX11EffectBlendState::SetBlendState"; CHECK_SCALAR_BOUNDS(Index); if( !Data.pBlend[Index].IsUserManaged ) { // Save original state object in case we UndoSet D3DXASSERT( pMemberData[Index].Type == MDT_BlendState ); VB( pMemberData[Index].Data.pD3DEffectsManagedBlendState == NULL ); pMemberData[Index].Data.pD3DEffectsManagedBlendState = Data.pBlend[Index].pBlendObject; Data.pBlend[Index].pBlendObject = NULL; Data.pBlend[Index].IsUserManaged = TRUE; } SAFE_ADDREF( pBlendState ); SAFE_RELEASE( Data.pBlend[Index].pBlendObject ); Data.pBlend[Index].pBlendObject = pBlendState; Data.pBlend[Index].IsValid = TRUE; lExit: return hr; } template<typename IBaseInterface> HRESULT TBlendVariable<IBaseInterface>::UndoSetBlendState(UINT Index) { LPCSTR pFuncName = "ID3DX11EffectBlendState::UndoSetBlendState"; CHECK_SCALAR_BOUNDS(Index); if( !Data.pBlend[Index].IsUserManaged ) { return S_FALSE; } // Revert to original state object SAFE_RELEASE( Data.pBlend[Index].pBlendObject ); Data.pBlend[Index].pBlendObject = pMemberData[Index].Data.pD3DEffectsManagedBlendState; pMemberData[Index].Data.pD3DEffectsManagedBlendState = NULL; Data.pBlend[Index].IsUserManaged = FALSE; lExit: return hr; } template<typename IBaseInterface> HRESULT TBlendVariable<IBaseInterface>::GetBackingStore(UINT Index, D3D11_BLEND_DESC *pBlendDesc) { LPCSTR pFuncName = "ID3DX11EffectBlendVariable::GetBackingStore"; CHECK_OBJECT_SCALAR_BOUNDS(Index, pBlendDesc); if( Data.pBlend[Index].IsUserManaged ) { if( Data.pBlend[Index].pBlendObject ) { Data.pBlend[Index].pBlendObject->GetDesc( pBlendDesc ); } else { *pBlendDesc = CD3D11_BLEND_DESC( D3D11_DEFAULT ); } } else { SBlendBlock *pBlock = Data.pBlend + Index; if (pBlock->ApplyAssignments(GetTopLevelEntity()->pEffect)) { pBlock->pAssignments[0].LastRecomputedTime = 0; // Force a recreate of this block the next time ApplyRenderStateBlock is called } memcpy( pBlendDesc, &pBlock->BackingStore, sizeof(D3D11_BLEND_DESC) ); } lExit: return hr; } template<typename IBaseInterface> BOOL TBlendVariable<IBaseInterface>::IsValid() { UINT numElements = IsArray()? pType->Elements : 1; BOOL valid = TRUE; while( numElements > 0 && ( valid = Data.pBlend[ numElements-1 ].IsValid ) ) numElements--; return valid; } //////////////////////////////////////////////////////////////////////////////// // ID3DX11EffectDepthStencilVariable (TDepthStencilVariable implementation) //////////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TDepthStencilVariable : public IBaseInterface { public: STDMETHOD(GetDepthStencilState)(UINT Index, ID3D11DepthStencilState **ppDepthStencilState); STDMETHOD(SetDepthStencilState)(UINT Index, ID3D11DepthStencilState *pDepthStencilState); STDMETHOD(UndoSetDepthStencilState)(UINT Index); STDMETHOD(GetBackingStore)(UINT Index, D3D11_DEPTH_STENCIL_DESC *pDepthStencilDesc); STDMETHOD_(BOOL, IsValid)(); }; template<typename IBaseInterface> HRESULT TDepthStencilVariable<IBaseInterface>::GetDepthStencilState(UINT Index, ID3D11DepthStencilState **ppDepthStencilState) { LPCSTR pFuncName = "ID3DX11EffectDepthStencilVariable::GetDepthStencilState"; CHECK_OBJECT_SCALAR_BOUNDS(Index, ppDepthStencilState); *ppDepthStencilState = Data.pDepthStencil[Index].pDSObject; SAFE_ADDREF(*ppDepthStencilState); lExit: return hr; } template<typename IBaseInterface> HRESULT TDepthStencilVariable<IBaseInterface>::SetDepthStencilState(UINT Index, ID3D11DepthStencilState *pDepthStencilState) { LPCSTR pFuncName = "ID3DX11EffectDepthStencilState::SetDepthStencilState"; CHECK_SCALAR_BOUNDS(Index); if( !Data.pDepthStencil[Index].IsUserManaged ) { // Save original state object in case we UndoSet D3DXASSERT( pMemberData[Index].Type == MDT_DepthStencilState ); VB( pMemberData[Index].Data.pD3DEffectsManagedDepthStencilState == NULL ); pMemberData[Index].Data.pD3DEffectsManagedDepthStencilState = Data.pDepthStencil[Index].pDSObject; Data.pDepthStencil[Index].pDSObject = NULL; Data.pDepthStencil[Index].IsUserManaged = TRUE; } SAFE_ADDREF( pDepthStencilState ); SAFE_RELEASE( Data.pDepthStencil[Index].pDSObject ); Data.pDepthStencil[Index].pDSObject = pDepthStencilState; Data.pDepthStencil[Index].IsValid = TRUE; lExit: return hr; } template<typename IBaseInterface> HRESULT TDepthStencilVariable<IBaseInterface>::UndoSetDepthStencilState(UINT Index) { LPCSTR pFuncName = "ID3DX11EffectDepthStencilState::UndoSetDepthStencilState"; CHECK_SCALAR_BOUNDS(Index); if( !Data.pDepthStencil[Index].IsUserManaged ) { return S_FALSE; } // Revert to original state object SAFE_RELEASE( Data.pDepthStencil[Index].pDSObject ); Data.pDepthStencil[Index].pDSObject = pMemberData[Index].Data.pD3DEffectsManagedDepthStencilState; pMemberData[Index].Data.pD3DEffectsManagedDepthStencilState = NULL; Data.pDepthStencil[Index].IsUserManaged = FALSE; lExit: return hr; } template<typename IBaseInterface> HRESULT TDepthStencilVariable<IBaseInterface>::GetBackingStore(UINT Index, D3D11_DEPTH_STENCIL_DESC *pDepthStencilDesc) { LPCSTR pFuncName = "ID3DX11EffectDepthStencilVariable::GetBackingStore"; CHECK_OBJECT_SCALAR_BOUNDS(Index, pDepthStencilDesc); if( Data.pDepthStencil[Index].IsUserManaged ) { if( Data.pDepthStencil[Index].pDSObject ) { Data.pDepthStencil[Index].pDSObject->GetDesc( pDepthStencilDesc ); } else { *pDepthStencilDesc = CD3D11_DEPTH_STENCIL_DESC( D3D11_DEFAULT ); } } else { SDepthStencilBlock *pBlock = Data.pDepthStencil + Index; if (pBlock->ApplyAssignments(GetTopLevelEntity()->pEffect)) { pBlock->pAssignments[0].LastRecomputedTime = 0; // Force a recreate of this block the next time ApplyRenderStateBlock is called } memcpy(pDepthStencilDesc, &pBlock->BackingStore, sizeof(D3D11_DEPTH_STENCIL_DESC)); } lExit: return hr; } template<typename IBaseInterface> BOOL TDepthStencilVariable<IBaseInterface>::IsValid() { UINT numElements = IsArray()? pType->Elements : 1; BOOL valid = TRUE; while( numElements > 0 && ( valid = Data.pDepthStencil[ numElements-1 ].IsValid ) ) numElements--; return valid; } //////////////////////////////////////////////////////////////////////////////// // ID3DX11EffectRasterizerVariable (TRasterizerVariable implementation) //////////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TRasterizerVariable : public IBaseInterface { public: STDMETHOD(GetRasterizerState)(UINT Index, ID3D11RasterizerState **ppRasterizerState); STDMETHOD(SetRasterizerState)(UINT Index, ID3D11RasterizerState *pRasterizerState); STDMETHOD(UndoSetRasterizerState)(UINT Index); STDMETHOD(GetBackingStore)(UINT Index, D3D11_RASTERIZER_DESC *pRasterizerDesc); STDMETHOD_(BOOL, IsValid)(); }; template<typename IBaseInterface> HRESULT TRasterizerVariable<IBaseInterface>::GetRasterizerState(UINT Index, ID3D11RasterizerState **ppRasterizerState) { LPCSTR pFuncName = "ID3DX11EffectRasterizerVariable::GetRasterizerState"; CHECK_OBJECT_SCALAR_BOUNDS(Index, ppRasterizerState); *ppRasterizerState = Data.pRasterizer[Index].pRasterizerObject; SAFE_ADDREF(*ppRasterizerState); lExit: return hr; } template<typename IBaseInterface> HRESULT TRasterizerVariable<IBaseInterface>::SetRasterizerState(UINT Index, ID3D11RasterizerState *pRasterizerState) { LPCSTR pFuncName = "ID3DX11EffectRasterizerState::SetRasterizerState"; CHECK_SCALAR_BOUNDS(Index); if( !Data.pRasterizer[Index].IsUserManaged ) { // Save original state object in case we UndoSet D3DXASSERT( pMemberData[Index].Type == MDT_RasterizerState ); VB( pMemberData[Index].Data.pD3DEffectsManagedRasterizerState == NULL ); pMemberData[Index].Data.pD3DEffectsManagedRasterizerState = Data.pRasterizer[Index].pRasterizerObject; Data.pRasterizer[Index].pRasterizerObject = NULL; Data.pRasterizer[Index].IsUserManaged = TRUE; } SAFE_ADDREF( pRasterizerState ); SAFE_RELEASE( Data.pRasterizer[Index].pRasterizerObject ); Data.pRasterizer[Index].pRasterizerObject = pRasterizerState; Data.pRasterizer[Index].IsValid = TRUE; lExit: return hr; } template<typename IBaseInterface> HRESULT TRasterizerVariable<IBaseInterface>::UndoSetRasterizerState(UINT Index) { LPCSTR pFuncName = "ID3DX11EffectRasterizerState::UndoSetRasterizerState"; CHECK_SCALAR_BOUNDS(Index); if( !Data.pRasterizer[Index].IsUserManaged ) { return S_FALSE; } // Revert to original state object SAFE_RELEASE( Data.pRasterizer[Index].pRasterizerObject ); Data.pRasterizer[Index].pRasterizerObject = pMemberData[Index].Data.pD3DEffectsManagedRasterizerState; pMemberData[Index].Data.pD3DEffectsManagedRasterizerState = NULL; Data.pRasterizer[Index].IsUserManaged = FALSE; lExit: return hr; } template<typename IBaseInterface> HRESULT TRasterizerVariable<IBaseInterface>::GetBackingStore(UINT Index, D3D11_RASTERIZER_DESC *pRasterizerDesc) { LPCSTR pFuncName = "ID3DX11EffectRasterizerVariable::GetBackingStore"; CHECK_OBJECT_SCALAR_BOUNDS(Index, pRasterizerDesc); if( Data.pRasterizer[Index].IsUserManaged ) { if( Data.pRasterizer[Index].pRasterizerObject ) { Data.pRasterizer[Index].pRasterizerObject->GetDesc( pRasterizerDesc ); } else { *pRasterizerDesc = CD3D11_RASTERIZER_DESC( D3D11_DEFAULT ); } } else { SRasterizerBlock *pBlock = Data.pRasterizer + Index; if (pBlock->ApplyAssignments(GetTopLevelEntity()->pEffect)) { pBlock->pAssignments[0].LastRecomputedTime = 0; // Force a recreate of this block the next time ApplyRenderStateBlock is called } memcpy(pRasterizerDesc, &pBlock->BackingStore, sizeof(D3D11_RASTERIZER_DESC)); } lExit: return hr; } template<typename IBaseInterface> BOOL TRasterizerVariable<IBaseInterface>::IsValid() { UINT numElements = IsArray()? pType->Elements : 1; BOOL valid = TRUE; while( numElements > 0 && ( valid = Data.pRasterizer[ numElements-1 ].IsValid ) ) numElements--; return valid; } //////////////////////////////////////////////////////////////////////////////// // ID3DX11EffectSamplerVariable (TSamplerVariable implementation) //////////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TSamplerVariable : public IBaseInterface { public: STDMETHOD(GetSampler)(UINT Index, ID3D11SamplerState **ppSampler); STDMETHOD(SetSampler)(UINT Index, ID3D11SamplerState *pSampler); STDMETHOD(UndoSetSampler)(UINT Index); STDMETHOD(GetBackingStore)(UINT Index, D3D11_SAMPLER_DESC *pSamplerDesc); }; template<typename IBaseInterface> HRESULT TSamplerVariable<IBaseInterface>::GetSampler(UINT Index, ID3D11SamplerState **ppSampler) { LPCSTR pFuncName = "ID3DX11EffectSamplerVariable::GetSampler"; CHECK_OBJECT_SCALAR_BOUNDS(Index, ppSampler); *ppSampler = Data.pSampler[Index].pD3DObject; SAFE_ADDREF(*ppSampler); lExit: return hr; } template<typename IBaseInterface> HRESULT TSamplerVariable<IBaseInterface>::SetSampler(UINT Index, ID3D11SamplerState *pSampler) { LPCSTR pFuncName = "ID3DX11EffectSamplerState::SetSampler"; CHECK_SCALAR_BOUNDS(Index); // Replace all references to the old shader block with this one GetEffect()->ReplaceSamplerReference(&Data.pSampler[Index], pSampler); if( !Data.pSampler[Index].IsUserManaged ) { // Save original state object in case we UndoSet D3DXASSERT( pMemberData[Index].Type == MDT_SamplerState ); VB( pMemberData[Index].Data.pD3DEffectsManagedSamplerState == NULL ); pMemberData[Index].Data.pD3DEffectsManagedSamplerState = Data.pSampler[Index].pD3DObject; Data.pSampler[Index].pD3DObject = NULL; Data.pSampler[Index].IsUserManaged = TRUE; } SAFE_ADDREF( pSampler ); SAFE_RELEASE( Data.pSampler[Index].pD3DObject ); Data.pSampler[Index].pD3DObject = pSampler; lExit: return hr; } template<typename IBaseInterface> HRESULT TSamplerVariable<IBaseInterface>::UndoSetSampler(UINT Index) { LPCSTR pFuncName = "ID3DX11EffectSamplerState::UndoSetSampler"; CHECK_SCALAR_BOUNDS(Index); if( !Data.pSampler[Index].IsUserManaged ) { return S_FALSE; } // Replace all references to the old shader block with this one GetEffect()->ReplaceSamplerReference(&Data.pSampler[Index], pMemberData[Index].Data.pD3DEffectsManagedSamplerState); // Revert to original state object SAFE_RELEASE( Data.pSampler[Index].pD3DObject ); Data.pSampler[Index].pD3DObject = pMemberData[Index].Data.pD3DEffectsManagedSamplerState; pMemberData[Index].Data.pD3DEffectsManagedSamplerState = NULL; Data.pSampler[Index].IsUserManaged = FALSE; lExit: return hr; } template<typename IBaseInterface> HRESULT TSamplerVariable<IBaseInterface>::GetBackingStore(UINT Index, D3D11_SAMPLER_DESC *pSamplerDesc) { LPCSTR pFuncName = "ID3DX11EffectSamplerVariable::GetBackingStore"; CHECK_OBJECT_SCALAR_BOUNDS(Index, pSamplerDesc); if( Data.pSampler[Index].IsUserManaged ) { if( Data.pSampler[Index].pD3DObject ) { Data.pSampler[Index].pD3DObject->GetDesc( pSamplerDesc ); } else { *pSamplerDesc = CD3D11_SAMPLER_DESC( D3D11_DEFAULT ); } } else { SSamplerBlock *pBlock = Data.pSampler + Index; if (pBlock->ApplyAssignments(GetTopLevelEntity()->pEffect)) { pBlock->pAssignments[0].LastRecomputedTime = 0; // Force a recreate of this block the next time ApplyRenderStateBlock is called } memcpy(pSamplerDesc, &pBlock->BackingStore.SamplerDesc, sizeof(D3D11_SAMPLER_DESC)); } lExit: return hr; } //////////////////////////////////////////////////////////////////////////////// // TUncastableVariable //////////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TUncastableVariable : public IBaseInterface { STDMETHOD_(ID3DX11EffectScalarVariable*, AsScalar)(); STDMETHOD_(ID3DX11EffectVectorVariable*, AsVector)(); STDMETHOD_(ID3DX11EffectMatrixVariable*, AsMatrix)(); STDMETHOD_(ID3DX11EffectStringVariable*, AsString)(); STDMETHOD_(ID3DX11EffectClassInstanceVariable*, AsClassInstance)(); STDMETHOD_(ID3DX11EffectInterfaceVariable*, AsInterface)(); STDMETHOD_(ID3DX11EffectShaderResourceVariable*, AsShaderResource)(); STDMETHOD_(ID3DX11EffectUnorderedAccessViewVariable*, AsUnorderedAccessView)(); STDMETHOD_(ID3DX11EffectRenderTargetViewVariable*, AsRenderTargetView)(); STDMETHOD_(ID3DX11EffectDepthStencilViewVariable*, AsDepthStencilView)(); STDMETHOD_(ID3DX11EffectConstantBuffer*, AsConstantBuffer)(); STDMETHOD_(ID3DX11EffectShaderVariable*, AsShader)(); STDMETHOD_(ID3DX11EffectBlendVariable*, AsBlend)(); STDMETHOD_(ID3DX11EffectDepthStencilVariable*, AsDepthStencil)(); STDMETHOD_(ID3DX11EffectRasterizerVariable*, AsRasterizer)(); STDMETHOD_(ID3DX11EffectSamplerVariable*, AsSampler)(); }; template<typename IBaseInterface> ID3DX11EffectScalarVariable * TUncastableVariable<IBaseInterface>::AsScalar() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsScalar"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidScalarVariable; } template<typename IBaseInterface> ID3DX11EffectVectorVariable * TUncastableVariable<IBaseInterface>::AsVector() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsVector"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidVectorVariable; } template<typename IBaseInterface> ID3DX11EffectMatrixVariable * TUncastableVariable<IBaseInterface>::AsMatrix() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsMatrix"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidMatrixVariable; } template<typename IBaseInterface> ID3DX11EffectStringVariable * TUncastableVariable<IBaseInterface>::AsString() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsString"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidStringVariable; } template<typename IBaseClassInstance> ID3DX11EffectClassInstanceVariable * TUncastableVariable<IBaseClassInstance>::AsClassInstance() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsClassInstance"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidClassInstanceVariable; } template<typename IBaseInterface> ID3DX11EffectInterfaceVariable * TUncastableVariable<IBaseInterface>::AsInterface() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsInterface"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidInterfaceVariable; } template<typename IBaseInterface> ID3DX11EffectShaderResourceVariable * TUncastableVariable<IBaseInterface>::AsShaderResource() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsShaderResource"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidShaderResourceVariable; } template<typename IBaseInterface> ID3DX11EffectUnorderedAccessViewVariable * TUncastableVariable<IBaseInterface>::AsUnorderedAccessView() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsUnorderedAccessView"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidUnorderedAccessViewVariable; } template<typename IBaseInterface> ID3DX11EffectRenderTargetViewVariable * TUncastableVariable<IBaseInterface>::AsRenderTargetView() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsRenderTargetView"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidRenderTargetViewVariable; } template<typename IBaseInterface> ID3DX11EffectDepthStencilViewVariable * TUncastableVariable<IBaseInterface>::AsDepthStencilView() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsDepthStencilView"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidDepthStencilViewVariable; } template<typename IBaseInterface> ID3DX11EffectConstantBuffer * TUncastableVariable<IBaseInterface>::AsConstantBuffer() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsConstantBuffer"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidConstantBuffer; } template<typename IBaseInterface> ID3DX11EffectShaderVariable * TUncastableVariable<IBaseInterface>::AsShader() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsShader"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidShaderVariable; } template<typename IBaseInterface> ID3DX11EffectBlendVariable * TUncastableVariable<IBaseInterface>::AsBlend() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsBlend"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidBlendVariable; } template<typename IBaseInterface> ID3DX11EffectDepthStencilVariable * TUncastableVariable<IBaseInterface>::AsDepthStencil() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsDepthStencil"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidDepthStencilVariable; } template<typename IBaseInterface> ID3DX11EffectRasterizerVariable * TUncastableVariable<IBaseInterface>::AsRasterizer() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsRasterizer"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidRasterizerVariable; } template<typename IBaseInterface> ID3DX11EffectSamplerVariable * TUncastableVariable<IBaseInterface>::AsSampler() { LPCSTR pFuncName = "ID3DX11EffectVariable::AsSampler"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidSamplerVariable; } //////////////////////////////////////////////////////////////////////////////// // Macros to instantiate the myriad templates //////////////////////////////////////////////////////////////////////////////// // generates a global variable, annotation, global variable member, and annotation member of each struct type #define GenerateReflectionClasses(Type, BaseInterface) \ struct S##Type##GlobalVariable : public T##Type##Variable<TGlobalVariable<BaseInterface>, FALSE> { }; \ struct S##Type##Annotation : public T##Type##Variable<TAnnotation<BaseInterface>, TRUE> { }; \ struct S##Type##GlobalVariableMember : public T##Type##Variable<TVariable<TMember<BaseInterface> >, FALSE> { }; \ struct S##Type##AnnotationMember : public T##Type##Variable<TVariable<TMember<BaseInterface> >, TRUE> { }; #define GenerateVectorReflectionClasses(Type, BaseType, BaseInterface) \ struct S##Type##GlobalVariable : public TVectorVariable<TGlobalVariable<BaseInterface>, FALSE, BaseType> { }; \ struct S##Type##Annotation : public TVectorVariable<TAnnotation<BaseInterface>, TRUE, BaseType> { }; \ struct S##Type##GlobalVariableMember : public TVectorVariable<TVariable<TMember<BaseInterface> >, FALSE, BaseType> { }; \ struct S##Type##AnnotationMember : public TVectorVariable<TVariable<TMember<BaseInterface> >, TRUE, BaseType> { }; #define GenerateReflectionGlobalOnlyClasses(Type) \ struct S##Type##GlobalVariable : public T##Type##Variable<TGlobalVariable<ID3DX11Effect##Type##Variable> > { }; \ struct S##Type##GlobalVariableMember : public T##Type##Variable<TVariable<TMember<ID3DX11Effect##Type##Variable> > > { }; \ GenerateReflectionClasses(Numeric, ID3DX11EffectVariable); GenerateReflectionClasses(FloatScalar, ID3DX11EffectScalarVariable); GenerateReflectionClasses(IntScalar, ID3DX11EffectScalarVariable); GenerateReflectionClasses(BoolScalar, ID3DX11EffectScalarVariable); GenerateVectorReflectionClasses(FloatVector, ETVT_Float, ID3DX11EffectVectorVariable); GenerateVectorReflectionClasses(BoolVector, ETVT_Bool, ID3DX11EffectVectorVariable); GenerateVectorReflectionClasses(IntVector, ETVT_Int, ID3DX11EffectVectorVariable); GenerateReflectionClasses(Matrix, ID3DX11EffectMatrixVariable); GenerateReflectionClasses(String, ID3DX11EffectStringVariable); GenerateReflectionGlobalOnlyClasses(ClassInstance); GenerateReflectionGlobalOnlyClasses(Interface); GenerateReflectionGlobalOnlyClasses(ShaderResource); GenerateReflectionGlobalOnlyClasses(UnorderedAccessView); GenerateReflectionGlobalOnlyClasses(RenderTargetView); GenerateReflectionGlobalOnlyClasses(DepthStencilView); GenerateReflectionGlobalOnlyClasses(Shader); GenerateReflectionGlobalOnlyClasses(Blend); GenerateReflectionGlobalOnlyClasses(DepthStencil); GenerateReflectionGlobalOnlyClasses(Rasterizer); GenerateReflectionGlobalOnlyClasses(Sampler); // Optimized matrix classes struct SMatrix4x4ColumnMajorGlobalVariable : public TMatrix4x4Variable<TGlobalVariable<ID3DX11EffectMatrixVariable>, TRUE> { }; struct SMatrix4x4RowMajorGlobalVariable : public TMatrix4x4Variable<TGlobalVariable<ID3DX11EffectMatrixVariable>, FALSE> { }; struct SMatrix4x4ColumnMajorGlobalVariableMember : public TMatrix4x4Variable<TVariable<TMember<ID3DX11EffectMatrixVariable> >, TRUE> { }; struct SMatrix4x4RowMajorGlobalVariableMember : public TMatrix4x4Variable<TVariable<TMember<ID3DX11EffectMatrixVariable> >, FALSE> { }; // Optimized vector classes struct SFloatVector4GlobalVariable : public TVector4Variable<TGlobalVariable<ID3DX11EffectVectorVariable> > { }; struct SFloatVector4GlobalVariableMember : public TVector4Variable<TVariable<TMember<ID3DX11EffectVectorVariable> > > { }; // These 3 classes should never be used directly // The "base" global variable struct (all global variables should be the same size in bytes, // but we pick this as the default). struct SGlobalVariable : public TGlobalVariable<ID3DX11EffectVariable> { }; // The "base" annotation struct (all annotations should be the same size in bytes, // but we pick this as the default). struct SAnnotation : public TAnnotation<ID3DX11EffectVariable> { }; // The "base" variable member struct (all annotation/global variable members should be the // same size in bytes, but we pick this as the default). struct SMember : public TVariable<TMember<ID3DX11EffectVariable> > { }; // creates a new variable of the appropriate polymorphic type where pVar was HRESULT PlacementNewVariable(void *pVar, SType *pType, BOOL IsAnnotation); SMember * CreateNewMember(SType *pType, BOOL IsAnnotation);
163,903
55,584
// // Copyright (c) 2008-2014 the Urho3D project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "Precompiled.h" #include "Camera.h" #include "Geometry.h" #include "Graphics.h" #include "GraphicsImpl.h" #include "Material.h" #include "Node.h" #include "Renderer.h" #include "Profiler.h" #include "Scene.h" #include "ShaderVariation.h" #include "Sort.h" #include "Technique.h" #include "Texture2D.h" #include "VertexBuffer.h" #include "View.h" #include "Zone.h" #include "DebugNew.h" namespace Urho3D { inline bool CompareBatchesState(Batch* lhs, Batch* rhs) { if (lhs->sortKey_ != rhs->sortKey_) return lhs->sortKey_ < rhs->sortKey_; else return lhs->distance_ < rhs->distance_; } inline bool CompareBatchesFrontToBack(Batch* lhs, Batch* rhs) { if (lhs->distance_ != rhs->distance_) return lhs->distance_ < rhs->distance_; else return lhs->sortKey_ < rhs->sortKey_; } inline bool CompareBatchesBackToFront(Batch* lhs, Batch* rhs) { if (lhs->distance_ != rhs->distance_) return lhs->distance_ > rhs->distance_; else return lhs->sortKey_ < rhs->sortKey_; } inline bool CompareInstancesFrontToBack(const InstanceData& lhs, const InstanceData& rhs) { return lhs.distance_ < rhs.distance_; } void CalculateShadowMatrix(Matrix4& dest, LightBatchQueue* queue, unsigned split, Renderer* renderer, const Vector3& translation) { Camera* shadowCamera = queue->shadowSplits_[split].shadowCamera_; const IntRect& viewport = queue->shadowSplits_[split].shadowViewport_; Matrix3x4 posAdjust(translation, Quaternion::IDENTITY, 1.0f); Matrix3x4 shadowView(shadowCamera->GetView()); Matrix4 shadowProj(shadowCamera->GetProjection()); Matrix4 texAdjust(Matrix4::IDENTITY); Texture2D* shadowMap = queue->shadowMap_; if (!shadowMap) return; float width = (float)shadowMap->GetWidth(); float height = (float)shadowMap->GetHeight(); Vector2 offset( (float)viewport.left_ / width, (float)viewport.top_ / height ); Vector2 scale( 0.5f * (float)viewport.Width() / width, 0.5f * (float)viewport.Height() / height ); #ifdef URHO3D_OPENGL offset.x_ += scale.x_; offset.y_ += scale.y_; offset.y_ = 1.0f - offset.y_; // If using 4 shadow samples, offset the position diagonally by half pixel if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT) { offset.x_ -= 0.5f / width; offset.y_ -= 0.5f / height; } texAdjust.SetTranslation(Vector3(offset.x_, offset.y_, 0.5f)); texAdjust.SetScale(Vector3(scale.x_, scale.y_, 0.5f)); #else offset.x_ += scale.x_ + 0.5f / width; offset.y_ += scale.y_ + 0.5f / height; if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT) { offset.x_ -= 0.5f / width; offset.y_ -= 0.5f / height; } scale.y_ = -scale.y_; texAdjust.SetTranslation(Vector3(offset.x_, offset.y_, 0.0f)); texAdjust.SetScale(Vector3(scale.x_, scale.y_, 1.0f)); #endif dest = texAdjust * shadowProj * shadowView * posAdjust; } void CalculateSpotMatrix(Matrix4& dest, Light* light, const Vector3& translation) { Node* lightNode = light->GetNode(); Matrix3x4 posAdjust(translation, Quaternion::IDENTITY, 1.0f); Matrix3x4 spotView = Matrix3x4(lightNode->GetWorldPosition(), lightNode->GetWorldRotation(), 1.0f).Inverse(); Matrix4 spotProj(Matrix4::ZERO); Matrix4 texAdjust(Matrix4::IDENTITY); // Make the projected light slightly smaller than the shadow map to prevent light spill float h = 1.005f / tanf(light->GetFov() * M_DEGTORAD * 0.5f); float w = h / light->GetAspectRatio(); spotProj.m00_ = w; spotProj.m11_ = h; spotProj.m22_ = 1.0f / Max(light->GetRange(), M_EPSILON); spotProj.m32_ = 1.0f; #ifdef URHO3D_OPENGL texAdjust.SetTranslation(Vector3(0.5f, 0.5f, 0.5f)); texAdjust.SetScale(Vector3(0.5f, -0.5f, 0.5f)); #else texAdjust.SetTranslation(Vector3(0.5f, 0.5f, 0.0f)); texAdjust.SetScale(Vector3(0.5f, -0.5f, 1.0f)); #endif dest = texAdjust * spotProj * spotView * posAdjust; } void Batch::CalculateSortKey() { unsigned shaderID = ((*((unsigned*)&vertexShader_) / sizeof(ShaderVariation)) + (*((unsigned*)&pixelShader_) / sizeof(ShaderVariation))) & 0x3fff; if (!isBase_) shaderID |= 0x8000; if (pass_ && pass_->GetAlphaMask()) shaderID |= 0x4000; unsigned lightQueueID = (*((unsigned*)&lightQueue_) / sizeof(LightBatchQueue)) & 0xffff; unsigned materialID = (*((unsigned*)&material_) / sizeof(Material)) & 0xffff; unsigned geometryID = (*((unsigned*)&geometry_) / sizeof(Geometry)) & 0xffff; sortKey_ = (((unsigned long long)shaderID) << 48) | (((unsigned long long)lightQueueID) << 32) | (((unsigned long long)materialID) << 16) | geometryID; } void Batch::Prepare(View* view, bool setModelTransform) const { if (!vertexShader_ || !pixelShader_) return; Graphics* graphics = view->GetGraphics(); Renderer* renderer = view->GetRenderer(); Node* cameraNode = camera_ ? camera_->GetNode() : 0; Light* light = lightQueue_ ? lightQueue_->light_ : 0; Texture2D* shadowMap = lightQueue_ ? lightQueue_->shadowMap_ : 0; // Set pass / material-specific renderstates if (pass_ && material_) { bool isShadowPass = pass_->GetType() == PASS_SHADOW; BlendMode blend = pass_->GetBlendMode(); // Turn additive blending into subtract if the light is negative if (light && light->IsNegative()) { if (blend == BLEND_ADD) blend = BLEND_SUBTRACT; else if (blend == BLEND_ADDALPHA) blend = BLEND_SUBTRACTALPHA; } graphics->SetBlendMode(blend); renderer->SetCullMode(isShadowPass ? material_->GetShadowCullMode() : material_->GetCullMode(), camera_); if (!isShadowPass) { const BiasParameters& depthBias = material_->GetDepthBias(); graphics->SetDepthBias(depthBias.constantBias_, depthBias.slopeScaledBias_); } graphics->SetDepthTest(pass_->GetDepthTestMode()); graphics->SetDepthWrite(pass_->GetDepthWrite()); } // Set shaders first. The available shader parameters and their register/uniform positions depend on the currently set shaders graphics->SetShaders(vertexShader_, pixelShader_); // Set global (per-frame) shader parameters if (graphics->NeedParameterUpdate(SP_FRAME, (void*)0)) view->SetGlobalShaderParameters(); // Set camera shader parameters unsigned cameraHash = overrideView_ ? (unsigned)(size_t)camera_ + 4 : (unsigned)(size_t)camera_; if (graphics->NeedParameterUpdate(SP_CAMERA, reinterpret_cast<void*>(cameraHash))) view->SetCameraShaderParameters(camera_, true, overrideView_); // Set viewport shader parameters IntRect viewport = graphics->GetViewport(); IntVector2 viewSize = IntVector2(viewport.Width(), viewport.Height()); unsigned viewportHash = viewSize.x_ | (viewSize.y_ << 16); if (graphics->NeedParameterUpdate(SP_VIEWPORT, reinterpret_cast<void*>(viewportHash))) { // During renderpath commands the G-Buffer or viewport texture is assumed to always be viewport-sized view->SetGBufferShaderParameters(viewSize, IntRect(0, 0, viewSize.x_, viewSize.y_)); } // Set model or skinning transforms if (setModelTransform && graphics->NeedParameterUpdate(SP_OBJECTTRANSFORM, worldTransform_)) { if (geometryType_ == GEOM_SKINNED) { graphics->SetShaderParameter(VSP_SKINMATRICES, reinterpret_cast<const float*>(worldTransform_), 12 * numWorldTransforms_); } else graphics->SetShaderParameter(VSP_MODEL, *worldTransform_); // Set the orientation for billboards, either from the object itself or from the camera if (geometryType_ == GEOM_BILLBOARD) { if (numWorldTransforms_ > 1) graphics->SetShaderParameter(VSP_BILLBOARDROT, worldTransform_[1].RotationMatrix()); else graphics->SetShaderParameter(VSP_BILLBOARDROT, cameraNode->GetWorldRotation().RotationMatrix()); } } // Set zone-related shader parameters BlendMode blend = graphics->GetBlendMode(); // If the pass is additive, override fog color to black so that shaders do not need a separate additive path bool overrideFogColorToBlack = blend == BLEND_ADD || blend == BLEND_ADDALPHA; unsigned zoneHash = (unsigned)(size_t)zone_; if (overrideFogColorToBlack) zoneHash += 0x80000000; if (zone_ && graphics->NeedParameterUpdate(SP_ZONE, reinterpret_cast<void*>(zoneHash))) { graphics->SetShaderParameter(VSP_AMBIENTSTARTCOLOR, zone_->GetAmbientStartColor()); graphics->SetShaderParameter(VSP_AMBIENTENDCOLOR, zone_->GetAmbientEndColor().ToVector4() - zone_->GetAmbientStartColor().ToVector4()); const BoundingBox& box = zone_->GetBoundingBox(); Vector3 boxSize = box.Size(); Matrix3x4 adjust(Matrix3x4::IDENTITY); adjust.SetScale(Vector3(1.0f / boxSize.x_, 1.0f / boxSize.y_, 1.0f / boxSize.z_)); adjust.SetTranslation(Vector3(0.5f, 0.5f, 0.5f)); Matrix3x4 zoneTransform = adjust * zone_->GetInverseWorldTransform(); graphics->SetShaderParameter(VSP_ZONE, zoneTransform); graphics->SetShaderParameter(PSP_AMBIENTCOLOR, zone_->GetAmbientColor()); graphics->SetShaderParameter(PSP_FOGCOLOR, overrideFogColorToBlack ? Color::BLACK : zone_->GetFogColor()); float farClip = camera_->GetFarClip(); float fogStart = Min(zone_->GetFogStart(), farClip); float fogEnd = Min(zone_->GetFogEnd(), farClip); if (fogStart >= fogEnd * (1.0f - M_LARGE_EPSILON)) fogStart = fogEnd * (1.0f - M_LARGE_EPSILON); float fogRange = Max(fogEnd - fogStart, M_EPSILON); Vector4 fogParams(fogEnd / farClip, farClip / fogRange, 0.0f, 0.0f); Node* zoneNode = zone_->GetNode(); if (zone_->GetHeightFog() && zoneNode) { Vector3 worldFogHeightVec = zoneNode->GetWorldTransform() * Vector3(0.0f, zone_->GetFogHeight(), 0.0f); fogParams.z_ = worldFogHeightVec.y_; fogParams.w_ = zone_->GetFogHeightScale() / Max(zoneNode->GetWorldScale().y_, M_EPSILON); } graphics->SetShaderParameter(PSP_FOGPARAMS, fogParams); } // Set light-related shader parameters if (lightQueue_) { if (graphics->NeedParameterUpdate(SP_VERTEXLIGHTS, lightQueue_) && graphics->HasShaderParameter(VS, VSP_VERTEXLIGHTS)) { Vector4 vertexLights[MAX_VERTEX_LIGHTS * 3]; const PODVector<Light*>& lights = lightQueue_->vertexLights_; for (unsigned i = 0; i < lights.Size(); ++i) { Light* vertexLight = lights[i]; Node* vertexLightNode = vertexLight->GetNode(); LightType type = vertexLight->GetLightType(); // Attenuation float invRange, cutoff, invCutoff; if (type == LIGHT_DIRECTIONAL) invRange = 0.0f; else invRange = 1.0f / Max(vertexLight->GetRange(), M_EPSILON); if (type == LIGHT_SPOT) { cutoff = Cos(vertexLight->GetFov() * 0.5f); invCutoff = 1.0f / (1.0f - cutoff); } else { cutoff = -1.0f; invCutoff = 1.0f; } // Color float fade = 1.0f; float fadeEnd = vertexLight->GetDrawDistance(); float fadeStart = vertexLight->GetFadeDistance(); // Do fade calculation for light if both fade & draw distance defined if (vertexLight->GetLightType() != LIGHT_DIRECTIONAL && fadeEnd > 0.0f && fadeStart > 0.0f && fadeStart < fadeEnd) fade = Min(1.0f - (vertexLight->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 1.0f); Color color = vertexLight->GetEffectiveColor() * fade; vertexLights[i * 3] = Vector4(color.r_, color.g_, color.b_, invRange); // Direction vertexLights[i * 3 + 1] = Vector4(-(vertexLightNode->GetWorldDirection()), cutoff); // Position vertexLights[i * 3 + 2] = Vector4(vertexLightNode->GetWorldPosition(), invCutoff); } if (lights.Size()) graphics->SetShaderParameter(VSP_VERTEXLIGHTS, vertexLights[0].Data(), lights.Size() * 3 * 4); } } if (light && graphics->NeedParameterUpdate(SP_LIGHT, light)) { // Deferred light volume batches operate in a camera-centered space. Detect from material, zone & pass all being null bool isLightVolume = !material_ && !pass_ && !zone_; Matrix3x4 cameraEffectiveTransform = camera_->GetEffectiveWorldTransform(); Vector3 cameraEffectivePos = cameraEffectiveTransform.Translation(); Node* lightNode = light->GetNode(); Matrix3 lightWorldRotation = lightNode->GetWorldRotation().RotationMatrix(); graphics->SetShaderParameter(VSP_LIGHTDIR, lightWorldRotation * Vector3::BACK); float atten = 1.0f / Max(light->GetRange(), M_EPSILON); graphics->SetShaderParameter(VSP_LIGHTPOS, Vector4(lightNode->GetWorldPosition(), atten)); if (graphics->HasShaderParameter(VS, VSP_LIGHTMATRICES)) { switch (light->GetLightType()) { case LIGHT_DIRECTIONAL: { Matrix4 shadowMatrices[MAX_CASCADE_SPLITS]; unsigned numSplits = lightQueue_->shadowSplits_.Size(); for (unsigned i = 0; i < numSplits; ++i) CalculateShadowMatrix(shadowMatrices[i], lightQueue_, i, renderer, Vector3::ZERO); graphics->SetShaderParameter(VSP_LIGHTMATRICES, shadowMatrices[0].Data(), 16 * numSplits); } break; case LIGHT_SPOT: { Matrix4 shadowMatrices[2]; CalculateSpotMatrix(shadowMatrices[0], light, Vector3::ZERO); bool isShadowed = shadowMap && graphics->HasTextureUnit(TU_SHADOWMAP); if (isShadowed) CalculateShadowMatrix(shadowMatrices[1], lightQueue_, 0, renderer, Vector3::ZERO); graphics->SetShaderParameter(VSP_LIGHTMATRICES, shadowMatrices[0].Data(), isShadowed ? 32 : 16); } break; case LIGHT_POINT: { Matrix4 lightVecRot(lightNode->GetWorldRotation().RotationMatrix()); // HLSL compiler will pack the parameters as if the matrix is only 3x4, so must be careful to not overwrite // the next parameter #ifdef URHO3D_OPENGL graphics->SetShaderParameter(VSP_LIGHTMATRICES, lightVecRot.Data(), 16); #else graphics->SetShaderParameter(VSP_LIGHTMATRICES, lightVecRot.Data(), 12); #endif } break; } } float fade = 1.0f; float fadeEnd = light->GetDrawDistance(); float fadeStart = light->GetFadeDistance(); // Do fade calculation for light if both fade & draw distance defined if (light->GetLightType() != LIGHT_DIRECTIONAL && fadeEnd > 0.0f && fadeStart > 0.0f && fadeStart < fadeEnd) fade = Min(1.0f - (light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 1.0f); // Negative lights will use subtract blending, so write absolute RGB values to the shader parameter graphics->SetShaderParameter(PSP_LIGHTCOLOR, Color(light->GetEffectiveColor().Abs(), light->GetEffectiveSpecularIntensity()) * fade); graphics->SetShaderParameter(PSP_LIGHTDIR, lightWorldRotation * Vector3::BACK); graphics->SetShaderParameter(PSP_LIGHTPOS, Vector4((isLightVolume ? (lightNode->GetWorldPosition() - cameraEffectivePos) : lightNode->GetWorldPosition()), atten)); if (graphics->HasShaderParameter(PS, PSP_LIGHTMATRICES)) { switch (light->GetLightType()) { case LIGHT_DIRECTIONAL: { Matrix4 shadowMatrices[MAX_CASCADE_SPLITS]; unsigned numSplits = lightQueue_->shadowSplits_.Size(); for (unsigned i = 0; i < numSplits; ++i) { CalculateShadowMatrix(shadowMatrices[i], lightQueue_, i, renderer, isLightVolume ? cameraEffectivePos : Vector3::ZERO); } graphics->SetShaderParameter(PSP_LIGHTMATRICES, shadowMatrices[0].Data(), 16 * numSplits); } break; case LIGHT_SPOT: { Matrix4 shadowMatrices[2]; CalculateSpotMatrix(shadowMatrices[0], light, cameraEffectivePos); bool isShadowed = lightQueue_->shadowMap_ != 0; if (isShadowed) { CalculateShadowMatrix(shadowMatrices[1], lightQueue_, 0, renderer, isLightVolume ? cameraEffectivePos : Vector3::ZERO); } graphics->SetShaderParameter(PSP_LIGHTMATRICES, shadowMatrices[0].Data(), isShadowed ? 32 : 16); } break; case LIGHT_POINT: { Matrix4 lightVecRot(lightNode->GetWorldRotation().RotationMatrix()); // HLSL compiler will pack the parameters as if the matrix is only 3x4, so must be careful to not overwrite // the next parameter #ifdef URHO3D_OPENGL graphics->SetShaderParameter(PSP_LIGHTMATRICES, lightVecRot.Data(), 16); #else graphics->SetShaderParameter(PSP_LIGHTMATRICES, lightVecRot.Data(), 12); #endif } break; } } // Set shadow mapping shader parameters if (shadowMap) { { // Calculate point light shadow sampling offsets (unrolled cube map) unsigned faceWidth = shadowMap->GetWidth() / 2; unsigned faceHeight = shadowMap->GetHeight() / 3; float width = (float)shadowMap->GetWidth(); float height = (float)shadowMap->GetHeight(); #ifdef URHO3D_OPENGL float mulX = (float)(faceWidth - 3) / width; float mulY = (float)(faceHeight - 3) / height; float addX = 1.5f / width; float addY = 1.5f / height; #else float mulX = (float)(faceWidth - 4) / width; float mulY = (float)(faceHeight - 4) / height; float addX = 2.5f / width; float addY = 2.5f / height; #endif // If using 4 shadow samples, offset the position diagonally by half pixel if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT) { addX -= 0.5f / width; addY -= 0.5f / height; } graphics->SetShaderParameter(PSP_SHADOWCUBEADJUST, Vector4(mulX, mulY, addX, addY)); } { // Calculate shadow camera depth parameters for point light shadows and shadow fade parameters for // directional light shadows, stored in the same uniform Camera* shadowCamera = lightQueue_->shadowSplits_[0].shadowCamera_; float nearClip = shadowCamera->GetNearClip(); float farClip = shadowCamera->GetFarClip(); float q = farClip / (farClip - nearClip); float r = -q * nearClip; const CascadeParameters& parameters = light->GetShadowCascade(); float viewFarClip = camera_->GetFarClip(); float shadowRange = parameters.GetShadowRange(); float fadeStart = parameters.fadeStart_ * shadowRange / viewFarClip; float fadeEnd = shadowRange / viewFarClip; float fadeRange = fadeEnd - fadeStart; graphics->SetShaderParameter(PSP_SHADOWDEPTHFADE, Vector4(q, r, fadeStart, 1.0f / fadeRange)); } { float intensity = light->GetShadowIntensity(); float fadeStart = light->GetShadowFadeDistance(); float fadeEnd = light->GetShadowDistance(); if (fadeStart > 0.0f && fadeEnd > 0.0f && fadeEnd > fadeStart) intensity = Lerp(intensity, 1.0f, Clamp((light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 0.0f, 1.0f)); float pcfValues = (1.0f - intensity); float samples = renderer->GetShadowQuality() >= SHADOWQUALITY_HIGH_16BIT ? 4.0f : 1.0f; graphics->SetShaderParameter(PSP_SHADOWINTENSITY, Vector4(pcfValues / samples, intensity, 0.0f, 0.0f)); } float sizeX = 1.0f / (float)shadowMap->GetWidth(); float sizeY = 1.0f / (float)shadowMap->GetHeight(); graphics->SetShaderParameter(PSP_SHADOWMAPINVSIZE, Vector4(sizeX, sizeY, 0.0f, 0.0f)); Vector4 lightSplits(M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE); if (lightQueue_->shadowSplits_.Size() > 1) lightSplits.x_ = lightQueue_->shadowSplits_[0].farSplit_ / camera_->GetFarClip(); if (lightQueue_->shadowSplits_.Size() > 2) lightSplits.y_ = lightQueue_->shadowSplits_[1].farSplit_ / camera_->GetFarClip(); if (lightQueue_->shadowSplits_.Size() > 3) lightSplits.z_ = lightQueue_->shadowSplits_[2].farSplit_ / camera_->GetFarClip(); graphics->SetShaderParameter(PSP_SHADOWSPLITS, lightSplits); } } // Set material-specific shader parameters and textures if (material_) { if (graphics->NeedParameterUpdate(SP_MATERIAL, material_)) { const HashMap<StringHash, MaterialShaderParameter>& parameters = material_->GetShaderParameters(); for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = parameters.Begin(); i != parameters.End(); ++i) graphics->SetShaderParameter(i->first_, i->second_.value_); } const SharedPtr<Texture>* textures = material_->GetTextures(); unsigned numTextures = material_->GetNumUsedTextureUnits(); for (unsigned i = 0; i < numTextures; ++i) { TextureUnit unit = (TextureUnit)i; if (textures[i] && graphics->HasTextureUnit(unit)) graphics->SetTexture(i, textures[i]); } } // Set light-related textures if (light) { if (shadowMap && graphics->HasTextureUnit(TU_SHADOWMAP)) graphics->SetTexture(TU_SHADOWMAP, shadowMap); if (graphics->HasTextureUnit(TU_LIGHTRAMP)) { Texture* rampTexture = light->GetRampTexture(); if (!rampTexture) rampTexture = renderer->GetDefaultLightRamp(); graphics->SetTexture(TU_LIGHTRAMP, rampTexture); } if (graphics->HasTextureUnit(TU_LIGHTSHAPE)) { Texture* shapeTexture = light->GetShapeTexture(); if (!shapeTexture && light->GetLightType() == LIGHT_SPOT) shapeTexture = renderer->GetDefaultLightSpot(); graphics->SetTexture(TU_LIGHTSHAPE, shapeTexture); } } // Set zone texture if necessary if (zone_ && graphics->HasTextureUnit(TU_ZONE)) graphics->SetTexture(TU_ZONE, zone_->GetZoneTexture()); } void Batch::Draw(View* view) const { if (!geometry_->IsEmpty()) { Prepare(view); geometry_->Draw(view->GetGraphics()); } } void BatchGroup::SetTransforms(void* lockedData, unsigned& freeIndex) { // Do not use up buffer space if not going to draw as instanced if (geometryType_ != GEOM_INSTANCED) return; startIndex_ = freeIndex; Matrix3x4* dest = (Matrix3x4*)lockedData; dest += freeIndex; for (unsigned i = 0; i < instances_.Size(); ++i) *dest++ = *instances_[i].worldTransform_; freeIndex += instances_.Size(); } void BatchGroup::Draw(View* view) const { Graphics* graphics = view->GetGraphics(); Renderer* renderer = view->GetRenderer(); if (instances_.Size() && !geometry_->IsEmpty()) { // Draw as individual objects if instancing not supported VertexBuffer* instanceBuffer = renderer->GetInstancingBuffer(); if (!instanceBuffer || geometryType_ != GEOM_INSTANCED) { Batch::Prepare(view, false); graphics->SetIndexBuffer(geometry_->GetIndexBuffer()); graphics->SetVertexBuffers(geometry_->GetVertexBuffers(), geometry_->GetVertexElementMasks()); for (unsigned i = 0; i < instances_.Size(); ++i) { if (graphics->NeedParameterUpdate(SP_OBJECTTRANSFORM, instances_[i].worldTransform_)) graphics->SetShaderParameter(VSP_MODEL, *instances_[i].worldTransform_); graphics->Draw(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(), geometry_->GetVertexStart(), geometry_->GetVertexCount()); } } else { Batch::Prepare(view, false); // Get the geometry vertex buffers, then add the instancing stream buffer // Hack: use a const_cast to avoid dynamic allocation of new temp vectors Vector<SharedPtr<VertexBuffer> >& vertexBuffers = const_cast<Vector<SharedPtr<VertexBuffer> >&> (geometry_->GetVertexBuffers()); PODVector<unsigned>& elementMasks = const_cast<PODVector<unsigned>&>(geometry_->GetVertexElementMasks()); vertexBuffers.Push(SharedPtr<VertexBuffer>(instanceBuffer)); elementMasks.Push(instanceBuffer->GetElementMask()); // No stream offset support, instancing buffer not pre-filled with transforms: have to fill now if (startIndex_ == M_MAX_UNSIGNED) { unsigned startIndex = 0; while (startIndex < instances_.Size()) { unsigned instances = instances_.Size() - startIndex; if (instances > instanceBuffer->GetVertexCount()) instances = instanceBuffer->GetVertexCount(); // Copy the transforms Matrix3x4* dest = (Matrix3x4*)instanceBuffer->Lock(0, instances, true); if (dest) { for (unsigned i = 0; i < instances; ++i) dest[i] = *instances_[i + startIndex].worldTransform_; instanceBuffer->Unlock(); graphics->SetIndexBuffer(geometry_->GetIndexBuffer()); graphics->SetVertexBuffers(vertexBuffers, elementMasks); graphics->DrawInstanced(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(), geometry_->GetVertexStart(), geometry_->GetVertexCount(), instances); } startIndex += instances; } } // Stream offset supported and instancing buffer has been already filled, so just draw else { graphics->SetIndexBuffer(geometry_->GetIndexBuffer()); graphics->SetVertexBuffers(vertexBuffers, elementMasks, startIndex_); graphics->DrawInstanced(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(), geometry_->GetVertexStart(), geometry_->GetVertexCount(), instances_.Size()); } // Remove the instancing buffer & element mask now vertexBuffers.Pop(); elementMasks.Pop(); } } } unsigned BatchGroupKey::ToHash() const { return ((unsigned)(size_t)zone_) / sizeof(Zone) + ((unsigned)(size_t)lightQueue_) / sizeof(LightBatchQueue) + ((unsigned)(size_t)pass_) / sizeof(Pass) + ((unsigned)(size_t)material_) / sizeof(Material) + ((unsigned)(size_t)geometry_) / sizeof(Geometry); } void BatchQueue::Clear(int maxSortedInstances) { batches_.Clear(); sortedBatches_.Clear(); batchGroups_.Clear(); maxSortedInstances_ = maxSortedInstances; } void BatchQueue::SortBackToFront() { sortedBatches_.Resize(batches_.Size()); for (unsigned i = 0; i < batches_.Size(); ++i) sortedBatches_[i] = &batches_[i]; Sort(sortedBatches_.Begin(), sortedBatches_.End(), CompareBatchesBackToFront); // Do not actually sort batch groups, just list them sortedBatchGroups_.Resize(batchGroups_.Size()); unsigned index = 0; for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i) sortedBatchGroups_[index++] = &i->second_; } void BatchQueue::SortFrontToBack() { sortedBatches_.Clear(); for (unsigned i = 0; i < batches_.Size(); ++i) sortedBatches_.Push(&batches_[i]); SortFrontToBack2Pass(sortedBatches_); // Sort each group front to back for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i) { if (i->second_.instances_.Size() <= maxSortedInstances_) { Sort(i->second_.instances_.Begin(), i->second_.instances_.End(), CompareInstancesFrontToBack); if (i->second_.instances_.Size()) i->second_.distance_ = i->second_.instances_[0].distance_; } else { float minDistance = M_INFINITY; for (PODVector<InstanceData>::ConstIterator j = i->second_.instances_.Begin(); j != i->second_.instances_.End(); ++j) minDistance = Min(minDistance, j->distance_); i->second_.distance_ = minDistance; } } sortedBatchGroups_.Resize(batchGroups_.Size()); unsigned index = 0; for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i) sortedBatchGroups_[index++] = &i->second_; SortFrontToBack2Pass(reinterpret_cast<PODVector<Batch*>& >(sortedBatchGroups_)); } void BatchQueue::SortFrontToBack2Pass(PODVector<Batch*>& batches) { // Mobile devices likely use a tiled deferred approach, with which front-to-back sorting is irrelevant. The 2-pass // method is also time consuming, so just sort with state having priority #ifdef GL_ES_VERSION_2_0 Sort(batches.Begin(), batches.End(), CompareBatchesState); #else // For desktop, first sort by distance and remap shader/material/geometry IDs in the sort key Sort(batches.Begin(), batches.End(), CompareBatchesFrontToBack); unsigned freeShaderID = 0; unsigned short freeMaterialID = 0; unsigned short freeGeometryID = 0; for (PODVector<Batch*>::Iterator i = batches.Begin(); i != batches.End(); ++i) { Batch* batch = *i; unsigned shaderID = (batch->sortKey_ >> 32); HashMap<unsigned, unsigned>::ConstIterator j = shaderRemapping_.Find(shaderID); if (j != shaderRemapping_.End()) shaderID = j->second_; else { shaderID = shaderRemapping_[shaderID] = freeShaderID | (shaderID & 0xc0000000); ++freeShaderID; } unsigned short materialID = (unsigned short)(batch->sortKey_ & 0xffff0000); HashMap<unsigned short, unsigned short>::ConstIterator k = materialRemapping_.Find(materialID); if (k != materialRemapping_.End()) materialID = k->second_; else { materialID = materialRemapping_[materialID] = freeMaterialID; ++freeMaterialID; } unsigned short geometryID = (unsigned short)(batch->sortKey_ & 0xffff); HashMap<unsigned short, unsigned short>::ConstIterator l = geometryRemapping_.Find(geometryID); if (l != geometryRemapping_.End()) geometryID = l->second_; else { geometryID = geometryRemapping_[geometryID] = freeGeometryID; ++freeGeometryID; } batch->sortKey_ = (((unsigned long long)shaderID) << 32) || (((unsigned long long)materialID) << 16) | geometryID; } shaderRemapping_.Clear(); materialRemapping_.Clear(); geometryRemapping_.Clear(); // Finally sort again with the rewritten ID's Sort(batches.Begin(), batches.End(), CompareBatchesState); #endif } void BatchQueue::SetTransforms(void* lockedData, unsigned& freeIndex) { for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i) i->second_.SetTransforms(lockedData, freeIndex); } void BatchQueue::Draw(View* view, bool markToStencil, bool usingLightOptimization) const { Graphics* graphics = view->GetGraphics(); Renderer* renderer = view->GetRenderer(); // If View has set up its own light optimizations, do not disturb the stencil/scissor test settings if (!usingLightOptimization) { graphics->SetScissorTest(false); // During G-buffer rendering, mark opaque pixels' lightmask to stencil buffer if requested if (!markToStencil) graphics->SetStencilTest(false); } // Instanced for (PODVector<BatchGroup*>::ConstIterator i = sortedBatchGroups_.Begin(); i != sortedBatchGroups_.End(); ++i) { BatchGroup* group = *i; if (markToStencil) graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, group->lightMask_); group->Draw(view); } // Non-instanced for (PODVector<Batch*>::ConstIterator i = sortedBatches_.Begin(); i != sortedBatches_.End(); ++i) { Batch* batch = *i; if (markToStencil) graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, batch->lightMask_); if (!usingLightOptimization) { // If drawing an alpha batch, we can optimize fillrate by scissor test if (!batch->isBase_ && batch->lightQueue_) renderer->OptimizeLightByScissor(batch->lightQueue_->light_, batch->camera_); else graphics->SetScissorTest(false); } batch->Draw(view); } } unsigned BatchQueue::GetNumInstances() const { unsigned total = 0; for (HashMap<BatchGroupKey, BatchGroup>::ConstIterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i) { if (i->second_.geometryType_ == GEOM_INSTANCED) total += i->second_.instances_.Size(); } return total; } }
38,414
11,709
#include "stdafx.h" // CGExchangeSynchLock.cpp // ///////////////////////////////////////////////////// #include "CGExchangeSynchLock.h" BOOL CGExchangeSynchLock::Read( SocketInputStream& iStream ) { __ENTER_FUNCTION iStream.Read( (CHAR*)(&m_LockMyself), sizeof(BYTE)); return TRUE ; __LEAVE_FUNCTION return FALSE ; } BOOL CGExchangeSynchLock::Write( SocketOutputStream& oStream )const { __ENTER_FUNCTION oStream.Write( (CHAR*)(&m_LockMyself), sizeof(BYTE)); return TRUE ; __LEAVE_FUNCTION return FALSE ; } UINT CGExchangeSynchLock::Execute( Player* pPlayer ) { __ENTER_FUNCTION return CGExchangeSynchLockHandler::Execute( this, pPlayer ) ; __LEAVE_FUNCTION return FALSE ; }
763
265
#include "comm/SLIPMsgParser.hpp" #include "crc.hpp" using std::vector; namespace comm { SLIPMsgParser::SLIPMsgParser(unsigned int parseMsgMaxIn, unsigned int SLIPMaxLength) : MsgParser(parseMsgMaxIn), slipMsg(SLIPMsg(SLIPMaxLength)) { }; unsigned int SLIPMsgParser::parseSerialMsg(const vector<uint8_t> & msgBytes, unsigned int msgStart) { if (msgBytes.size() < 0) { // no message bytes return 0; } if (slipMsg.decodeSLIPMsg(msgBytes, msgStart) == true && slipMsg.msg.size() >= sizeof(crc_t)) { // minimum size should be crc length // Compare CRC vector<uint8_t> msgOnly = vector<uint8_t>(slipMsg.msg.begin(), slipMsg.msg.end()-2); crc_t crc = crc_create(msgOnly); if (crc == bytesToCrc(slipMsg.msg, slipMsg.msg.size()-2)) { // Add message to parsed messages parsedMsgs.push_back(msgOnly); } return slipMsg.msgEnd; } return msgBytes.size(); // no message found - return length of parsed bytes } vector<uint8_t> SLIPMsgParser::encodeMsg(vector<uint8_t> msgBytes) { if (msgBytes.size() > 0) { // Add CRC crc_t crc = crc_create(msgBytes); crcToBytes(msgBytes, crc); //msgBytes.push_back((uint8_t)((crc & 0xFF00) >> 8)); //msgBytes.push_back((uint8_t)((crc & 0x00FF))); return slipMsg.encodeSLIPMsg(msgBytes); } return vector<uint8_t>(); // no message } }
1,565
540
#ifndef __cxxtest__GlobalFixture_cpp__ #define __cxxtest__GlobalFixture_cpp__ #include <cxxtest/GlobalFixture.h> namespace CxxTest { bool GlobalFixture::setUpWorld() { return true; } bool GlobalFixture::tearDownWorld() { return true; } bool GlobalFixture::setUp() { return true; } bool GlobalFixture::tearDown() { return true; } GlobalFixture::GlobalFixture() { attach( _list ); } GlobalFixture::~GlobalFixture() { detach( _list ); } GlobalFixture *GlobalFixture::firstGlobalFixture() { return (GlobalFixture *)_list.head(); } GlobalFixture *GlobalFixture::lastGlobalFixture() { return (GlobalFixture *)_list.tail(); } GlobalFixture *GlobalFixture::nextGlobalFixture() { return (GlobalFixture *)next(); } GlobalFixture *GlobalFixture::prevGlobalFixture() { return (GlobalFixture *)prev(); } } #endif // __cxxtest__GlobalFixture_cpp__
897
284
#include <algorithm> #include <iomanip> #include <iostream> using namespace std; int main() { ios::sync_with_stdio(false); int a, b; cin >> a >> b; if (max(a, b) % min(a, b) == 0) cout << "Sao Multiplos\n"; else cout << "Nao sao Multiplos\n"; return 0; }
314
124
template<typename T> class AddSpace { private: T const& ref; // refer to argument passed in constructor public: AddSpace(T const& r): ref(r) { } friend std::ostream& operator<< (std::ostream& os, AddSpace<T> s) { return os << s.ref << ' '; // output passed argument and a space } }; template<typename... Args> void print (Args... args) { ( std::cout << ... << AddSpace(args) ) << '\n'; }
439
142
/*========================================================================= Program: ALBA (Agile Library for Biomedical Applications) Module: albaPipeScalarMatrix Authors: Paolo Quadrani Copyright (c) BIC All rights reserved. See Copyright.txt or This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "albaDefines.h" //---------------------------------------------------------------------------- // NOTE: Every CPP file in the ALBA must include "albaDefines.h" as first. // This force to include Window,wxWidgets and VTK exactly in this order. // Failing in doing this will result in a run-time error saying: // "Failure#0: The value of ESP was not properly saved across a function call" //---------------------------------------------------------------------------- #include "albaPipeScalarMatrix.h" #include "albaPipeScalarMatrix.h" #include "albaDecl.h" #include "albaSceneNode.h" #include "albaGUI.h" #include "albaVME.h" #include "albaVMEOutputScalarMatrix.h" #include "albaVMEScalarMatrix.h" #include "albaTagItem.h" #include "albaTagArray.h" #include "vtkALBASmartPointer.h" #include "vtkALBAAssembly.h" #include "vtkRenderer.h" #include "vtkPolyDataMapper.h" #include "vtkTextProperty.h" #include "vtkCubeAxesActor2D.h" #include "vtkPolyData.h" #include "vtkActor.h" //---------------------------------------------------------------------------- albaCxxTypeMacro(albaPipeScalarMatrix); //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- albaPipeScalarMatrix::albaPipeScalarMatrix() :albaPipe() //---------------------------------------------------------------------------- { m_CubeAxes = NULL; m_Actor = NULL; } //---------------------------------------------------------------------------- void albaPipeScalarMatrix::Create(albaSceneNode *n) //---------------------------------------------------------------------------- { Superclass::Create(n); m_Selected = false; vtkDataSet *ds = m_Vme->GetOutput()->GetVTKData(); vtkALBASmartPointer<vtkTextProperty> tprop; tprop->SetColor(1, 1, 1); tprop->ShadowOn(); vtkALBASmartPointer<vtkPolyDataMapper> mapper; mapper->SetInput((vtkPolyData *)ds); mapper->ScalarVisibilityOn(); mapper->SetScalarRange(ds->GetScalarRange()); vtkNEW(m_Actor); m_Actor->SetMapper(mapper); m_AssemblyFront->AddPart(m_Actor); vtkNEW(m_CubeAxes); m_CubeAxes->SetInput(ds); m_CubeAxes->SetCamera(m_RenFront->GetActiveCamera()); m_CubeAxes->SetLabelFormat("%6.4g"); m_CubeAxes->SetNumberOfLabels(5); m_CubeAxes->SetFlyModeToOuterEdges(); m_CubeAxes->SetFontFactor(0.4); m_CubeAxes->SetAxisTitleTextProperty(tprop); m_CubeAxes->SetAxisLabelTextProperty(tprop); m_RenFront->AddActor2D(m_CubeAxes); } //---------------------------------------------------------------------------- albaPipeScalarMatrix::~albaPipeScalarMatrix() //---------------------------------------------------------------------------- { m_RenFront->RemoveActor2D(m_CubeAxes); vtkDEL(m_CubeAxes); m_AssemblyFront->RemovePart(m_Actor); vtkDEL(m_Actor); } //---------------------------------------------------------------------------- void albaPipeScalarMatrix::Select(bool sel) //---------------------------------------------------------------------------- { m_Selected = sel; } //---------------------------------------------------------------------------- albaGUI *albaPipeScalarMatrix::CreateGui() //---------------------------------------------------------------------------- { m_Gui = new albaGUI(this); m_Gui->Divider(); return m_Gui; } //---------------------------------------------------------------------------- void albaPipeScalarMatrix::OnEvent(albaEventBase *alba_event) //---------------------------------------------------------------------------- { if (albaEvent *e = albaEvent::SafeDownCast(alba_event)) { switch(e->GetId()) { case ID_RADIUS: break; } GetLogicManager()->CameraUpdate(); } } //---------------------------------------------------------------------------- void albaPipeScalarMatrix::UpdateProperty(bool fromTag) //---------------------------------------------------------------------------- { }
4,485
1,334
// File implement/oglplus/enums/texture_target_def.ipp // // Automatically generated file, DO NOT modify manually. // Edit the source 'source/enums/oglplus/texture_target.txt' // or the 'source/enums/make_enum.py' script instead. // // Copyright 2010-2019 Matus Chochlik. // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // #ifdef OGLPLUS_LIST_NEEDS_COMMA # undef OGLPLUS_LIST_NEEDS_COMMA #endif #if defined GL_TEXTURE_1D # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined _1D # pragma push_macro("_1D") # undef _1D OGLPLUS_ENUM_CLASS_VALUE(_1D, GL_TEXTURE_1D) # pragma pop_macro("_1D") # else OGLPLUS_ENUM_CLASS_VALUE(_1D, GL_TEXTURE_1D) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_TEXTURE_2D # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined _2D # pragma push_macro("_2D") # undef _2D OGLPLUS_ENUM_CLASS_VALUE(_2D, GL_TEXTURE_2D) # pragma pop_macro("_2D") # else OGLPLUS_ENUM_CLASS_VALUE(_2D, GL_TEXTURE_2D) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_TEXTURE_3D # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined _3D # pragma push_macro("_3D") # undef _3D OGLPLUS_ENUM_CLASS_VALUE(_3D, GL_TEXTURE_3D) # pragma pop_macro("_3D") # else OGLPLUS_ENUM_CLASS_VALUE(_3D, GL_TEXTURE_3D) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_TEXTURE_1D_ARRAY # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined _1DArray # pragma push_macro("_1DArray") # undef _1DArray OGLPLUS_ENUM_CLASS_VALUE(_1DArray, GL_TEXTURE_1D_ARRAY) # pragma pop_macro("_1DArray") # else OGLPLUS_ENUM_CLASS_VALUE(_1DArray, GL_TEXTURE_1D_ARRAY) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_TEXTURE_2D_ARRAY # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined _2DArray # pragma push_macro("_2DArray") # undef _2DArray OGLPLUS_ENUM_CLASS_VALUE(_2DArray, GL_TEXTURE_2D_ARRAY) # pragma pop_macro("_2DArray") # else OGLPLUS_ENUM_CLASS_VALUE(_2DArray, GL_TEXTURE_2D_ARRAY) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_TEXTURE_RECTANGLE # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined Rectangle # pragma push_macro("Rectangle") # undef Rectangle OGLPLUS_ENUM_CLASS_VALUE(Rectangle, GL_TEXTURE_RECTANGLE) # pragma pop_macro("Rectangle") # else OGLPLUS_ENUM_CLASS_VALUE(Rectangle, GL_TEXTURE_RECTANGLE) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_TEXTURE_BUFFER # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined Buffer # pragma push_macro("Buffer") # undef Buffer OGLPLUS_ENUM_CLASS_VALUE(Buffer, GL_TEXTURE_BUFFER) # pragma pop_macro("Buffer") # else OGLPLUS_ENUM_CLASS_VALUE(Buffer, GL_TEXTURE_BUFFER) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_TEXTURE_CUBE_MAP # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined CubeMap # pragma push_macro("CubeMap") # undef CubeMap OGLPLUS_ENUM_CLASS_VALUE(CubeMap, GL_TEXTURE_CUBE_MAP) # pragma pop_macro("CubeMap") # else OGLPLUS_ENUM_CLASS_VALUE(CubeMap, GL_TEXTURE_CUBE_MAP) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_TEXTURE_CUBE_MAP_ARRAY # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined CubeMapArray # pragma push_macro("CubeMapArray") # undef CubeMapArray OGLPLUS_ENUM_CLASS_VALUE(CubeMapArray, GL_TEXTURE_CUBE_MAP_ARRAY) # pragma pop_macro("CubeMapArray") # else OGLPLUS_ENUM_CLASS_VALUE(CubeMapArray, GL_TEXTURE_CUBE_MAP_ARRAY) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_TEXTURE_2D_MULTISAMPLE # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined _2DMultisample # pragma push_macro("_2DMultisample") # undef _2DMultisample OGLPLUS_ENUM_CLASS_VALUE(_2DMultisample, GL_TEXTURE_2D_MULTISAMPLE) # pragma pop_macro("_2DMultisample") # else OGLPLUS_ENUM_CLASS_VALUE(_2DMultisample, GL_TEXTURE_2D_MULTISAMPLE) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_TEXTURE_2D_MULTISAMPLE_ARRAY # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined _2DMultisampleArray # pragma push_macro("_2DMultisampleArray") # undef _2DMultisampleArray OGLPLUS_ENUM_CLASS_VALUE(_2DMultisampleArray, GL_TEXTURE_2D_MULTISAMPLE_ARRAY) # pragma pop_macro("_2DMultisampleArray") # else OGLPLUS_ENUM_CLASS_VALUE(_2DMultisampleArray, GL_TEXTURE_2D_MULTISAMPLE_ARRAY) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_TEXTURE_CUBE_MAP_POSITIVE_X # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined CubeMapPositiveX # pragma push_macro("CubeMapPositiveX") # undef CubeMapPositiveX OGLPLUS_ENUM_CLASS_VALUE(CubeMapPositiveX, GL_TEXTURE_CUBE_MAP_POSITIVE_X) # pragma pop_macro("CubeMapPositiveX") # else OGLPLUS_ENUM_CLASS_VALUE(CubeMapPositiveX, GL_TEXTURE_CUBE_MAP_POSITIVE_X) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_TEXTURE_CUBE_MAP_NEGATIVE_X # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined CubeMapNegativeX # pragma push_macro("CubeMapNegativeX") # undef CubeMapNegativeX OGLPLUS_ENUM_CLASS_VALUE(CubeMapNegativeX, GL_TEXTURE_CUBE_MAP_NEGATIVE_X) # pragma pop_macro("CubeMapNegativeX") # else OGLPLUS_ENUM_CLASS_VALUE(CubeMapNegativeX, GL_TEXTURE_CUBE_MAP_NEGATIVE_X) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_TEXTURE_CUBE_MAP_POSITIVE_Y # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined CubeMapPositiveY # pragma push_macro("CubeMapPositiveY") # undef CubeMapPositiveY OGLPLUS_ENUM_CLASS_VALUE(CubeMapPositiveY, GL_TEXTURE_CUBE_MAP_POSITIVE_Y) # pragma pop_macro("CubeMapPositiveY") # else OGLPLUS_ENUM_CLASS_VALUE(CubeMapPositiveY, GL_TEXTURE_CUBE_MAP_POSITIVE_Y) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_TEXTURE_CUBE_MAP_NEGATIVE_Y # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined CubeMapNegativeY # pragma push_macro("CubeMapNegativeY") # undef CubeMapNegativeY OGLPLUS_ENUM_CLASS_VALUE(CubeMapNegativeY, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y) # pragma pop_macro("CubeMapNegativeY") # else OGLPLUS_ENUM_CLASS_VALUE(CubeMapNegativeY, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_TEXTURE_CUBE_MAP_POSITIVE_Z # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined CubeMapPositiveZ # pragma push_macro("CubeMapPositiveZ") # undef CubeMapPositiveZ OGLPLUS_ENUM_CLASS_VALUE(CubeMapPositiveZ, GL_TEXTURE_CUBE_MAP_POSITIVE_Z) # pragma pop_macro("CubeMapPositiveZ") # else OGLPLUS_ENUM_CLASS_VALUE(CubeMapPositiveZ, GL_TEXTURE_CUBE_MAP_POSITIVE_Z) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_TEXTURE_CUBE_MAP_NEGATIVE_Z # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined CubeMapNegativeZ # pragma push_macro("CubeMapNegativeZ") # undef CubeMapNegativeZ OGLPLUS_ENUM_CLASS_VALUE(CubeMapNegativeZ, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z) # pragma pop_macro("CubeMapNegativeZ") # else OGLPLUS_ENUM_CLASS_VALUE(CubeMapNegativeZ, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #ifdef OGLPLUS_LIST_NEEDS_COMMA # undef OGLPLUS_LIST_NEEDS_COMMA #endif
8,333
3,939
/**************************************************************************************** * @author: kzvd4729 created: 24-02-2018 21:46:36 * solution_verdict: Partially Accepted language: C++14 * run_time: 0.26 sec memory_used: 15.7M * problem: https://www.codechef.com/LTIME57/problems/BORDER ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; long n,q,t,f,x,nm; string ss,s; vector<long>v[505]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin>>t; while(t--) { cin>>n>>q; for(long i=1;i<=n;i++)v[i].clear(); cin>>ss; for(long i=1;i<=n;i++) { s=ss.substr(0,i); for(long j=1;j<=s.size();j++) { f=0; for(long k=0,kk=s.size()-j;k<j;k++,kk++) { if(s[k]!=s[kk])f=1; } if(!f)v[i].push_back(j); } } while(q--) { cin>>x>>nm; if(v[x].size()<nm)cout<<-1<<endl; else cout<<v[x][nm-1]<<endl; } } return 0; }
1,407
472
#include "skinconfigchanger.hpp" int KnifeCT = WEAPON_KNIFE_SKELETON; int KnifeT = WEAPON_KNIFE_SKELETON; int GloveCT = GLOVE_MOTORCYCLE; int GloveT = GLOVE_MOTORCYCLE; unordered_map<int, cSkin> cSkinchanger::Skins = unordered_map<int, cSkin>( { //knife make_pair(WEAPON_KNIFE, cSkin(59, -1, KnifeCT, -1, 3, nullptr, 0.00000000001f)), make_pair(WEAPON_KNIFE_T, cSkin(59, -1, KnifeCT, -1, 3, nullptr, 0.00000000001f)), //glove make_pair(GLOVE_CT, cSkin(10026, -1, GloveCT, -1, 3, nullptr, 0.00000000001f)), make_pair(GLOVE_T, cSkin(10026, -1, GloveT, -1, 3, nullptr, 0.00000000001f)), //guns make_pair(WEAPON_AWP, cSkin(756, -1, -1, -1, 0, nullptr, 0.00000000001f)), make_pair(WEAPON_SSG08, cSkin(899, -1, -1, -1, 0, nullptr, 0.00000000001f)), make_pair(WEAPON_MAC10, cSkin(898, -1, -1, -1, 0, nullptr, 0.00000000001f)), make_pair(WEAPON_SG556, cSkin(897, -1, -1, -1, 0, nullptr, 0.00000000001f)), make_pair(WEAPON_MP7, cSkin(893, -1, -1, -1, 0, nullptr, 0.00000000001f)), }); unordered_map<int, const char*> cSkinchanger::ModelList; std::unique_ptr<RecvPropHook> SkinChanger::sequenceHook; cSkinchanger* skinchanger = new cSkinchanger; void cSkinchanger::FrameStageNotify(ClientFrameStage_t stage) { if(stage == FRAME_NET_UPDATE_POSTDATAUPDATE_START){ pLocalPlayer = (C_BaseEntity*)(pEntList->GetClientEntity(pEngine->GetLocalPlayer())); if(pLocalPlayer && pLocalPlayer->GetHealth() > 0){ if(!bInit){ Init(); bInit = true; } ForceSkins(); } } } void cSkinchanger::FindModels() { ModelList[pModelInfo->GetModelIndex("models/weapons/v_knife_default_ct.mdl")] = KnifeToModelMatrix[KnifeCT].c_str(); ModelList[pModelInfo->GetModelIndex("models/weapons/v_knife_default_t.mdl")] = KnifeToModelMatrix[KnifeT].c_str(); ModelList[pModelInfo->GetModelIndex("models/weapons/v_models/arms/glove_hardknuckle/v_glove_hardknuckle.mdl")] = GloveToModelMatrix[GloveCT].c_str(); ModelList[pModelInfo->GetModelIndex("models/weapons/v_models/arms/glove_fingerless/v_glove_fingerless.mdl")] = GloveToModelMatrix[GloveT].c_str(); } void cSkinchanger::ForceSkins() { player_info_t player_info; if(pEngine->GetPlayerInfo(pLocalPlayer->GetId(), &player_info)){ int* pWeapons = pLocalPlayer->GetWeapons(); C_BaseViewModel* LocalPlayerViewModel = (C_BaseViewModel*)pEntList->GetClientEntityFromHandle(pLocalPlayer->GetViewModel()); C_BaseAttributableItem* WeaponViewModel = nullptr; if(LocalPlayerViewModel) WeaponViewModel = (C_BaseAttributableItem*)pEntList->GetClientEntityFromHandle(LocalPlayerViewModel->GetWeapon()); C_BaseCombatWeapon* localWeapon = (C_BaseCombatWeapon*)pEntList->GetClientEntityFromHandle(pLocalPlayer->GetActiveWeapon()); if(pWeapons){ for(int i = 0; pWeapons[i]; i++){ C_BaseAttributableItem* attributableItem = (C_BaseAttributableItem*)pEntList->GetClientEntityFromHandle(pWeapons[i]); if(attributableItem) { short* Definition = attributableItem->GetItemDefinitionIndex(); unordered_map<int, cSkin>::iterator SkinIter = (*Definition == WEAPON_KNIFE ? (*Definition == WEAPON_KNIFE ? Skins.find(WEAPON_KNIFE) : Skins.find(WEAPON_KNIFE_T)) : Skins.find(*Definition)); if(SkinIter != Skins.end()) { if(*attributableItem->GetOriginalOwnerXuidLow() == player_info.xuidlow && *attributableItem->GetOriginalOwnerXuidHigh() == player_info.xuidhigh){ int* model_index = attributableItem->GetModelIndex(); unordered_map<int, const char*>::iterator model_iter = ModelList.find(*model_index); if(model_iter != ModelList.end()){ *model_index = pModelInfo->GetModelIndex(model_iter->second); } cSkin skin = move(SkinIter->second); if(KnifeCT && (*Definition == WEAPON_KNIFE)) *attributableItem->GetItemDefinitionIndex() = KnifeCT; else if(KnifeT && (*Definition == WEAPON_KNIFE_T)) *attributableItem->GetItemDefinitionIndex() = KnifeT; if(skin.name) { sprintf(attributableItem->GetCustomName(), "%s", skin.name); } *attributableItem->GetItemIDHigh() = -1; *attributableItem->GetFallbackPaintKit() = skin.Paintkit; *attributableItem->GetFallbackStatTrak() = skin.StatTrack; *attributableItem->GetEntityQuality() = skin.EntityQuality; *attributableItem->GetFallbackSeed() = skin.Seed; *attributableItem->GetFallbackWear() = skin.Wear; *attributableItem->GetAccountID() = player_info.xuidlow; ApplyCustomGloves(); Init(); } } if (WeaponViewModel && WeaponViewModel == attributableItem) { int* model_index = ((C_BaseEntity*)LocalPlayerViewModel)->GetModelIndex(); unordered_map<int, const char*>::iterator model_iter = ModelList.find(*model_index); if (model_iter != ModelList.end()) { *model_index = pModelInfo->GetModelIndex(model_iter->second); } } } } if(LocalPlayerViewModel && localWeapon) { int* model_index = ((C_BaseEntity*)LocalPlayerViewModel)->GetModelIndex(); unordered_map<int, const char*>::iterator model_iter = ModelList.find(*((C_BaseEntity*)localWeapon)->GetModelIndex()); if(model_iter != ModelList.end()){ *model_index = pModelInfo->GetModelIndex(model_iter->second); } } } } } void cSkinchanger::ApplyCustomGloves() { C_BaseEntity* pLocal = (C_BaseEntity*)pEntList->GetClientEntity(pEngine->GetLocalPlayer()); if (!pEntList->GetClientEntityFromHandle((void*)pLocal->GetWearables())) { for (ClientClass* pClass = pClient->GetAllClasses(); pClass; pClass = pClass->m_pNext) { if (pClass->m_ClassID != (int)EClassIds::CEconWearable) continue; int entry = (pEntList->GetHighestEntityIndex() + 1); int serial = RandomInt(0x0, 0xFFF); pClass->m_pCreateFn(entry, serial); pLocal->GetWearables()[0] = entry | serial << 16; glovesUpdated = true; break; } } player_info_t LocalPlayerInfo; pEngine->GetPlayerInfo(pEngine->GetLocalPlayer(), &LocalPlayerInfo); C_BaseAttributableItem* glove = (C_BaseAttributableItem*)pEntList->GetClientEntity(pLocal->GetWearables()[0] & 0xFFF); if (!glove) return; int* glove_index = glove->GetModelIndex(); unordered_map<int, const char*>::iterator glove_iter = ModelList.find(*glove_index); unordered_map<int, cSkin>::iterator Iter = (pLocal->GetTeam() == TEAM_COUNTER_TERRORIST ? Skins.find(GLOVE_CT) : Skins.find(GLOVE_T)); cSkin gloveskin = move(Iter->second); if(glove_iter != ModelList.end()) *glove_index = pModelInfo->GetModelIndex(glove_iter->second); if(GloveCT && pLocal->GetTeam() == TEAM_COUNTER_TERRORIST) *glove->GetItemDefinitionIndex() = GloveCT; if(GloveT && pLocal->GetTeam() == TEAM_TERRORIST) *glove->GetItemDefinitionIndex() = GloveT; *glove->GetItemIDHigh() = -1; *glove->GetFallbackPaintKit() = gloveskin.Paintkit; *glove->GetFallbackWear() = gloveskin.Wear; *glove->GetAccountID() = LocalPlayerInfo.xuidlow; if(glovesUpdated) { glove->GetNetworkable()->PreDataUpdate(DATA_UPDATE_CREATED); glovesUpdated = false; } } void cSkinchanger::Init() { ModelList.clear(); FindModels(); } void cSkinchanger::FireEventClientSide(IGameEvent *event) { if (!vars.visuals.skinc) return; if (!pEngine->IsInGame()) return; if (!event || strcmp(event->GetName(), "player_death") != 0) return; if (!event->GetInt("attacker") || pEngine->GetPlayerForUserID(event->GetInt("attacker")) != pEngine->GetLocalPlayer()) return; if(!strcmp(event->GetName(), "game_newmap")) { Init(); } //f(const auto icon_override = (event->GetString("weapon"))) event->SetString("weapon", icon_override); } inline const int RandomSequence1(int low, int high) { return (rand() % (high - low + 1) + low); } void HSequenceProxyFn(const CRecvProxyData *pDataConst, void *pStruct, void *pOut) { CRecvProxyData* pData = const_cast<CRecvProxyData*>(pDataConst); C_BaseViewModel* pViewModel = (C_BaseViewModel*)pStruct; if(!pViewModel) return g_pSequence(pDataConst, pStruct, pOut); C_BaseEntity* pOwner = (C_BaseEntity*)pEntList->GetClientEntityFromHandle(pViewModel->GetOwner()); if (pViewModel && pOwner) { if (pOwner->GetIndex() == pEngine->GetLocalPlayer()) { const model_t* knife_model = pModelInfo->GetModel(*pViewModel->GetModelIndex()); const char* model_filename = pModelInfo->GetModelName(knife_model); int m_nSequence = (int)pData->m_Value.m_Int; if (!strcmp(model_filename, "models/weapons/v_knife_butterfly.mdl")) { switch (m_nSequence) { case SEQUENCE_DEFAULT_DRAW: m_nSequence = RandomSequence1(SEQUENCE_BUTTERFLY_DRAW, SEQUENCE_BUTTERFLY_DRAW2); break; case SEQUENCE_DEFAULT_LOOKAT01: m_nSequence = RandomSequence1(SEQUENCE_BUTTERFLY_LOOKAT01, SEQUENCE_BUTTERFLY_LOOKAT03); break; default: m_nSequence++; } } else if (!strcmp(model_filename, "models/weapons/v_knife_falchion_advanced.mdl")) { switch (m_nSequence) { case SEQUENCE_DEFAULT_IDLE2: m_nSequence = SEQUENCE_FALCHION_IDLE1; break; case SEQUENCE_DEFAULT_HEAVY_MISS1: m_nSequence = RandomSequence1(SEQUENCE_FALCHION_HEAVY_MISS1, SEQUENCE_FALCHION_HEAVY_MISS1_NOFLIP); break; case SEQUENCE_DEFAULT_LOOKAT01: m_nSequence = RandomSequence1(SEQUENCE_FALCHION_LOOKAT01, SEQUENCE_FALCHION_LOOKAT02); break; case SEQUENCE_DEFAULT_DRAW: case SEQUENCE_DEFAULT_IDLE1: break; default: m_nSequence--; } } else if (!strcmp(model_filename, "models/weapons/v_knife_push.mdl")) { switch (m_nSequence) { case SEQUENCE_DEFAULT_IDLE2: m_nSequence = SEQUENCE_DAGGERS_IDLE1; break; case SEQUENCE_DEFAULT_LIGHT_MISS1: case SEQUENCE_DEFAULT_LIGHT_MISS2: m_nSequence = RandomSequence1(SEQUENCE_DAGGERS_LIGHT_MISS1, SEQUENCE_DAGGERS_LIGHT_MISS5); break; case SEQUENCE_DEFAULT_HEAVY_MISS1: m_nSequence = RandomSequence1(SEQUENCE_DAGGERS_HEAVY_MISS2, SEQUENCE_DAGGERS_HEAVY_MISS1); break; case SEQUENCE_DEFAULT_HEAVY_HIT1: case SEQUENCE_DEFAULT_HEAVY_BACKSTAB: case SEQUENCE_DEFAULT_LOOKAT01: m_nSequence += 3; break; case SEQUENCE_DEFAULT_DRAW: case SEQUENCE_DEFAULT_IDLE1: break; default: m_nSequence += 2; } } else if (!strcmp(model_filename, "models/weapons/v_knife_survival_bowie.mdl")) { switch (m_nSequence) { case SEQUENCE_DEFAULT_DRAW: case SEQUENCE_DEFAULT_IDLE1: break; case SEQUENCE_DEFAULT_IDLE2: m_nSequence = SEQUENCE_BOWIE_IDLE1; break; default: m_nSequence--; } } else if (!strcmp(model_filename, "models/weapons/v_knife_ursus.mdl")) { switch (m_nSequence) { case SEQUENCE_DEFAULT_DRAW: m_nSequence = RandomSequence1(SEQUENCE_BUTTERFLY_DRAW, SEQUENCE_BUTTERFLY_DRAW2); break; case SEQUENCE_DEFAULT_LOOKAT01: m_nSequence = RandomSequence1(SEQUENCE_BUTTERFLY_LOOKAT01, 14); break; default: m_nSequence++; } } else if (!strcmp(model_filename, "models/weapons/v_knife_cord.mdl")) { switch (m_nSequence) { case SEQUENCE_DEFAULT_DRAW: m_nSequence = RandomSequence1(SEQUENCE_BUTTERFLY_DRAW, SEQUENCE_BUTTERFLY_DRAW2); break; case SEQUENCE_DEFAULT_LOOKAT01: m_nSequence = RandomSequence1(SEQUENCE_BUTTERFLY_LOOKAT01, 14); break; default: m_nSequence++; } } else if (!strcmp(model_filename, "models/weapons/v_knife_canis.mdl")) { switch (m_nSequence) { case SEQUENCE_DEFAULT_DRAW: m_nSequence = RandomSequence1(SEQUENCE_BUTTERFLY_DRAW, SEQUENCE_BUTTERFLY_DRAW2); break; case SEQUENCE_DEFAULT_LOOKAT01: m_nSequence = RandomSequence1(SEQUENCE_BUTTERFLY_LOOKAT01, 14); break; default: m_nSequence++; } } else if (!strcmp(model_filename, "models/weapons/v_knife_outdoor.mdl")) { switch (m_nSequence) { case SEQUENCE_DEFAULT_DRAW: m_nSequence = RandomSequence1(SEQUENCE_BUTTERFLY_DRAW, SEQUENCE_BUTTERFLY_DRAW2); break; case SEQUENCE_DEFAULT_LOOKAT01: m_nSequence = RandomSequence1(SEQUENCE_BUTTERFLY_LOOKAT01, 14); break; default: m_nSequence++; } } else if (!strcmp(model_filename, "models/weapons/v_knife_skeleton.mdl")) { switch (m_nSequence) { case SEQUENCE_DEFAULT_DRAW: m_nSequence = RandomSequence1(SEQUENCE_BUTTERFLY_DRAW, SEQUENCE_BUTTERFLY_DRAW2); break; case SEQUENCE_DEFAULT_LOOKAT01: m_nSequence = RandomSequence1(SEQUENCE_BUTTERFLY_LOOKAT01, 14); break; default: m_nSequence++; } }else if (!strcmp(model_filename, "models/weapons/v_knife_stiletto.mdl")) { switch (m_nSequence){ case SEQUENCE_DEFAULT_LOOKAT01: m_nSequence = RandomSequence1(12, 13); break; } } else if(!strcmp(model_filename, "models/weapons/v_knife_widowmaker.mdl")) { switch (m_nSequence) { case SEQUENCE_DEFAULT_LOOKAT01: m_nSequence = RandomSequence1(SEQUENCE_TALON_LOOKAT1, SEQUENCE_TALON_LOOKAT2); break; } } pData->m_Value.m_Int = m_nSequence; } } return g_pSequence(pData, pStruct, pOut); }
17,293
5,551
#include<stdio.h> #include<stdlib.h> int numcmp(const void *a,const void *b) { return *(int *)a-*(int *)b; } main() { scanf("%d",&n); for(i=bsum=0;i<n;i++) { scanf("%d",&board[i]); bsum+=board[i]; } scanf("%d",&r); for(i=rsum=0;i<r;i++) { scanf("%d",&j); if(rmin>j) rmin=j; if(rmax<j) rmax=j; rail[j]++; rsum+=j; } qsort(board,n,sizeof(board[0]),numcmp); if(board[n-1]>=rsum) { printf("%d\n",r); return 0; } for(j=0;board[j]<rmin;j++) bsum-=board[j]; for(i=0;j<n;i++,j++) board[i]=board[j]; n=i; for(;rsum>bsum;rmax--) while(rail[rmax]>0 && rsum>bsum) rsum-=rmax; test(0); printf("%d\n",best); } void test(int bi) { if(board[n-1]>=rrem) { best=r; return; } if(bi>=n) { if(cut>=best) best=cut; return; } if(best>=r) return; for(i=rmin,rsum=maxcut=0;i<=rmax && rsum<=bsum;i++) for(j=0;j<rail[i] && rsum<=bsum;j++,maxcut++) rsum+=i; if(cut+maxcut<=best) return; for(i=maxcut;i+cut>best;i--) dfs(bi,i,0); } void dfs(int bi,int n,int len) { if(n<=0) { calc(bi+1); return; } if(n==1 && len<rmax && s[len]>0) { s[len]--; cut++; calc(bi+1); cut--; s[len]++; return; } for(i=rmax;s[i]==0 && i>len;i--); for(;i>=rmin;i--) if(s[i]>0) { s[i]--; cut++; dfs(bi,n-1,len-i); cut--; s[i]++; } }
1,694
765
#include <iostream> #include <opencv2/opencv.hpp> using namespace cv; using namespace std; double alfa; int alfa_slider = 0; int alfa_slider_max = 100; int top_slider = 0; int top_slider_max = 100; Mat image1, image2, blended; Mat imageTop; char TrackbarName[50]; void on_trackbar_blend(int, void*){ alfa = (double) alfa_slider/alfa_slider_max ; addWeighted( image1, alfa, imageTop, 1-alfa, 0.0, blended); imshow("addweighted", blended); } void on_trackbar_line(int, void*){ image1.copyTo(imageTop); int limit = top_slider*255/100; if(limit > 0){ Mat tmp = image2(Rect(0, 0, 256, limit)); tmp.copyTo(imageTop(Rect(0, 0, 256, limit))); } on_trackbar_blend(alfa_slider,0); } int main(int argvc, char** argv){ image1 = imread("blend1.jpg"); image2 = imread("blend2.jpg"); image2.copyTo(imageTop); namedWindow("addweighted", 1); sprintf( TrackbarName, "Alpha x %d", alfa_slider_max ); createTrackbar( TrackbarName, "addweighted", &alfa_slider, alfa_slider_max, on_trackbar_blend ); on_trackbar_blend(alfa_slider, 0 ); sprintf( TrackbarName, "Scanline x %d", top_slider_max ); createTrackbar( TrackbarName, "addweighted", &top_slider, top_slider_max, on_trackbar_line ); on_trackbar_line(top_slider, 0 ); waitKey(0); return 0; }
1,315
576
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkImage.h" #include "itkScaleTransform.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkResampleImageFilter.h" using ImageType = itk::Image<unsigned char, 2>; static void CreateImage(ImageType::Pointer image); int main(int, char *[]) { ImageType::Pointer image = ImageType::New(); CreateImage(image); using WriterType = itk::ImageFileWriter<ImageType>; WriterType::Pointer inputWriter = WriterType::New(); inputWriter->SetFileName("input.png"); inputWriter->SetInput(image); inputWriter->Update(); // using TransformType = itk::ScaleTransform<float, 2>; // If you want to use float here, you must use: // using ResampleImageFilterType = itk::ResampleImageFilter<ImageType, ImageType, float>; later. using TransformType = itk::ScaleTransform<double, 2>; TransformType::Pointer scaleTransform = TransformType::New(); itk::FixedArray<float, 2> scale; scale[0] = 1.5; // newWidth/oldWidth scale[1] = 1.5; scaleTransform->SetScale(scale); itk::Point<float, 2> center; center[0] = image->GetLargestPossibleRegion().GetSize()[0] / 2; center[1] = image->GetLargestPossibleRegion().GetSize()[1] / 2; scaleTransform->SetCenter(center); using ResampleImageFilterType = itk::ResampleImageFilter<ImageType, ImageType>; ResampleImageFilterType::Pointer resampleFilter = ResampleImageFilterType::New(); resampleFilter->SetTransform(scaleTransform); resampleFilter->SetInput(image); resampleFilter->SetSize(image->GetLargestPossibleRegion().GetSize()); resampleFilter->Update(); WriterType::Pointer outputWriter = WriterType::New(); outputWriter->SetFileName("output.png"); outputWriter->SetInput(resampleFilter->GetOutput()); outputWriter->Update(); return EXIT_SUCCESS; } void CreateImage(ImageType::Pointer image) { itk::Index<2> start; start.Fill(0); itk::Size<2> size; size.Fill(101); ImageType::RegionType region(start, size); image->SetRegions(region); image->Allocate(); image->FillBuffer(0); // Make a white square for (unsigned int r = 40; r < 60; r++) { for (unsigned int c = 40; c < 60; c++) { ImageType::IndexType pixelIndex; pixelIndex[0] = r; pixelIndex[1] = c; image->SetPixel(pixelIndex, 255); } } itk::ImageRegionIterator<ImageType> imageIterator(image, image->GetLargestPossibleRegion()); // Draw a white border while (!imageIterator.IsAtEnd()) { if (imageIterator.GetIndex()[0] == 0 || imageIterator.GetIndex()[0] == static_cast<int>(image->GetLargestPossibleRegion().GetSize()[0]) - 1 || imageIterator.GetIndex()[1] == 0 || imageIterator.GetIndex()[1] == static_cast<int>(image->GetLargestPossibleRegion().GetSize()[1]) - 1) { imageIterator.Set(255); } ++imageIterator; } }
3,593
1,165
/* Copyright (c) 2014-2015 DataStax Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef __CASS_MULTIPLE_REQUEST_HANDLER_HPP_INCLUDED__ #define __CASS_MULTIPLE_REQUEST_HANDLER_HPP_INCLUDED__ #include "handler.hpp" #include "ref_counted.hpp" #include "request.hpp" #include <string> #include <vector> namespace cass { class Connection; class Response; class MultipleRequestHandler : public RefCounted<MultipleRequestHandler> { public: typedef std::vector<Response*> ResponseVec; MultipleRequestHandler(Connection* connection) : connection_(connection) , has_errors_or_timeouts_(false) , remaining_(0) {} virtual ~MultipleRequestHandler(); void execute_query(const std::string& query); virtual void on_set(const ResponseVec& responses) = 0; virtual void on_error(CassError code, const std::string& message) = 0; virtual void on_timeout() = 0; Connection* connection() { return connection_; } private: class InternalHandler : public Handler { public: InternalHandler(MultipleRequestHandler* parent, Request* request, int index) : parent_(parent) , request_(request) , index_(index) {} const Request* request() const { return request_.get(); } virtual void on_set(ResponseMessage* response); virtual void on_error(CassError code, const std::string& message); virtual void on_timeout(); private: ScopedRefPtr<MultipleRequestHandler> parent_; ScopedRefPtr<Request> request_; int index_; }; Connection* connection_; bool has_errors_or_timeouts_; int remaining_; ResponseVec responses_; }; } // namespace cass #endif
2,136
665
#include "FWCore/PluginManager/interface/ModuleDef.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "EventFilter/SiStripRawToDigi/test/plugins/SiStripFEDRawDataAnalyzer.h" DEFINE_FWK_MODULE(SiStripFEDRawDataAnalyzer); #include "EventFilter/SiStripRawToDigi/test/plugins/SiStripDigiAnalyzer.h" DEFINE_FWK_MODULE(SiStripDigiAnalyzer); #include "EventFilter/SiStripRawToDigi/test/plugins/SiStripTrivialClusterSource.h" DEFINE_FWK_MODULE(SiStripTrivialClusterSource); #include "EventFilter/SiStripRawToDigi/test/plugins/SiStripTrivialDigiSource.h" DEFINE_FWK_MODULE(SiStripTrivialDigiSource); #include "EventFilter/SiStripRawToDigi/test/plugins/SiStripDigiValidator.h" DEFINE_FWK_MODULE(SiStripDigiValidator); #include "EventFilter/SiStripRawToDigi/test/plugins/SiStripClusterValidator.h" DEFINE_FWK_MODULE(SiStripClusterValidator); #include "EventFilter/SiStripRawToDigi/test/plugins/SiStripModuleTimer.h" DEFINE_FWK_MODULE(SiStripModuleTimer);
966
394
/* render model module part of uni module Copyright 2020-2021 Lukas Cone Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include "format.hpp" #include "list.hpp" namespace uni { struct RTSValue; struct BBOX { Vector4A16 min; Vector4A16 max; }; class PrimitiveDescriptor : public Base { public: enum class UnpackDataType_e { None, Add, // x + min Mul, // x * min Madd, // max + x * min }; enum class Usage_e : uint8 { Undefined, Position, Normal, Tangent, BiTangent, TextureCoordiante, BoneIndices, BoneWeights, VertexColor, VertexIndex, PositionDelta, }; // Get already indexed & offseted vertex buffer virtual const char *RawBuffer() const = 0; virtual size_t Stride() const = 0; virtual size_t Offset() const = 0; virtual size_t Index() const = 0; virtual Usage_e Usage() const = 0; virtual FormatDescr Type() const = 0; virtual FormatCodec &Codec() const { return FormatCodec::Get(Type()); } virtual BBOX UnpackData() const = 0; virtual UnpackDataType_e UnpackDataType() const = 0; void Resample(FormatCodec::fvec &data) const; }; typedef Element<const List<PrimitiveDescriptor>> PrimitiveDescriptorsConst; typedef Element<List<PrimitiveDescriptor>> PrimitiveDescriptors; class Primitive : public Base { public: enum class IndexType_e { None, Line, Triangle, Strip, Fan }; virtual const char *RawIndexBuffer() const = 0; virtual const char *RawVertexBuffer(size_t id) const = 0; virtual PrimitiveDescriptorsConst Descriptors() const = 0; virtual IndexType_e IndexType() const = 0; virtual size_t IndexSize() const = 0; virtual size_t NumVertices() const = 0; virtual size_t NumVertexBuffers() const = 0; virtual size_t NumIndices() const = 0; virtual std::string Name() const = 0; virtual size_t SkinIndex() const = 0; virtual size_t LODIndex() const = 0; virtual size_t MaterialIndex() const = 0; }; typedef Element<const List<Primitive>> PrimitivesConst; typedef Element<List<Primitive>> Primitives; class PC_EXTERN Skin : public Base { public: virtual size_t NumNodes() const = 0; virtual TransformType TMType() const = 0; virtual void GetTM(RTSValue &out, size_t index) const; virtual void GetTM(esMatrix44 &out, size_t index) const; virtual size_t NodeIndex(size_t index) const = 0; }; typedef Element<const List<Skin>> SkinsConst; typedef Element<List<Skin>> Skins; using ResourcesConst = Element<const List<std::string>>; using Resources = Element<List<std::string>>; class Material : public Base { public: virtual size_t Version() const = 0; virtual std::string Name() const = 0; virtual std::string TypeName() const = 0; }; using MaterialsConst = Element<const List<Material>>; using Materials = Element<List<Material>>; class Model : public Base { public: virtual PrimitivesConst Primitives() const = 0; virtual SkinsConst Skins() const = 0; virtual ResourcesConst Resources() const = 0; virtual MaterialsConst Materials() const = 0; }; } // namespace uni #include "internal/model.inl"
3,600
1,185
/****************************************************************************** DSPatch - The Refreshingly Simple C++ Dataflow Framework Copyright (c) 2020, Marcus Tomlinson BSD 2-Clause License Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ #include <dspatch/SignalBus.h> using namespace DSPatch; namespace DSPatch { namespace internal { class SignalBus { public: Signal::SPtr nullSignal = nullptr; }; } // namespace internal } // namespace DSPatch SignalBus::SignalBus() : p( new internal::SignalBus() ) { } SignalBus::SignalBus( SignalBus&& rhs ) { _signals = rhs._signals; } SignalBus::~SignalBus() { } void SignalBus::SetSignalCount( int signalCount ) { int fromSize = _signals.size(); _signals.resize( signalCount ); for ( int i = fromSize; i < signalCount; ++i ) { _signals[i] = std::make_shared<Signal>(); } } int SignalBus::GetSignalCount() const { return _signals.size(); } Signal::SPtr const& SignalBus::GetSignal( int signalIndex ) const { if ( (size_t)signalIndex < _signals.size() ) { return _signals[signalIndex]; } else { return p->nullSignal; } } bool SignalBus::HasValue( int signalIndex ) const { if ( (size_t)signalIndex < _signals.size() ) { return _signals[signalIndex]->HasValue(); } else { return false; } } bool SignalBus::CopySignal( int toSignalIndex, Signal::SPtr const& fromSignal ) { if ( (size_t)toSignalIndex < _signals.size() ) { return _signals[toSignalIndex]->CopySignal( fromSignal ); } else { return false; } } bool SignalBus::MoveSignal( int toSignalIndex, Signal::SPtr const& fromSignal ) { if ( (size_t)toSignalIndex < _signals.size() ) { return _signals[toSignalIndex]->MoveSignal( fromSignal ); } else { return false; } } void SignalBus::ClearAllValues() { for ( auto& signal : _signals ) { signal->ClearValue(); } } std::type_info const& SignalBus::GetType( int signalIndex ) const { if ( (size_t)signalIndex < _signals.size() ) { return _signals[signalIndex]->GetType(); } else { return typeid( void ); } }
3,515
1,222
#include <iostream> #include <math.h> using namespace std; int main(){ long long int n = 0, x; cin >> n; for(int i = 0; i < n; i++){ x = 0; cin >> x; x = ((pow(2, x)) / 12) / 1000; cout << x << " kg" << endl; } return 0; }
283
125
#include <string> #include <vector> using namespace std; string solution(int num) { string answer = ""; if (num % 2 == 0) { answer = "Even"; } else { answer = "Odd"; } return answer; }
236
86
// Copyright 2021 David Conran /// @file /// @brief Support for XMP protocols. /// @see https://github.com/crankyoldgit/IRremoteESP8266/issues/1414 /// @see http://www.hifi-remote.com/wiki/index.php/XMP // Supports: // Brand: Xfinity, Model: XR2 remote // Brand: Xfinity, Model: XR11 remote #include <algorithm> #include "IRrecv.h" #include "IRsend.h" #include "IRutils.h" // Constants const uint16_t kXmpMark = 210; ///< uSeconds. const uint16_t kXmpBaseSpace = 760; ///< uSeconds const uint16_t kXmpSpaceStep = 135; ///< uSeconds const uint16_t kXmpFooterSpace = 13000; ///< uSeconds. const uint32_t kXmpMessageGap = 80400; ///< uSeconds. const uint8_t kXmpWordSize = kNibbleSize; ///< nr. of Bits in a word. const uint8_t kXmpMaxWordValue = (1 << kXmpWordSize) - 1; // Max word value. const uint8_t kXmpSections = 2; ///< Nr. of Data sections const uint8_t kXmpRepeatCode = 0b1000; const uint8_t kXmpRepeatCodeAlt = 0b1001; using irutils::setBits; namespace IRXmpUtils { /// Get the current checksum value from an XMP data section. /// @param[in] data The value of the data section. /// @param[in] nbits The number of data bits in the section. /// @return The value of the stored checksum. /// @warning Returns 0 if we can't obtain a valid checksum. uint8_t getSectionChecksum(const uint32_t data, const uint16_t nbits) { // The checksum is the 2nd most significant nibble of a section. return (nbits < 2 * kNibbleSize) ? 0 : GETBITS32(data, nbits - (2 * kNibbleSize), kNibbleSize); } /// Calculate the correct checksum value for an XMP data section. /// @param[in] data The value of the data section. /// @param[in] nbits The number of data bits in the section. /// @return The value of the correct checksum. uint8_t calcSectionChecksum(const uint32_t data, const uint16_t nbits) { return (0xF & ~(irutils::sumNibbles(data, nbits / kNibbleSize, 0xF, false) - getSectionChecksum(data, nbits))); } /// Recalculate a XMP message code ensuring it has the checksums valid. /// @param[in] data The value of the XMP message code. /// @param[in] nbits The number of data bits in the entire message code. /// @return The corrected XMP message with valid checksum sections. uint64_t updateChecksums(const uint64_t data, const uint16_t nbits) { const uint16_t sectionbits = nbits / kXmpSections; uint64_t result = data; for (uint16_t sectionOffset = 0; sectionOffset < nbits; sectionOffset += sectionbits) { const uint16_t checksumOffset = sectionOffset + sectionbits - (2 * kNibbleSize); setBits(&result, checksumOffset, kNibbleSize, calcSectionChecksum(GETBITS64(data, sectionOffset, sectionbits), sectionbits)); } return result; } /// Calculate the bit offset the repeat nibble in an XMP code. /// @param[in] nbits The number of data bits in the entire message code. /// @return The offset to the start of the XMP repeat nibble. uint16_t calcRepeatOffset(const uint16_t nbits) { return (nbits < 3 * kNibbleSize) ? 0 : (nbits / kXmpSections) - (3 * kNibbleSize); } /// Test if an XMP message code is a repeat or not. /// @param[in] data The value of the XMP message code. /// @param[in] nbits The number of data bits in the entire message code. /// @return true, if it looks like a repeat, false if not. bool isRepeat(const uint64_t data, const uint16_t nbits) { switch (GETBITS64(data, calcRepeatOffset(nbits), kNibbleSize)) { case kXmpRepeatCode: case kXmpRepeatCodeAlt: return true; default: return false; } } /// Adjust an XMP message code to make it a valid repeat or non-repeat code. /// @param[in] data The value of the XMP message code. /// @param[in] nbits The number of data bits in the entire message code. /// @param[in] repeat_code The value of the XMP repeat nibble to use. /// A value of `8` is the normal value for a repeat. `9` has also been seen. /// A value of `0` will convert the code to a non-repeat code. /// @return The valud of the modified XMP code. uint64_t adjustRepeat(const uint64_t data, const uint16_t nbits, const uint8_t repeat_code) { uint64_t result = data; setBits(&result, calcRepeatOffset(nbits), kNibbleSize, repeat_code); return updateChecksums(result, nbits); } } // namespace IRXmpUtils using IRXmpUtils::calcSectionChecksum; using IRXmpUtils::getSectionChecksum; using IRXmpUtils::isRepeat; using IRXmpUtils::adjustRepeat; #if SEND_XMP /// Send a XMP packet. /// Status: Beta / Untested against a real device. /// @param[in] data The message to be sent. /// @param[in] nbits The number of bits of message to be sent. /// @param[in] repeat The number of times the command is to be repeated. void IRsend::sendXmp(const uint64_t data, const uint16_t nbits, const uint16_t repeat) { enableIROut(38000); if (nbits < 2 * kXmpWordSize) return; // Too small to send, abort! uint64_t send_data = data; for (uint16_t r = 0; r <= repeat; r++) { uint16_t bits_so_far = kXmpWordSize; for (uint64_t mask = ((uint64_t)kXmpMaxWordValue) << (nbits - kXmpWordSize); mask; mask >>= kXmpWordSize) { uint8_t word = (send_data & mask) >> (nbits - bits_so_far); mark(kXmpMark); space(kXmpBaseSpace + word * kXmpSpaceStep); bits_so_far += kXmpWordSize; // Are we at a data section boundary? if ((bits_so_far - kXmpWordSize) % (nbits / kXmpSections) == 0) { // Yes. mark(kXmpMark); space(kXmpFooterSpace); } } space(kXmpMessageGap - kXmpFooterSpace); // Modify the value if needed, to make it into a valid repeat code. if (!isRepeat(send_data, nbits)) send_data = adjustRepeat(send_data, nbits, kXmpRepeatCode); } } #endif // SEND_XMP #if DECODE_XMP /// Decode the supplied XMP packet/message. /// Status: BETA / Probably works. /// @param[in,out] results Ptr to the data to decode & where to store the result /// @param[in] offset The starting index to use when attempting to decode the /// raw data. Typically/Defaults to kStartOffset. /// @param[in] nbits The number of data bits to expect. /// @param[in] strict Flag indicating if we should perform strict matching. /// @return True if it can decode it, false if it can't. bool IRrecv::decodeXmp(decode_results *results, uint16_t offset, const uint16_t nbits, const bool strict) { uint64_t data = 0; if (results->rawlen < 2 * (nbits / kXmpWordSize) + (kXmpSections * kFooter) + offset - 1) return false; // Not enough entries to ever be XMP. // Compliance if (strict && nbits != kXmpBits) return false; // Data // Sections for (uint8_t section = 1; section <= kXmpSections; section++) { for (uint16_t bits_so_far = 0; bits_so_far < nbits / kXmpSections; bits_so_far += kXmpWordSize) { if (!matchMarkRange(results->rawbuf[offset++], kXmpMark)) return 0; uint8_t value = 0; bool found = false; for (; value <= kXmpMaxWordValue; value++) { if (matchSpaceRange(results->rawbuf[offset], kXmpBaseSpace + value * kXmpSpaceStep, kXmpSpaceStep / 2, 0)) { found = true; break; } } if (!found) return 0; // Failure. data <<= kXmpWordSize; data += value; offset++; } // Section Footer if (!matchMarkRange(results->rawbuf[offset++], kXmpMark)) return 0; if (section < kXmpSections) { if (!matchSpace(results->rawbuf[offset++], kXmpFooterSpace)) return 0; } else { // Last section if (offset < results->rawlen && !matchAtLeast(results->rawbuf[offset++], kXmpFooterSpace)) return 0; } } // Compliance if (strict) { // Validate checksums. uint64_t checksum_data = data; const uint16_t section_size = nbits / kXmpSections; // Each section has a checksum. for (uint16_t section = 0; section < kXmpSections; section++) { if (getSectionChecksum(checksum_data, section_size) != calcSectionChecksum(checksum_data, section_size)) return 0; checksum_data >>= section_size; } } // Success results->value = data; results->decode_type = decode_type_t::XMP; results->bits = nbits; results->address = 0; results->command = 0; // See if it is a repeat message. results->repeat = isRepeat(data, nbits); return true; } #endif // DECODE_XMP
8,821
3,032
#ifndef DASH_REPLACER_HPP #define DASH_REPLACER_HPP #include <iostream> #include <unordered_map> #include "text/replacer/replacer.hpp" /// Replaces -- with an en-dash and --- with an em-dash class DashReplacer : public Replacer { public: /// Constructs a new dash replacer DashReplacer(const ReplacerTable* pTable); /// Replaces dashes and output html virtual std::string replace(const char pPrev, const char pCur, const char pNext, bool& pConsume); /// Not used in this replacer virtual ReplacerState state() const { return eStateNormal; } /// Resets found state virtual void reset(); //// Verifies that found dashes were emitted virtual void verify() const; private: /// A dash block of atleast two was found int mCount; }; #endif
889
267
/* * An application for applying a Gaussian blur. * It uses a 3x3 stencil with constant weights. */ #include "Halide.h" namespace { using namespace Halide; // Size of blur for gradients. const int blockSize = 3; int imgSize = 64-blockSize+1; class GaussianBlur : public Halide::Generator<GaussianBlur> { public: Input<Buffer<uint8_t>> input{"input", 2}; Output<Buffer<uint8_t>> output{"output", 2}; //Input<int32_t> tilesize{"tilesize", 64, 8, 128}; // default 64. bounded between 8 and 128 int tilesize = imgSize; void generate() { /* THE ALGORITHM */ Var x("x"), y("y"); Var xo("xo"), yo("yo"), xi("xi"), yi("yi"); // Create a reduction domain of the correct bounds. RDom win(0, blockSize, 0, blockSize); Func hw_input, input_copy; hw_input(x, y) = cast<uint16_t>(input(x, y)); //input_copy(x, y) = cast<uint16_t>(input(x, y)); //hw_input(x, y) = input_copy(x, y); // create the gaussia nkernel Func kernel_f; float sigma = 1.5f; kernel_f(x) = exp(-x*x/(2*sigma*sigma)) / (sqrtf(2*M_PI)*sigma); // create a normalized set of 8bit weights Func kernel; Expr sum_kernel[blockSize*blockSize]; for (int idx=0, i=0; i<blockSize; ++i) { for (int j=0; j<blockSize; ++j) { if (i==0 && j==0) { sum_kernel[idx] = kernel_f(i-blockSize/2) * kernel_f(j-blockSize/2); } else { sum_kernel[idx] = kernel_f(i-blockSize/2) * kernel_f(j-blockSize/2) + sum_kernel[idx-1]; } idx++; } } //kernel(x) = cast<uint16_t>(kernel_f(x) * 64 / sum_kernel[blockSize-1]); //kernel(x,y) = cast<uint16_t>(kernel_f(x-blockSize/2) * kernel_f(y-blockSize/2) * 256.0f / // sum_kernel[blockSize*blockSize-1]); kernel(x,y) = cast<uint16_t>(kernel_f(x-blockSize/2) * kernel_f(y-blockSize/2) * 256.0f / sum_kernel[blockSize*blockSize-1]); // Use a 2D filter to blur the input Func blur_unnormalized, blur; blur_unnormalized(x, y) = cast<uint16_t>(0); //blur_unnormalized(x, y) += cast<uint16_t>( kernel(win.x, win.y) * hw_input(x+win.x, y+win.y) ); blur_unnormalized(x, y) += kernel(win.x, win.y) * hw_input(x+win.x, y+win.y); blur(x, y) = blur_unnormalized(x, y) / 256; Func hw_output; hw_output(x, y) = blur(x, y); output(x, y) = cast<uint8_t>( hw_output(x, y) ); /* THE SCHEDULE */ if (get_target().has_feature(Target::CoreIR)) { hw_output.bound(x, 0, imgSize); hw_output.bound(y, 0, imgSize); output.bound(x, 0, imgSize); output.bound(y, 0, imgSize); blur_unnormalized.bound(x, 0, imgSize); blur_unnormalized.bound(y, 0, imgSize); //hw_input.compute_root(); //kernel.compute_root(); hw_output.compute_root(); hw_output // .compute_at(output, xo) .tile(x, y, xo, yo, xi, yi, imgSize, imgSize) .hw_accelerate(xi, xo); blur_unnormalized.update() .unroll(win.x, blockSize) .unroll(win.y, blockSize); blur_unnormalized.linebuffer(); //hw_output.accelerate({hw_input}, xi, xo); hw_input.compute_at(hw_output, xi).store_at(hw_output, xo); hw_input.stream_to_accelerator(); } else if (get_target().has_feature(Target::Clockwork)) { //output.bound(x, 0, imgSize); //output.bound(y, 0, imgSize); output.bound(x, 0, tilesize); output.bound(y, 0, tilesize); hw_output.compute_root(); hw_output //.tile(x, y, xo, yo, xi, yi, imgSize, imgSize) .tile(x, y, xo, yo, xi, yi, tilesize, tilesize) .hw_accelerate(xi, xo); blur_unnormalized.update() .unroll(win.x, blockSize) .unroll(win.y, blockSize); blur_unnormalized.compute_at(hw_output, xo); blur.compute_at(hw_output, xo); hw_input.stream_to_accelerator();//.compute_root();//at(output, xo); //hw_input.compute_root(); //hw_input.compute_at(hw_output, xo); //input_copy.stream_to_accelerator(); //input_copy.compute_root(); } else { // schedule to CPU /*output.tile(x, y, xo, yo, xi, yi, imgSize, imgSize) .vectorize(xi, 8) .fuse(xo, yo, xo) .parallel(xo);*/ } } }; } // namespace HALIDE_REGISTER_GENERATOR(GaussianBlur, gaussian)
4,730
1,809
#include "robotoc/utils/derivative_checker.hpp" #include "robotoc/ocp/split_kkt_residual.hpp" #include "robotoc/ocp/split_kkt_matrix.hpp" #include "robotoc/ocp/split_solution.hpp" #include "robotoc/hybrid/grid_info.hpp" #include <cmath> namespace robotoc { DerivativeChecker::DerivativeChecker(const Robot& robot, const double finite_diff, const double test_tol) : robot_(robot), finite_diff_(finite_diff), test_tol_(test_tol) { } DerivativeChecker::~DerivativeChecker() { } void DerivativeChecker::setFiniteDifference(const double finite_diff) { finite_diff_ = finite_diff; } void DerivativeChecker::setTestTolerance(const double test_tol) { test_tol_ = test_tol; } bool DerivativeChecker::checkFirstOrderStageCostDerivatives( const std::shared_ptr<CostFunctionComponentBase>& cost) { return checkFirstOrderStageCostDerivatives(cost, robot_.createContactStatus()); } bool DerivativeChecker::checkSecondOrderStageCostDerivatives( const std::shared_ptr<CostFunctionComponentBase>& cost) { return checkSecondOrderStageCostDerivatives(cost, robot_.createContactStatus()); } bool DerivativeChecker::checkFirstOrderStageCostDerivatives( const std::shared_ptr<CostFunctionComponentBase>& cost, const ContactStatus& contact_status) { const auto s = SplitSolution::Random(robot_, contact_status); const auto grid_info = GridInfo::Random(); const int dimv = robot_.dimv(); const int dimu = robot_.dimu(); const int dimf = contact_status.dimf(); SplitKKTResidual kkt_residual(robot_); kkt_residual.setContactStatus(contact_status); CostFunctionData data(robot_); robot_.updateKinematics(s.q, s.v, s.a); double cost0 = cost->evalStageCost(robot_, contact_status, data, grid_info, s); cost->evalStageCostDerivatives(robot_, contact_status, data, grid_info, s, kkt_residual); auto s1 = s; Eigen::VectorXd lq_ref(dimv); for (int i=0; i<dimv; ++i) { s1 = s; Eigen::VectorXd dq = Eigen::VectorXd::Zero(dimv); dq(i) = 1; robot_.integrateConfiguration(s.q, dq, finite_diff_, s1.q); robot_.updateKinematics(s1.q, s1.v, s1.a); lq_ref(i) = (cost->evalStageCost(robot_, contact_status, data, grid_info, s1) - cost0) / finite_diff_; } if (!kkt_residual.lq().isApprox(lq_ref, test_tol_)) { std::cout << "lq is not correct! lq - lq_ref = " << (kkt_residual.lq() - lq_ref).transpose() << std::endl; return false; } Eigen::VectorXd lv_ref(dimv); for (int i=0; i<dimv; ++i) { s1 = s; s1.v(i) += finite_diff_; robot_.updateKinematics(s1.q, s1.v, s1.a); lv_ref(i) = (cost->evalStageCost(robot_, contact_status, data, grid_info, s1) - cost0) / finite_diff_; } if (!kkt_residual.lv().isApprox(lv_ref, test_tol_)) { std::cout << "lv is not correct! lv - lv_ref = " << (kkt_residual.lv() - lv_ref).transpose() << std::endl; return false; } Eigen::VectorXd la_ref(dimv); for (int i=0; i<dimv; ++i) { s1 = s; s1.a(i) += finite_diff_; robot_.updateKinematics(s1.q, s1.v, s1.a); la_ref(i) = (cost->evalStageCost(robot_, contact_status, data, grid_info, s1) - cost0) / finite_diff_; } if (!kkt_residual.la.isApprox(la_ref, test_tol_)) { std::cout << "la is not correct! la - la_ref = " << (kkt_residual.la - la_ref).transpose() << std::endl; return false; } Eigen::VectorXd lu_ref(dimu); for (int i=0; i<dimu; ++i) { s1 = s; s1.u(i) += finite_diff_; lu_ref(i) = (cost->evalStageCost(robot_, contact_status, data, grid_info, s1) - cost0) / finite_diff_; } if (!kkt_residual.lu.isApprox(lu_ref, test_tol_)) { std::cout << "lu is not correct! lu - lu_ref = " << (kkt_residual.lu - lu_ref).transpose() << std::endl; return false; } Eigen::VectorXd lf_ref(dimf); if (dimf > 0) { for (int i=0; i<dimf; ++i) { s1 = s; s1.f_stack().coeffRef(i) += finite_diff_; s1.set_f_vector(); lf_ref(i) = (cost->evalStageCost(robot_, contact_status, data, grid_info, s1) - cost0) / finite_diff_; } if (!kkt_residual.lf().isApprox(lf_ref, test_tol_)) { std::cout << "lf is not correct! lf - lf_ref = " << (kkt_residual.lf() - lf_ref).transpose() << std::endl; return false; } } return true; } bool DerivativeChecker::checkSecondOrderStageCostDerivatives( const std::shared_ptr<CostFunctionComponentBase>& cost, const ContactStatus& contact_status) { const auto s = SplitSolution::Random(robot_, contact_status); const auto grid_info = GridInfo::Random(); const int dimv = robot_.dimv(); const int dimu = robot_.dimu(); const int dimf = contact_status.dimf(); SplitKKTResidual kkt_residual0(robot_); kkt_residual0.setContactStatus(contact_status); SplitKKTMatrix kkt_matrix(robot_); kkt_matrix.setContactStatus(contact_status); CostFunctionData data(robot_); robot_.updateKinematics(s.q, s.v, s.a); cost->evalStageCost(robot_, contact_status, data, grid_info, s); cost->evalStageCostDerivatives(robot_, contact_status, data, grid_info, s, kkt_residual0); cost->evalStageCostHessian(robot_, contact_status, data, grid_info, s, kkt_matrix); SplitKKTResidual kkt_residual(robot_); kkt_residual.setContactStatus(contact_status); auto s1 = s; Eigen::MatrixXd Qqq_ref(dimv, dimv); for (int i=0; i<dimv; ++i) { s1 = s; Eigen::VectorXd dq = Eigen::VectorXd::Zero(dimv); dq(i) = 1; robot_.integrateConfiguration(s.q, dq, finite_diff_, s1.q); robot_.updateKinematics(s1.q, s1.v, s1.a); kkt_residual.lq().setZero(); cost->evalStageCost(robot_, contact_status, data, grid_info, s1); cost->evalStageCostDerivatives(robot_, contact_status, data, grid_info, s1, kkt_residual); Qqq_ref.col(i) = (kkt_residual.lq() - kkt_residual0.lq()) / finite_diff_; } if (!kkt_matrix.Qqq().isApprox(Qqq_ref, test_tol_)) { std::cout << "Qqq is not correct! Qqq - Qqq_ref = " << (kkt_matrix.Qqq() - Qqq_ref).transpose() << std::endl; return false; } Eigen::MatrixXd Qvv_ref(dimv, dimv); for (int i=0; i<dimv; ++i) { s1 = s; s1.v(i) += finite_diff_; robot_.updateKinematics(s1.q, s1.v, s1.a); kkt_residual.lv().setZero(); cost->evalStageCost(robot_, contact_status, data, grid_info, s1); cost->evalStageCostDerivatives(robot_, contact_status, data, grid_info, s1, kkt_residual); Qvv_ref.col(i) = (kkt_residual.lv() - kkt_residual0.lv()) / finite_diff_; } if (!kkt_matrix.Qvv().isApprox(Qvv_ref, test_tol_)) { std::cout << "Qvv is not correct! Qvv - Qvv_ref = " << (kkt_matrix.Qvv() - Qvv_ref).transpose() << std::endl; return false; } Eigen::MatrixXd Qaa_ref(dimv, dimv); for (int i=0; i<dimv; ++i) { s1 = s; s1.a(i) += finite_diff_; robot_.updateKinematics(s1.q, s1.v, s1.a); kkt_residual.la.setZero(); cost->evalStageCost(robot_, contact_status, data, grid_info, s1); cost->evalStageCostDerivatives(robot_, contact_status, data, grid_info, s1, kkt_residual); Qaa_ref.col(i) = (kkt_residual.la - kkt_residual0.la) / finite_diff_; } if (!kkt_matrix.Qaa.isApprox(Qaa_ref, test_tol_)) { std::cout << "Qaa is not correct! Qaa - Qaa_ref = " << (kkt_matrix.Qaa - Qaa_ref).transpose() << std::endl; return false; } Eigen::MatrixXd Quu_ref(dimu, dimu); for (int i=0; i<dimu; ++i) { s1 = s; s1.u(i) += finite_diff_; kkt_residual.lu.setZero(); cost->evalStageCost(robot_, contact_status, data, grid_info, s1); cost->evalStageCostDerivatives(robot_, contact_status, data, grid_info, s1, kkt_residual); Quu_ref.col(i) = (kkt_residual.lu - kkt_residual0.lu) / finite_diff_; } if (!kkt_matrix.Quu.isApprox(Quu_ref, test_tol_)) { std::cout << "Quu is not correct! Quu - Quu_ref = " << (kkt_matrix.Quu - Quu_ref).transpose() << std::endl; return false; } Eigen::MatrixXd Qff_ref(dimf, dimf); if (dimf > 0) { for (int i=0; i<dimf; ++i) { s1 = s; s1.f_stack().coeffRef(i) += finite_diff_; s1.set_f_vector(); kkt_residual.lf().setZero(); cost->evalStageCost(robot_, contact_status, data, grid_info, s1); cost->evalStageCostDerivatives(robot_, contact_status, data, grid_info, s1, kkt_residual); Qff_ref.col(i) = (kkt_residual.lf() - kkt_residual0.lf()) / finite_diff_; } if (!kkt_matrix.Qff().isApprox(Qff_ref, test_tol_)) { std::cout << "Qff is not correct! Qff - Qff_ref = " << (kkt_matrix.Qff() - Qff_ref).transpose() << std::endl; return false; } } return true; } bool DerivativeChecker::checkFirstOrderTerminalCostDerivatives( const std::shared_ptr<CostFunctionComponentBase>& cost) { const auto s = SplitSolution::Random(robot_); const auto grid_info = GridInfo::Random(); const int dimv = robot_.dimv(); SplitKKTResidual kkt_residual(robot_); CostFunctionData data(robot_); robot_.updateKinematics(s.q, s.v); double cost0 = cost->evalTerminalCost(robot_, data, grid_info, s); cost->evalTerminalCostDerivatives(robot_, data, grid_info, s, kkt_residual); auto s1 = s; Eigen::VectorXd lq_ref(dimv); for (int i=0; i<dimv; ++i) { s1 = s; Eigen::VectorXd dq = Eigen::VectorXd::Zero(dimv); dq(i) = 1; robot_.integrateConfiguration(s.q, dq, finite_diff_, s1.q); robot_.updateKinematics(s1.q, s1.v); lq_ref(i) = (cost->evalTerminalCost(robot_, data, grid_info, s1) - cost0) / finite_diff_; } if (!kkt_residual.lq().isApprox(lq_ref, test_tol_)) { std::cout << "lq is not correct! lq - lq_ref = " << (kkt_residual.lq() - lq_ref).transpose() << std::endl; return false; } Eigen::VectorXd lv_ref(dimv); for (int i=0; i<dimv; ++i) { s1 = s; s1.v(i) += finite_diff_; robot_.updateKinematics(s1.q, s1.v); lv_ref(i) = (cost->evalTerminalCost(robot_, data, grid_info, s1) - cost0) / finite_diff_; } if (!kkt_residual.lv().isApprox(lv_ref, test_tol_)) { std::cout << "lv is not correct! lv - lv_ref = " << (kkt_residual.lv() - lv_ref).transpose() << std::endl; return false; } return true; } bool DerivativeChecker::checkSecondOrderTerminalCostDerivatives( const std::shared_ptr<CostFunctionComponentBase>& cost) { const auto s = SplitSolution::Random(robot_); const auto grid_info = GridInfo::Random(); const int dimv = robot_.dimv(); SplitKKTMatrix kkt_matrix(robot_); SplitKKTResidual kkt_residual0(robot_); CostFunctionData data(robot_); robot_.updateKinematics(s.q, s.v); cost->evalTerminalCost(robot_, data, grid_info, s); cost->evalTerminalCostDerivatives(robot_, data, grid_info, s, kkt_residual0); cost->evalTerminalCostHessian(robot_, data, grid_info, s, kkt_matrix); SplitKKTResidual kkt_residual(robot_); auto s1 = s; Eigen::MatrixXd Qqq_ref(dimv, dimv); for (int i=0; i<dimv; ++i) { s1 = s; Eigen::VectorXd dq = Eigen::VectorXd::Zero(dimv); dq(i) = 1; robot_.integrateConfiguration(s.q, dq, finite_diff_, s1.q); robot_.updateKinematics(s1.q, s1.v); kkt_residual.lq().setZero(); cost->evalTerminalCost(robot_, data, grid_info, s1); cost->evalTerminalCostDerivatives(robot_, data, grid_info, s1, kkt_residual); Qqq_ref.col(i) = (kkt_residual.lq() - kkt_residual0.lq()) / finite_diff_; } if (!kkt_matrix.Qqq().isApprox(Qqq_ref, test_tol_)) { std::cout << "Qqq is not correct! Qqq - Qqq_ref = " << (kkt_matrix.Qqq() - Qqq_ref).transpose() << std::endl; return false; } Eigen::MatrixXd Qvv_ref(dimv, dimv); for (int i=0; i<dimv; ++i) { s1 = s; s1.v(i) += finite_diff_; robot_.updateKinematics(s1.q, s1.v); kkt_residual.lv().setZero(); cost->evalTerminalCost(robot_, data, grid_info, s1); cost->evalTerminalCostDerivatives(robot_, data, grid_info, s1, kkt_residual); Qvv_ref.col(i) = (kkt_residual.lv() - kkt_residual0.lv()) / finite_diff_; } if (!kkt_matrix.Qvv().isApprox(Qvv_ref, test_tol_)) { std::cout << "Qvv is not correct! Qvv - Qvv_ref = " << (kkt_matrix.Qvv() - Qvv_ref).transpose() << std::endl; return false; } return true; } bool DerivativeChecker::checkFirstOrderImpulseCostDerivatives( const std::shared_ptr<CostFunctionComponentBase>& cost) { return checkFirstOrderImpulseCostDerivatives(cost, robot_.createImpulseStatus()); } bool DerivativeChecker::checkSecondOrderImpulseCostDerivatives( const std::shared_ptr<CostFunctionComponentBase>& cost) { return checkSecondOrderImpulseCostDerivatives(cost, robot_.createImpulseStatus()); } bool DerivativeChecker::checkFirstOrderImpulseCostDerivatives( const std::shared_ptr<CostFunctionComponentBase>& cost, const ImpulseStatus& impulse_status) { const auto s = ImpulseSplitSolution::Random(robot_, impulse_status); const auto grid_info = GridInfo::Random(); const int dimv = robot_.dimv(); const int dimf = impulse_status.dimi(); ImpulseSplitKKTResidual kkt_residual(robot_); kkt_residual.setImpulseStatus(impulse_status); CostFunctionData data(robot_); robot_.updateKinematics(s.q, s.v); double cost0 = cost->evalImpulseCost(robot_, impulse_status, data, grid_info, s); cost->evalImpulseCostDerivatives(robot_, impulse_status, data, grid_info, s, kkt_residual); auto s1 = s; Eigen::VectorXd lq_ref(dimv); for (int i=0; i<dimv; ++i) { s1 = s; Eigen::VectorXd dq = Eigen::VectorXd::Zero(dimv); dq(i) = 1; robot_.integrateConfiguration(s.q, dq, finite_diff_, s1.q); robot_.updateKinematics(s1.q, s1.v); lq_ref(i) = (cost->evalImpulseCost(robot_, impulse_status, data, grid_info, s1) - cost0) / finite_diff_; } if (!kkt_residual.lq().isApprox(lq_ref, test_tol_)) { std::cout << "lq is not correct! lq - lq_ref = " << (kkt_residual.lq() - lq_ref).transpose() << std::endl; return false; } Eigen::VectorXd lv_ref(dimv); for (int i=0; i<dimv; ++i) { s1 = s; s1.v(i) += finite_diff_; robot_.updateKinematics(s1.q, s1.v); lv_ref(i) = (cost->evalImpulseCost(robot_, impulse_status, data, grid_info, s1) - cost0) / finite_diff_; } if (!kkt_residual.lv().isApprox(lv_ref, test_tol_)) { std::cout << "lv is not correct! lv - lv_ref = " << (kkt_residual.lv() - lv_ref).transpose() << std::endl; return false; } Eigen::VectorXd ldv_ref(dimv); for (int i=0; i<dimv; ++i) { s1 = s; s1.dv(i) += finite_diff_; ldv_ref(i) = (cost->evalImpulseCost(robot_, impulse_status, data, grid_info, s1) - cost0) / finite_diff_; } if (!kkt_residual.ldv.isApprox(ldv_ref, test_tol_)) { std::cout << "ldv is not correct! ldv - ldv_ref = " << (kkt_residual.ldv - ldv_ref).transpose() << std::endl; return false; } Eigen::VectorXd lf_ref(dimf); if (dimf > 0) { for (int i=0; i<dimf; ++i) { s1 = s; s1.f_stack().coeffRef(i) += finite_diff_; s1.set_f_vector(); lf_ref(i) = (cost->evalImpulseCost(robot_, impulse_status, data, grid_info, s1) - cost0) / finite_diff_; } if (!kkt_residual.lf().isApprox(lf_ref, test_tol_)) { std::cout << "lf is not correct! lf - lf_ref = " << (kkt_residual.lf() - lf_ref).transpose() << std::endl; return false; } } return true; } bool DerivativeChecker::checkSecondOrderImpulseCostDerivatives( const std::shared_ptr<CostFunctionComponentBase>& cost, const ImpulseStatus& impulse_status) { const auto s = ImpulseSplitSolution::Random(robot_, impulse_status); const auto grid_info = GridInfo::Random(); const int dimv = robot_.dimv(); const int dimf = impulse_status.dimi(); ImpulseSplitKKTMatrix kkt_matrix(robot_); kkt_matrix.setImpulseStatus(impulse_status); ImpulseSplitKKTResidual kkt_residual0(robot_); kkt_residual0.setImpulseStatus(impulse_status); CostFunctionData data(robot_); robot_.updateKinematics(s.q, s.v); cost->evalImpulseCost(robot_, impulse_status, data, grid_info, s); cost->evalImpulseCostDerivatives(robot_, impulse_status, data, grid_info, s, kkt_residual0); cost->evalImpulseCostHessian(robot_, impulse_status, data, grid_info, s, kkt_matrix); ImpulseSplitKKTResidual kkt_residual(robot_); kkt_residual.setImpulseStatus(impulse_status); auto s1 = s; Eigen::MatrixXd Qqq_ref(dimv, dimv); for (int i=0; i<dimv; ++i) { s1 = s; Eigen::VectorXd dq = Eigen::VectorXd::Zero(dimv); dq(i) = 1; robot_.integrateConfiguration(s.q, dq, finite_diff_, s1.q); kkt_residual.lq().setZero(); robot_.updateKinematics(s1.q, s1.v); cost->evalImpulseCost(robot_, impulse_status, data, grid_info, s1); cost->evalImpulseCostDerivatives(robot_, impulse_status, data, grid_info, s1, kkt_residual); Qqq_ref.col(i) = (kkt_residual.lq() - kkt_residual0.lq()) / finite_diff_; } if (!kkt_matrix.Qqq().isApprox(Qqq_ref, test_tol_)) { std::cout << "Qqq is not correct! Qqq - Qqq_ref = " << (kkt_matrix.Qqq() - Qqq_ref).transpose() << std::endl; return false; } Eigen::MatrixXd Qvv_ref(dimv, dimv); for (int i=0; i<dimv; ++i) { s1 = s; s1.v(i) += finite_diff_; kkt_residual.lv().setZero(); robot_.updateKinematics(s1.q, s1.v); cost->evalImpulseCost(robot_, impulse_status, data, grid_info, s1); cost->evalImpulseCostDerivatives(robot_, impulse_status, data, grid_info, s1, kkt_residual); Qvv_ref.col(i) = (kkt_residual.lv() - kkt_residual0.lv()) / finite_diff_; } if (!kkt_matrix.Qvv().isApprox(Qvv_ref, test_tol_)) { std::cout << "Qvv is not correct! Qvv - Qvv_ref = " << (kkt_matrix.Qvv() - Qvv_ref).transpose() << std::endl; return false; } Eigen::MatrixXd Qdvdv_ref(dimv, dimv); for (int i=0; i<dimv; ++i) { s1 = s; s1.dv(i) += finite_diff_; kkt_residual.ldv.setZero(); cost->evalImpulseCost(robot_, impulse_status, data, grid_info, s1); cost->evalImpulseCostDerivatives(robot_, impulse_status, data, grid_info, s1, kkt_residual); Qdvdv_ref.col(i) = (kkt_residual.ldv - kkt_residual0.ldv) / finite_diff_; } if (!kkt_matrix.Qdvdv.isApprox(Qdvdv_ref, test_tol_)) { std::cout << "Qdvdv is not correct! Qdvdv - Qdvdv_ref = " << (kkt_matrix.Qdvdv - Qdvdv_ref).transpose() << std::endl; return false; } Eigen::MatrixXd Qff_ref(dimf, dimf); if (dimf > 0) { for (int i=0; i<dimf; ++i) { s1 = s; s1.f_stack().coeffRef(i) += finite_diff_; s1.set_f_vector(); kkt_residual.lf().setZero(); cost->evalImpulseCost(robot_, impulse_status, data, grid_info, s1); cost->evalImpulseCostDerivatives(robot_, impulse_status, data, grid_info, s1, kkt_residual); Qff_ref.col(i) = (kkt_residual.lf() - kkt_residual0.lf()) / finite_diff_; } if (!kkt_matrix.Qff().isApprox(Qff_ref, test_tol_)) { std::cout << "Qff is not correct! Qff - Qff_ref = " << (kkt_matrix.Qff() - Qff_ref).transpose() << std::endl; return false; } } return true; } } // namespace robotoc
19,074
7,859
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2015 - ROLI Ltd. Permission is granted to use this software under the terms of either: a) the GPL v2 (or any later version) b) the Affero GPL v3 Details of these licenses can be found at: www.gnu.org/licenses JUCE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.juce.com for more information. ============================================================================== */ // This file contains the implementations of the various AudioParameter[XYZ] classes.. AudioProcessorParameterWithID::AudioProcessorParameterWithID (String pid, String nm) : paramID (pid), name (nm) {} AudioProcessorParameterWithID::~AudioProcessorParameterWithID() {} String AudioProcessorParameterWithID::getName (int maximumStringLength) const { return name.substring (0, maximumStringLength); } String AudioProcessorParameterWithID::getLabel() const { return label; } //============================================================================== AudioParameterFloat::AudioParameterFloat (String pid, String nm, NormalisableRange<float> r, float def) : AudioProcessorParameterWithID (pid, nm), range (r), value (def), defaultValue (def) { } AudioParameterFloat::AudioParameterFloat (String pid, String nm, float minValue, float maxValue, float def) : AudioProcessorParameterWithID (pid, nm), range (minValue, maxValue), value (def), defaultValue (def) { } AudioParameterFloat::~AudioParameterFloat() {} float AudioParameterFloat::getValue() const { return range.convertTo0to1 (value); } void AudioParameterFloat::setValue (float newValue) { value = range.convertFrom0to1 (newValue); } float AudioParameterFloat::getDefaultValue() const { return range.convertTo0to1 (defaultValue); } int AudioParameterFloat::getNumSteps() const { return AudioProcessorParameterWithID::getNumSteps(); } float AudioParameterFloat::getValueForText (const String& text) const { return range.convertTo0to1 (text.getFloatValue()); } String AudioParameterFloat::getText (float v, int length) const { String asText (range.convertFrom0to1 (v), 2); return length > 0 ? asText.substring (0, length) : asText; } AudioParameterFloat& AudioParameterFloat::operator= (float newValue) { if (value != newValue) setValueNotifyingHost (range.convertTo0to1 (newValue)); return *this; } //============================================================================== AudioParameterInt::AudioParameterInt (String pid, String nm, int mn, int mx, int def) : AudioProcessorParameterWithID (pid, nm), minValue (mn), maxValue (mx), value ((float) def), defaultValue (convertTo0to1 (def)) { jassert (minValue < maxValue); // must have a non-zero range of values! } AudioParameterInt::~AudioParameterInt() {} int AudioParameterInt::limitRange (int v) const noexcept { return jlimit (minValue, maxValue, v); } float AudioParameterInt::convertTo0to1 (int v) const noexcept { return (limitRange (v) - minValue) / (float) (maxValue - minValue); } int AudioParameterInt::convertFrom0to1 (float v) const noexcept { return limitRange (roundToInt ((v * (float) (maxValue - minValue)) + minValue)); } float AudioParameterInt::getValue() const { return convertTo0to1 (roundToInt (value)); } void AudioParameterInt::setValue (float newValue) { value = (float) convertFrom0to1 (newValue); } float AudioParameterInt::getDefaultValue() const { return defaultValue; } int AudioParameterInt::getNumSteps() const { return AudioProcessorParameterWithID::getNumSteps(); } float AudioParameterInt::getValueForText (const String& text) const { return convertTo0to1 (text.getIntValue()); } String AudioParameterInt::getText (float v, int /*length*/) const { return String (convertFrom0to1 (v)); } AudioParameterInt& AudioParameterInt::operator= (int newValue) { if (get() != newValue) setValueNotifyingHost (convertTo0to1 (newValue)); return *this; } //============================================================================== AudioParameterBool::AudioParameterBool (String pid, String nm, bool def) : AudioProcessorParameterWithID (pid, nm), value (def ? 1.0f : 0.0f), defaultValue (value) { } AudioParameterBool::~AudioParameterBool() {} float AudioParameterBool::getValue() const { return value; } void AudioParameterBool::setValue (float newValue) { value = newValue; } float AudioParameterBool::getDefaultValue() const { return defaultValue; } int AudioParameterBool::getNumSteps() const { return 2; } float AudioParameterBool::getValueForText (const String& text) const { return text.getIntValue() != 0 ? 1.0f : 0.0f; } String AudioParameterBool::getText (float v, int /*length*/) const { return String ((int) (v > 0.5f ? 1 : 0)); } AudioParameterBool& AudioParameterBool::operator= (bool newValue) { if (get() != newValue) setValueNotifyingHost (newValue ? 1.0f : 0.0f); return *this; } //============================================================================== AudioParameterChoice::AudioParameterChoice (String pid, String nm, const StringArray& c, int def) : AudioProcessorParameterWithID (pid, nm), choices (c), value ((float) def), defaultValue (convertTo0to1 (def)) { jassert (choices.size() > 0); // you must supply an actual set of items to choose from! } AudioParameterChoice::~AudioParameterChoice() {} int AudioParameterChoice::limitRange (int v) const noexcept { return jlimit (0, choices.size() - 1, v); } float AudioParameterChoice::convertTo0to1 (int v) const noexcept { return jlimit (0.0f, 1.0f, (v + 0.5f) / (float) choices.size()); } int AudioParameterChoice::convertFrom0to1 (float v) const noexcept { return limitRange ((int) (v * (float) choices.size())); } float AudioParameterChoice::getValue() const { return convertTo0to1 (roundToInt (value)); } void AudioParameterChoice::setValue (float newValue) { value = (float) convertFrom0to1 (newValue); } float AudioParameterChoice::getDefaultValue() const { return defaultValue; } int AudioParameterChoice::getNumSteps() const { return choices.size(); } float AudioParameterChoice::getValueForText (const String& text) const { return convertTo0to1 (choices.indexOf (text)); } String AudioParameterChoice::getText (float v, int /*length*/) const { return choices [convertFrom0to1 (v)]; } AudioParameterChoice& AudioParameterChoice::operator= (int newValue) { if (getIndex() != newValue) setValueNotifyingHost (convertTo0to1 (newValue)); return *this; }
7,479
1,996
/*BISMILLAH THE WHITE WOLF NO DREAM IS TOO BIG AND NO DREAMER IS TOO SMALL*/ #include<bits/stdc++.h> using namespace std; int priority_ind[16][16], dp[1<<16], n; int Set(int n, int pos) { return n|(1<<pos); } bool check(int n, int pos) { return (bool)(n & (1<<pos)); } int counting(int m) { int cou = 0; while(m) { if(check(m, 0)) cou++; m >>= 1; } return cou; } int bitmask() { for(int mask = 0; mask<=(1<<n)-1; mask++) { int x = counting(mask); for(int j = 0; j <n; j++) { if(!check(mask, j)) { dp[Set(mask, j)] = max(dp[Set(mask, j)], dp[mask] + priority_ind[x][j]); } } } return dp[(1<<n) - 1]; } int main() { int tc; cin >> tc; for(int i = 1; i <= tc; i++) { cin >> n; memset(priority_ind, 0, sizeof(priority_ind)); memset(dp, INT_MIN, sizeof(dp)); for(int a = 0; a<n; a++) for(int b = 0; b < n; b++) cin >> priority_ind[a][b]; printf("Case %d: %d\n", i, bitmask()); } return 0; }
1,149
489
/* * Copyright (c) 2019-2020, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cuda_runtime.h> #include <raft/cudart_utils.h> #include <memory> #include <utility> namespace raft { namespace mr { /** * @brief Base for all RAII-based owning of temporary memory allocations. This * class should ideally not be used by users directly, but instead via * the child classes `device_buffer` and `host_buffer`. * * @tparam T data type * @tparam AllocatorT The underly allocator object */ template <typename T, typename AllocatorT> class buffer_base { public: using size_type = std::size_t; using value_type = T; using iterator = value_type*; using const_iterator = const value_type*; using reference = T&; using const_reference = const T&; buffer_base() = delete; buffer_base(const buffer_base& other) = delete; buffer_base& operator=(const buffer_base& other) = delete; /** * @brief Main ctor * * @param[in] allocator asynchronous allocator used for managing buffer life * @param[in] stream cuda stream where this allocation operations are async * @param[in] n size of the buffer (in number of elements) */ buffer_base(std::shared_ptr<AllocatorT> allocator, cudaStream_t stream, size_type n = 0) : data_(nullptr), size_(n), capacity_(n), stream_(stream), allocator_(std::move(allocator)) { if (capacity_ > 0) { data_ = static_cast<value_type*>( allocator_->allocate(capacity_ * sizeof(value_type), stream_)); CUDA_CHECK(cudaStreamSynchronize(stream_)); } } ~buffer_base() { release(); } value_type* data() { return data_; } const value_type* data() const { return data_; } size_type size() const { return size_; } void clear() { size_ = 0; } iterator begin() { return data_; } const_iterator begin() const { return data_; } iterator end() { return data_ + size_; } const_iterator end() const { return data_ + size_; } /** * @brief Reserve new memory size for this buffer. * * It re-allocates a fresh buffer if the new requested capacity is more than * the current one, copies the old buffer contents to this new buffer and * removes the old one. * * @param[in] new_capacity new capacity (in number of elements) * @param[in] stream cuda stream where allocation operations are queued * @{ */ void reserve(size_type new_capacity) { if (new_capacity > capacity_) { auto* new_data = static_cast<value_type*>( allocator_->allocate(new_capacity * sizeof(value_type), stream_)); if (size_ > 0) { raft::copy(new_data, data_, size_, stream_); } // Only deallocate if we have allocated a pointer if (nullptr != data_) { allocator_->deallocate(data_, capacity_ * sizeof(value_type), stream_); } data_ = new_data; capacity_ = new_capacity; } } void reserve(size_type new_capacity, cudaStream_t stream) { set_stream(stream); reserve(new_capacity); } /** @} */ /** * @brief Resize the underlying buffer (uses `reserve` method internally) * * @param[in] new_size new buffer size * @param[in] stream cuda stream where the work will be queued * @{ */ void resize(const size_type new_size) { reserve(new_size); size_ = new_size; } void resize(const size_type new_size, cudaStream_t stream) { set_stream(stream); resize(new_size); } /** @} */ /** * @brief Deletes the underlying buffer * * If this method is not explicitly called, it will be during the destructor * * @param[in] stream cuda stream where the work will be queued * @{ */ void release() { if (nullptr != data_) { allocator_->deallocate(data_, capacity_ * sizeof(value_type), stream_); } data_ = nullptr; capacity_ = 0; size_ = 0; } void release(cudaStream_t stream) { set_stream(stream); release(); } /** @} */ /** * @brief returns the underlying allocator used * * @return the allocator pointer */ std::shared_ptr<AllocatorT> get_allocator() const { return allocator_; } /** * @brief returns the underlying stream used * * @return the cuda stream */ cudaStream_t get_stream() const { return stream_; } protected: value_type* data_; private: size_type size_; size_type capacity_; cudaStream_t stream_; std::shared_ptr<AllocatorT> allocator_; /** * @brief Sets a new cuda stream where the future operations will be queued * * This method makes sure that the inter-stream dependencies are met and taken * care of, before setting the input stream as a new stream for this buffer. * Ideally, the same cuda stream passed during constructor is expected to be * used throughout this buffer's lifetime, for performance. * * @param[in] stream new cuda stream to be set. If it is the same as the * current one, then this method will be a no-op. */ void set_stream(cudaStream_t stream) { if (stream_ != stream) { cudaEvent_t event; CUDA_CHECK(cudaEventCreateWithFlags(&event, cudaEventDisableTiming)); CUDA_CHECK(cudaEventRecord(event, stream_)); CUDA_CHECK(cudaStreamWaitEvent(stream, event, 0)); stream_ = stream; CUDA_CHECK(cudaEventDestroy(event)); } } }; // class buffer_base }; // namespace mr }; // namespace raft
6,002
1,927
/** * Provides the ImageHandler class used by the AssetManager to manage all * sf::Image assets for the application. * * @file src/GQE/Core/assets/ImageHandler.cpp * @author Ryan Lindeman * @date 20120428 - Initial Release */ #include <GQE/Core/assets/ImageHandler.hpp> #include <GQE/Core/loggers/Log_macros.hpp> namespace GQE { ImageHandler::ImageHandler() : #if (SFML_VERSION_MAJOR < 2) TAssetHandler<sf::Image>() #else TAssetHandler<sf::Texture>() #endif { ILOG() << "ImageHandler::ctor()" << std::endl; } ImageHandler::~ImageHandler() { ILOG() << "ImageHandler::dtor()" << std::endl; } #if (SFML_VERSION_MAJOR < 2) bool ImageHandler::LoadFromFile(const typeAssetID theAssetID, sf::Image& theAsset) #else bool ImageHandler::LoadFromFile(const typeAssetID theAssetID, sf::Texture& theAsset) #endif { // Start with a return result of false bool anResult = false; // Retrieve the filename for this asset std::string anFilename = GetFilename(theAssetID); // Was a valid filename found? then attempt to load the asset from anFilename if(anFilename.length() > 0) { // Load the asset from a file #if (SFML_VERSION_MAJOR < 2) anResult = theAsset.LoadFromFile(anFilename); // Don't forget to set smoothing to false to better support tile base games theAsset.SetSmooth(false); #else anResult = theAsset.loadFromFile(anFilename); #endif } else { ELOG() << "ImageHandler::LoadFromFile(" << theAssetID << ") No filename provided!" << std::endl; } // Return anResult of true if successful, false otherwise return anResult; } #if (SFML_VERSION_MAJOR < 2) bool ImageHandler::LoadFromMemory(const typeAssetID theAssetID, sf::Image& theAsset) #else bool ImageHandler::LoadFromMemory(const typeAssetID theAssetID, sf::Texture& theAsset) #endif { // Start with a return result of false bool anResult = false; // TODO: Retrieve the const char* pointer to load data from const char* anData = NULL; // TODO: Retrieve the size in bytes of the font to load from memory size_t anDataSize = 0; // Try to obtain the font from the memory location specified if(NULL != anData && anDataSize > 0) { // Load the image from the memory location specified #if (SFML_VERSION_MAJOR < 2) anResult = theAsset.LoadFromMemory(anData, anDataSize); // Don't forget to set smoothing to false to better support tile base games theAsset.SetSmooth(false); #else anResult = theAsset.loadFromMemory(anData, anDataSize); #endif } else { ELOG() << "ImageHandler::LoadFromMemory(" << theAssetID << ") Bad memory location or size!" << std::endl; } // Return anResult of true if successful, false otherwise return anResult; } #if (SFML_VERSION_MAJOR < 2) bool ImageHandler::LoadFromNetwork(const typeAssetID theAssetID, sf::Image& theAsset) #else bool ImageHandler::LoadFromNetwork(const typeAssetID theAssetID, sf::Texture& theAsset) #endif { // Start with a return result of false bool anResult = false; // TODO: Add load from network for this asset // Return anResult of true if successful, false otherwise return anResult; } } // namespace GQE /** * Copyright (c) 2010-2012 Ryan Lindeman * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */
4,553
1,486
// This file is part of CxxDoc, The RAVL C++ Documentation tool // Copyright (C) 2001, University of Surrey // This code may be redistributed under the terms of the GNU General // Public License (GPL). See the gpl.licence file for details or // see http://www.gnu.org/copyleft/gpl.html // file-header-ends-here #ifndef RAVLCXXDOC_DOCUMENT_HEADER #define RAVLCXXDOC_DOCUMENT_HEADER 1 ////////////////////////////////////////////////////////// //! rcsid="$Id: Document.hh 5240 2005-12-06 17:16:50Z plugger $" //! file="Ravl/SourceTools/CxxDoc/Document.hh" //! userlevel=Default //! lib=RavlCxxDoc //! docentry="Ravl.API.Source Tools.CxxDoc.Internal" //! author="Charles Galambos" //! date="03/02/2000" #include "Ravl/Text/TemplateComplex.hh" #include "Ravl/Text/TextFile.hh" #include "Ravl/Hash.hh" #include "Ravl/RCHash.hh" #include "Ravl/HSet.hh" #include "Ravl/CxxDoc/Object.hh" #include "Ravl/CxxDoc/DocTree.hh" #include "Ravl/OS/Filename.hh" //: C++ parser namespace. // This namespace contains the classes that make up the parser, the parse tree // and the C++ documenation system. namespace RavlCxxDocN { using namespace RavlN; class DataTypeC ; //! userlevel=Develop //: Documenter Body. class DocumentBodyC : public TemplateComplexBodyC, public DesciptionGeneratorC { public: DocumentBodyC(const FilenameC &tmplName,const StringC &outDir,const DocTreeC &docTree = DocTreeC(),const StringC &projName = StringC(),const StringC &projDesc = StringC()); //: Default contructor. bool Foralli(StringC &data,bool ifAny = false,bool inClassScope = false); //: Do a forall build. bool Forall(StringC &data) { return Foralli(data); } //: Do a forall build. bool IfAny(StringC &data) { return Foralli(data,true); } //: Do a forall build. bool GotoInherit(StringC &param); //: Goto an inherited class. bool MakeFilenameCmd(StringC &pattern); //: Make a filename from a pattern and a full object name. bool InsertDocNode(StringC &node); //: Insert a DocNodeC into the documentation tree. bool AutoLink(StringC &text); //: Automaticly put links in some text. bool Exec(StringC &text); //: Execute a child process. bool ForDir(StringC &text); //: Go through files in a directory. void Document(ObjectListC &ol); //: Document list of files. FilenameC MakeFilename(ObjectC &obj,bool relative = false); //: Makefile name FilenameC MakeFilename(StringC pattern,ObjectC &obj,bool relative = false); //: Make a filename from a pattern and a full object name. bool HtmlMethodName(StringC &arg); //: Make a linked version of the method name. StringC GetHtmlTypeName(const DataTypeC &tn); //: Make a linked version of the method name. bool HtmlTypeName(StringC &arg); //: Make a linked version of the method name. StringC MakeHRef(StringC name); //: Make a string suitable for an href. virtual bool Lookup(const StringC &varname,StringC &buff); //: Lookup variable. // if found put value into 'buff' and return true. // otherwise return false. DocTreeC &DocTree() { return docTree; } //: Access doc tree. protected: void Init(); //: Get initalise information from template file. void InitVars(); //: Init known vars list. virtual StringC TextFor(const ObjectC &obj); //: How to render an object into html. virtual StringC TextFor(char let); //: How to render an char into html. virtual StringC TextFor(const StringC &obj); //: How to render a string in html. virtual StringC MethodNameText(const StringC &obj); //: Render a method name appropriatly. (e.g. bold.) StringC TemplateNameSubst(const StringC &x); //: If there's a substituation use it. StringC outputDir; StringC fileObject; StringC filePattern; StringC refPattern; StackC<ObjectC> obj; StackC<RCHashC<StringC,ObjectC> > templArgSub; // Template argument subsitutions. HSetC<StringC> knownVars; DocTreeC docTree; ObjectListC root; bool verbose; }; //! userlevel=Normal //: Documentor class DocumentC : public TemplateComplexC { public: DocumentC() {} //: Default contructor. // Creates an invalid handle. DocumentC(const FilenameC &tmplName,const StringC &outDir,const DocTreeC &docTree = DocTreeC(),const StringC &projName = StringC(),const StringC &projDesc = StringC()) : TemplateComplexC(*new DocumentBodyC(tmplName,outDir,docTree,projName,projDesc)) {} //: Contructor. // Create a documentor protected: DocumentBodyC &Body() { return static_cast<DocumentBodyC &>(TemplateComplexC::Body()); } //: Access body. const DocumentBodyC &Body() const { return static_cast<const DocumentBodyC &>(TemplateComplexC::Body()); } //: Access body. public: void Document(ObjectListC &ol) { Body().Document(ol); } //: Document list of files. DocTreeC &DocTree() { return Body().DocTree(); } //: Access doc tree. }; } #endif
5,225
1,732
//////////////////////////////////////////////////////////////////////////// // SQL Database MMF Extension // (c) 2004-2005, Jim St. Jean // // MAIN OBJECT EDIT ROUTINES - Source file // // //////////////////////////////////////////////////////////////////////////// // // Originally generated using FireMonkeySDK // // ============================================================================ // // This file contains routines that are handled during the Edittime. // // Including creating, display, and setting up your object. // // ============================================================================ /* Info from Tigs' Extension Tutorial Part 1: This source file contains data and functions which are used at edit-time. Have a look through, there are lots of handy edit-time functions, such as functions which are called when your object is placed in the frame, etc. However, we want to look at CreateObject(), called when the user chooses to insert your object. The code here calls the setup dialog. */ #ifndef RUN_ONLY // Common #include "common.h" // This variable will remain global between all instances of the object. // JSJNOTE: Implements single shared global database today GlobalData Global={NULL}; // We will check its nullity later // JSJNOTE: Implements single shared global database today // Prototype of setup procedure BOOL CALLBACK DLLExport setupProc(HWND hDlg,uint msgType,WPARAM wParam,LPARAM lParam); // Structure defined to pass edptr and mv into setup box typedef struct tagSetP { EDITDATA _far * edpt; mv _far * kv; } setupParams; // ----------------- // BmpToImg // ----------------- // Converts an image from the resource to an image displayable under CC&C // Not used in this template, but it is a good example on how to create // an image. /* JSJ REMOVED _inline WORD BmpToImg(int bmID, npAppli idApp, short HotX = 0, short HotY = 0, short ActionX = 0, short ActionY = 0) { Img ifo; WORD img; HRSRC hs; HGLOBAL hgBuf; LPBYTE adBuf; LPBITMAPINFOHEADER adBmi; img = 0; if ((hs = FindResource(hInstLib, MAKEINTRESOURCE(bmID), RT_BITMAP)) != NULL) { if ((hgBuf = LoadResource(hInstLib, hs)) != NULL) { if ((adBuf = (LPBYTE)LockResource(hgBuf)) != NULL) { adBmi = (LPBITMAPINFOHEADER)adBuf; ifo.imgXSpot = HotX; ifo.imgYSpot = HotY; ifo.imgXAction = ActionX; ifo.imgYAction = ActionY; if (adBmi->biBitCount > 4) RemapDib((LPBITMAPINFO)adBmi, idApp, NULL); img = DibToImage(idApp, &ifo, adBmi); UnlockResource(hgBuf); } FreeResource(hgBuf); } } return img; } JSJ REMOVED */ // ----------------- // Initialize // ----------------- // Where you want to do COLD-START initialization. Only called ONCE per application. // extern "C" int WINAPI DLLExport Initialize(mv _far *knpV, int quiet) { // Called when the application starts or restarts // Global.db = NULL; // No errors return 0; } // ----------------- // Free // ----------------- // Where you want to kill any initialized data opened in the above routine // Called ONCE per application, just before freeing the DLL. // extern "C" int WINAPI DLLExport Free(mv _far *knpV) { // if (Global.db) // sqldb_close(Global.db); /* close any global SQLDB db handle */ // No errors return 0; } // -------------------- // UpdateEditStructure // -------------------- // For you to update your object structure to newer versions // HGLOBAL WINAPI DLLExport UpdateEditStructure(mv __far *knpV, void __far * OldEdPtr) { // We do nothing here return 0; } // ----------------- // LoadObject // ----------------- // Routine called for each object, when the object is dropped in the frame. // You can load data here, reserve memory etc... // Called once per different object, just after loading extension data int WINAPI DLLExport LoadObject(mv _far *knpV, LPCSTR fileName, LPEDATA edPtr, int reserved) { return 0; } // ----------------- // UnloadObject // ----------------- // The counterpart of the above routine: called just before the object is // deleted from the frame void WINAPI DLLExport UnloadObject(mv _far *knpV, LPEDATA edPtr, int reserved) { } // -------------------- // UpdateFileNames // -------------------- // If you store file names in your datazone, they have to be relocated when the // application is moved: this routine does it. // void WINAPI DLLExport UpdateFileNames(mv _far *knpV, LPSTR gameName, LPEDATA edPtr, void (WINAPI * lpfnUpdate)(LPSTR, LPSTR)) { } // -------------------- // PutObject // -------------------- // Called when each individual object is dropped in the frame. // void WINAPI DLLExport PutObject(mv _far *knpV, fpLevObj loPtr, LPEDATA edPtr, ushort cpt) { } // -------------------- // RemoveObject // -------------------- // Called when each individual object is removed in the frame. // void WINAPI DLLExport RemoveObject(mv _far *knpV, fpLevObj loPtr, LPEDATA edPtr, ushort cpt) { // Is the last object removed? if (0 == cpt) { // Do whatever necessary to remove our data } } // -------------------- // MakeIcon // -------------------- // Called once object is created or modified, just after setup. // int WINAPI DLLExport MakeIcon ( mv _far *knpV, BITMAPINFO FAR *lpBitmap, LPSTR lpName, fpObjInfo oiPtr, LPEDATA edPtr ) { int error = -1; ushort pSize, bSize; HRSRC hs; HGLOBAL hgBuf; LPBYTE adBuf; LPBITMAPINFOHEADER adBmi; // Here, we simply load the icon from the resource and convert it into a format understood by CC&C. // You could also generate the icon yourself from what the user has entered in the setup. if ((hs = FindResource(hInstLib, MAKEINTRESOURCE(EXO_ICON), RT_BITMAP)) != NULL) { if ((hgBuf = LoadResource(hInstLib, hs)) != NULL) { if ((adBuf = (LPBYTE)LockResource(hgBuf)) != NULL) { adBmi = (LPBITMAPINFOHEADER)adBuf; pSize = (adBmi->biBitCount > 8) ? 0 : (4 << (BYTE) adBmi->biBitCount); bSize = (((WORD)adBmi->biWidth * adBmi->biBitCount + 31) &~ 31) / 8 * (WORD)adBmi->biHeight; _fmemcpy(lpBitmap, adBuf, sizeof(BITMAPINFOHEADER) + pSize + bSize); error = FALSE; UnlockResource (hgBuf); } FreeResource(hgBuf); } } return error; } // -------------------- // AppendPopup // -------------------- // Called just before opening the popup menu of the object under the editor. // You can remove or add options to the default menu... void WINAPI DLLExport AppendPopup(mv _far *knpV, HMENU hPopup, fpLevObj loPtr, LPEDATA edPtr, int nbSel) { } // -------------------- // CreateObject // -------------------- // Called when you choose "Create new object". It should display the setup box // and initialize everything in the datazone. int WINAPI DLLExport CreateObject(mv _far *knpV, fpLevObj loPtr, LPEDATA edPtr) { // Check compatibility if ( !IS_COMPATIBLE(knpV) ) return -1; setupParams spa; // Set default object flags edPtr->sx = 0; edPtr->sy = 0; edPtr->swidth = 32; edPtr->sheight = 32; // Call setup (remove this and return 0 if your object does not need a setup) spa.edpt = edPtr; spa.kv = knpV; return ((int) DialOpen(hInstLib, MAKEINTRESOURCE(DB_SETUP), knpV->mvHEditWin, setupProc, 0, 0, DL_MODAL|DL_CENTER_WINDOW, (LPARAM)(LPBYTE)&spa)); } // -------------------- // SelectPopup // -------------------- // One of the option from the menu has been selected, and not a default menu option // automatically handled by CC&C: this routine is then called. // int WINAPI DLLExport SelectPopup(mv _far *knpV, int modif, fpObjInfo oiPtr, fpLevObj loPtr, LPEDATA edPtr, fpushort lpParams, int maxParams) { // Check compatibility if ( !IS_COMPATIBLE(knpV) ) return 0; setupParams spa; // Remove this if your object does not need a setup if (modif == ID_POP_SETUP) { spa.edpt = edPtr; spa.kv = knpV; if (0 == DialOpen(hInstLib, MAKEINTRESOURCE(DB_SETUP), knpV->mvHEditWin, setupProc, 0, 0, DL_MODAL | DL_CENTER_WINDOW, (LPARAM)(LPBYTE)&spa)) return MODIF_HFRAN; } /* if your object can be resized, remove the remark! if (MODIF_SIZE == modif) { edPtr->swidth = lpParams[2]; edPtr->sheight = lpParams[3]; } */ return 0; } // -------------------- // SetupProc // -------------------- // This routine is yours. You may even not need a setup dialog box. // I have put it as an example... BOOL CALLBACK DLLExport setupProc(HWND hDlg,uint msgType,WPARAM wParam,LPARAM lParam) { setupParams _far * spa; EDITDATA _far * edPtr; switch (msgType) { case WM_INITDIALOG: // Init dialog SetWindowLong(hDlg, DWL_USER, lParam); spa = (setupParams far *)lParam; edPtr = spa->edpt; /* Insert your code to initalise the dialog! Try the following code snippets: ** Change an editbox's text: SetDlgItemText(hDlg, IDC_YOUR_EDITBOX_ID, edPtr->YourTextVariable); ** (Un)check a checkbox: CheckDlgButton(hDlg, IDC_YOUR_CHECKBOX_ID, edPtr->YourBooleanValue ? BST_CHECKED : BST_UNCHECKED); ** If the variable is not of type 'bool' then include a comparison ** before the question mark (conditional operator): CheckDlgButton(hDlg, IDC_YOUR_CHECKBOX_ID, edPtr->YourLongValue == 1 ? BST_CHECKED : BST_UNCHECKED); ** Check a radio button, deselecting the others at the same time CheckRadioButton(hDlg, IDC_FIRST_RADIO_IN_GROUP, IDC_LAST_RADIO_IN_GROUP, IDC_RADIO_TO_CHECK); ** You should know how to add radio buttons properly in MSVC++'s dialog editor first... ** Make sure to add radiobuttons in order, and use the 'Group' property to signal a new group ** of radio buttons. ** Disable a control. Replace 'FALSE' with 'TRUE' to enable the control: EnableWindow(GetDlgItem(hDlg, IDC_YOUR_CONTROL_ID), FALSE); */ return TRUE; case WM_COMMAND: // Command spa = (setupParams far *)GetWindowLong(hDlg, DWL_USER); edPtr = spa->edpt; switch (wmCommandID) { case IDOK: /* The user has pressed OK! Save our data with the following commands: ** Get text from an editbox. There is a limit to how much you can retrieve, ** make sure this limit is reasonable and your variable can hold this data. ** (Replace 'MAXIMUM_TEXT_LENGTH' with a value or defined constant!) GetDlgItemText(hDlg, IDC_YOUR_EDITBOX_ID, edPtr->YourTextVariable, MAXIMUM_TEXT_LENGTH); ** Check if a checkbox or radiobutton is checked. This is the basic code: (IsDlgButtonChecked(hDlg, IDC_YOUR_CHECKBOX_ID)==BST_CHECKED) ** This will return true if checked, false if not. ** If your variable is a bool, set it to this code ** If not, use an if statement or the conditional operator if (IsDlgButtonChecked(hDlg, IDC_YOUR_CHECKBOX_ID)==BST_CHECKED) edPtr->YourLongValue = 100; else edPtr->YourLongValue = 50; */ // Close the dialog EndDialog(hDlg, 0); return 0; case IDCANCEL: // User pressed cancel, don't save anything // Close the dialog EndDialog(hDlg, -1); return 0; case ID_HELP: { /* This code will run if the Help button is clicked. If you have just a text file, try this: (Paths relative to MMFusion.exe, don't forget to escape the backslashes!) ShellExecute(NULL, "open", "notepad", "Docs\\My Extension\\ThisIsMyDocumentation.txt", NULL, SW_MAXIMIZE); If you have a document for which the program you use can be different (for example, an HTML document or .doc) then try this form: ShellExecute(NULL, "open", "Docs\\My Extension\\MyDocs.html", NULL, NULL, SW_MAXIMIZE); If you use the ShellExecute function you must include the library 'shell32.lib' in your Release_Small config. To do this, go to menu Project > Settings, choose 'Win32 Release_Small' on the upper-left, click the 'Link' tab on the right and enter "shell32.lib" (w/o quotes) at the end of the 'Object/library modules' editbox. Ensure there is a space between this and the rest of the line. If you don't do this, you will get 'unresolved external' errors because the compiler cannot find the function when it links the different .cpp files together. */ ShellExecute(NULL, "open", "Help\\SQLDB\\SQLDB.htm", NULL, NULL, SW_MAXIMIZE); /* This is useful if your extension is documented in the MMF help file... // (In other words, you'll never need it, but it was SDK's default action) NPSTR chTmp; if ((chTmp = (NPSTR)LocalAlloc(LPTR, _MAX_PATH)) != NULL) { GetModuleFileName(hInstLib, chTmp, _MAX_PATH); spa->kv->mvKncHelp(chTmp, HELP_CONTEXT, 1); LocalFree((HLOCAL)chTmp); } */ } return 0; /* If you have a button or checkbox which, when clicked, will change something on the dialog, add them like so: case IDC_YOUR_CLICKED_CONTROL: // your code here return 0; You can use any of the commands added previously, (including the Help code,) but it's a good idea NOT to save data to edPtr until the user presses OK. */ default: break; } break; default: break; } return FALSE; } // -------------------- // ModifyObject // -------------------- // Called by CC&C when the object has been modified // int WINAPI DLLExport ModifyObject(mv _far *knpV, LPEDATA edPtr, fpObjInfo oiPtr, fpLevObj loPtr, int modif, fpushort lpParams) { // Modification in size? if (MODIF_SIZE == modif) { edPtr->swidth = lpParams[2]; edPtr->sheight = lpParams[3]; } // No errors... return 0; } // -------------------- // RebuildExt // -------------------- // This routine rebuilds the new extension datazone from the old one, and the // modifications done in the setup dialog int WINAPI DLLExport RebuildExt(mv _far *knpV, LPEDATA edPtr, LPBYTE oldExtPtr, fpObjInfo oiPtr, fpLevObj loPtr, fpushort lpParams) { // No errors return 0; } // -------------------- // EndModifyObject // -------------------- // After all modifications are done, this routine is called. // You can free any memory allocated here. void WINAPI DLLExport EndModifyObject(mv _far *knpV, int modif, fpushort lpParams) { } // -------------------- // GetObjectRect // -------------------- // Returns the size of the rectangle of the object in the frame window // void WINAPI DLLExport GetObjectRect(mv _far *knpV, RECT FAR *rc, fpLevObj loPtr, LPEDATA edPtr) { //Print("GetObjectRect"); rc->right = rc->left + edPtr->swidth; rc->bottom = rc->top + edPtr->sheight; return; } // -------------------- // EditorDisplay // -------------------- // Displays the object under the frame editor // void WINAPI DLLExport EditorDisplay(mv _far *knpV, fpObjInfo oiPtr, fpLevObj loPtr, LPEDATA edPtr, RECT FAR *rc) { /* This is a simple case of drawing an image onto MMF's frame editor window First, we must get a pointer to the surface used by the frame editor */ LPSURFACE ps = WinGetSurface((int)knpV->mvIdEditWin); if ( ps != NULL ) // Do the following if this surface exists { int x = rc->left; // get our boundaries int y = rc->top; int w = rc->right-rc->left; int h = rc->bottom-rc->top; cSurface is; // New surface variable for us to use is.Create(4, 4, ps); // Create a surface implementation from a prototype (frame editor win) is.LoadImage(hInstLib, EXO_IMAGE, LI_REMAP); // Load our bitmap from the resource, // and remap palette if necessary is.Blit(*ps, x, y, BMODE_TRANSP, BOP_COPY, 0); // Blit the image to the frame editor surface! // This actually blits (or copies) the whole of our surface onto the frame editor's surface // at a specified position. // We could use different image effects when we copy, e.g. invert, AND, OR, XOR, // blend (semi-transparent, the 6th param is amount of transparency) // You can 'anti-alias' with the 7th param (default=0 or off) } } // -------------------- // IsTransparent // -------------------- // This routine tells CC&C if the mouse pointer is over a transparent zone of the object. // extern "C" { BOOL WINAPI DLLExport IsTransparent(mv _far *knpV, fpLevObj loPtr, LPEDATA edPtr, int dx, int dy) { return FALSE; } } // -------------------- // PrepareToWriteObject // -------------------- // Just before writing the datazone when saving the application, CC&C calls this routine. // void WINAPI DLLExport PrepareToWriteObject(mv _far *knpV, LPEDATA edPtr, fpObjInfo adoi) { } // -------------------- // UsesFile // -------------------- // Triggers when a file is dropped onto the frame BOOL WINAPI DLLExport UsesFile (LPMV mV, LPSTR fileName) { // Return TRUE if you can create an object from the given file return FALSE; // Example: return TRUE if file extension is ".txt" /* BOOL r = FALSE; NPSTR ext, npath; if ( fileName != NULL ) { if ( (ext=(NPSTR)LocalAlloc(LPTR, _MAX_EXT)) != NULL ) { if ( (npath=(NPSTR)LocalAlloc(LPTR, _MAX_PATH)) != NULL ) { _fstrcpy(npath, fileName); _splitpath(npath, NULL, NULL, NULL, ext); if ( _stricmp(ext, ".txt") == 0 ) r = TRUE; LocalFree((HLOCAL)npath); } LocalFree((HLOCAL)ext); } } return r; */ } // -------------------- // CreateFromFile // -------------------- // Creates a new object from file void WINAPI DLLExport CreateFromFile (LPMV mV, LPSTR fileName, LPEDATA edPtr) { // Initialize your extension data from the given file edPtr->swidth = 32; edPtr->sheight = 32; // Example: store the filename // _fstrcpy(edPtr->myFileName, fileName); } // --------------------- // EnumElts // --------------------- int WINAPI DLLExport EnumElts (mv __far *knpV, LPEDATA edPtr, ENUMELTPROC enumProc, ENUMELTPROC undoProc, LPARAM lp1, LPARAM lp2) { int error = 0; /* //Uncomment this if you need to store an image in the image bank. //Replace imgidx with the variable you create within the edit structure // Enum images if ( (error = enumProc(&edPtr->imgidx, IMG_TAB, lp1, lp2)) != 0 ) { // Undo enum images undoProc (&edPtr->imgidx, IMG_TAB, lp1, lp2); } */ return error; } #endif //Not RUN_ONLY
17,941
6,638
#include <chrono> #include "envoy/common/scope_tracker.h" #include "envoy/event/timer.h" #include "common/event/dispatcher_impl.h" #include "common/event/scaled_range_timer_manager_impl.h" #include "test/mocks/common.h" #include "test/mocks/event/wrapped_dispatcher.h" #include "test/test_common/simulated_time_system.h" #include "gtest/gtest.h" namespace Envoy { namespace Event { namespace { using testing::ElementsAre; using testing::InSequence; using testing::MockFunction; class ScopeTrackingDispatcher : public WrappedDispatcher { public: ScopeTrackingDispatcher(DispatcherPtr dispatcher) : WrappedDispatcher(*dispatcher), dispatcher_(std::move(dispatcher)) {} void pushTrackedObject(const ScopeTrackedObject* object) override { scope_ = object; return impl_.pushTrackedObject(object); } void popTrackedObject(const ScopeTrackedObject* expected_object) override { scope_ = nullptr; return impl_.popTrackedObject(expected_object); } const ScopeTrackedObject* scope_{nullptr}; Dispatcher* impl() const { return dispatcher_.get(); } private: DispatcherPtr dispatcher_; }; class ScaledRangeTimerManagerTest : public testing::Test, public TestUsingSimulatedTime { public: ScaledRangeTimerManagerTest() : api_(Api::createApiForTest()), dispatcher_(api_->allocateDispatcher("test_thread")) {} Api::ApiPtr api_; ScopeTrackingDispatcher dispatcher_; }; struct TrackedRangeTimer { explicit TrackedRangeTimer(ScaledTimerMinimum minimum, ScaledRangeTimerManagerImpl& manager, TimeSystem& time_system) : timer(manager.createTimer(minimum, [trigger_times = trigger_times.get(), &time_system] { trigger_times->push_back(time_system.monotonicTime()); })) {} std::unique_ptr<std::vector<MonotonicTime>> trigger_times{ std::make_unique<std::vector<MonotonicTime>>()}; TimerPtr timer; }; TEST_F(ScaledRangeTimerManagerTest, CreateAndDestroy) { ScaledRangeTimerManagerImpl manager(dispatcher_); } TEST_F(ScaledRangeTimerManagerTest, CreateAndDestroyTimer) { ScaledRangeTimerManagerImpl manager(dispatcher_); { MockFunction<TimerCb> callback; auto timer = manager.createTimer(ScaledMinimum(UnitFloat(1.0)), callback.AsStdFunction()); } } TEST_F(ScaledRangeTimerManagerTest, CreateSingleScaledTimer) { ScaledRangeTimerManagerImpl manager(dispatcher_); MockFunction<TimerCb> callback; auto timer = manager.createTimer(ScaledMinimum(UnitFloat(0.5)), callback.AsStdFunction()); timer->enableTimer(std::chrono::seconds(10)); EXPECT_TRUE(timer->enabled()); simTime().advanceTimeAndRun(std::chrono::seconds(5), dispatcher_, Dispatcher::RunType::Block); EXPECT_TRUE(timer->enabled()); EXPECT_CALL(callback, Call()); simTime().advanceTimeAndRun(std::chrono::seconds(5), dispatcher_, Dispatcher::RunType::Block); EXPECT_FALSE(timer->enabled()); } TEST_F(ScaledRangeTimerManagerTest, EnableAndDisableTimer) { ScaledRangeTimerManagerImpl manager(dispatcher_); MockFunction<TimerCb> callback; auto timer = manager.createTimer(AbsoluteMinimum(std::chrono::seconds(5)), callback.AsStdFunction()); timer->enableTimer(std::chrono::seconds(30)); EXPECT_TRUE(timer->enabled()); timer->disableTimer(); EXPECT_FALSE(timer->enabled()); // Provide some additional guarantee of safety by running the dispatcher for a little bit. This // should be a no-op, and if not (because a timer was fired), that's a problem that will be caught // by the strict mock callback. simTime().advanceTimeAndRun(std::chrono::seconds(10), dispatcher_, Dispatcher::RunType::Block); } TEST_F(ScaledRangeTimerManagerTest, DisableWhileDisabled) { ScaledRangeTimerManagerImpl manager(dispatcher_); MockFunction<TimerCb> callback; auto timer = manager.createTimer(ScaledMinimum(UnitFloat(1.0)), callback.AsStdFunction()); EXPECT_FALSE(timer->enabled()); timer->disableTimer(); EXPECT_FALSE(timer->enabled()); } TEST_F(ScaledRangeTimerManagerTest, DisableWhileWaitingForMin) { ScaledRangeTimerManagerImpl manager(dispatcher_); MockFunction<TimerCb> callback; auto timer = manager.createTimer(AbsoluteMinimum(std::chrono::seconds(10)), callback.AsStdFunction()); timer->enableTimer(std::chrono::seconds(100)); EXPECT_TRUE(timer->enabled()); timer->disableTimer(); EXPECT_FALSE(timer->enabled()); } TEST_F(ScaledRangeTimerManagerTest, DisableWhileScalingMax) { ScaledRangeTimerManagerImpl manager(dispatcher_); MockFunction<TimerCb> callback; auto timer = manager.createTimer(AbsoluteMinimum(std::chrono::seconds(5)), callback.AsStdFunction()); timer->enableTimer(std::chrono::seconds(100)); simTime().advanceTimeAndRun(std::chrono::seconds(5), dispatcher_, Dispatcher::RunType::Block); EXPECT_TRUE(timer->enabled()); timer->disableTimer(); EXPECT_FALSE(timer->enabled()); // Run the dispatcher to make sure nothing happens when it's not supposed to. simTime().advanceTimeAndRun(std::chrono::seconds(100), dispatcher_, Dispatcher::RunType::Block); } TEST_F(ScaledRangeTimerManagerTest, InCallbackDisableLastTimerInSameQueue) { ScaledRangeTimerManagerImpl manager(dispatcher_); MockFunction<TimerCb> callback1; auto timer1 = manager.createTimer(AbsoluteMinimum(std::chrono::seconds(0)), callback1.AsStdFunction()); MockFunction<TimerCb> callback2; auto timer2 = manager.createTimer(AbsoluteMinimum(std::chrono::seconds(5)), callback2.AsStdFunction()); timer1->enableTimer(std::chrono::seconds(95)); timer2->enableTimer(std::chrono::seconds(100)); simTime().advanceTimeAndRun(std::chrono::seconds(5), dispatcher_, Dispatcher::RunType::Block); EXPECT_TRUE(timer1->enabled()); EXPECT_TRUE(timer2->enabled()); EXPECT_CALL(callback1, Call).WillOnce(Invoke([&]() { timer2->disableTimer(); timer2.reset(); })); // Run the dispatcher to make sure nothing happens when it's not supposed to. simTime().advanceTimeAndRun(std::chrono::seconds(100), dispatcher_, Dispatcher::RunType::Block); } TEST_F(ScaledRangeTimerManagerTest, InCallbackDisableTimerInOtherQueue) { ScaledRangeTimerManagerImpl manager(dispatcher_); MockFunction<TimerCb> callback1; auto timer1 = manager.createTimer(AbsoluteMinimum(std::chrono::seconds(5)), callback1.AsStdFunction()); MockFunction<TimerCb> callback2; auto timer2 = manager.createTimer(AbsoluteMinimum(std::chrono::seconds(5)), callback2.AsStdFunction()); timer1->enableTimer(std::chrono::seconds(95)); timer2->enableTimer(std::chrono::seconds(100)); simTime().advanceTimeAndRun(std::chrono::seconds(5), dispatcher_, Dispatcher::RunType::Block); EXPECT_TRUE(timer1->enabled()); EXPECT_TRUE(timer2->enabled()); EXPECT_CALL(callback1, Call).WillOnce(Invoke([&]() { timer2->disableTimer(); timer2.reset(); })); // Run the dispatcher to make sure nothing happens when it's not supposed to. simTime().advanceTimeAndRun(std::chrono::seconds(100), dispatcher_, Dispatcher::RunType::Block); } TEST_F(ScaledRangeTimerManagerTest, DisableWithZeroMinTime) { ScaledRangeTimerManagerImpl manager(dispatcher_); MockFunction<TimerCb> callback; auto timer = manager.createTimer(ScaledMinimum(UnitFloat(0.0)), callback.AsStdFunction()); timer->enableTimer(std::chrono::seconds(100)); EXPECT_TRUE(timer->enabled()); timer->disableTimer(); EXPECT_FALSE(timer->enabled()); // Run the dispatcher to make sure nothing happens when it's not supposed to. simTime().advanceTimeAndRun(std::chrono::seconds(100), dispatcher_, Dispatcher::RunType::Block); } TEST_F(ScaledRangeTimerManagerTest, TriggerWithZeroMinTime) { ScaledRangeTimerManagerImpl manager(dispatcher_); MockFunction<TimerCb> callback; auto timer = manager.createTimer(AbsoluteMinimum(std::chrono::seconds(0)), callback.AsStdFunction()); timer->enableTimer(std::chrono::seconds(10)); simTime().advanceTimeAndRun(std::chrono::seconds(9), dispatcher_, Dispatcher::RunType::Block); EXPECT_CALL(callback, Call); simTime().advanceTimeAndRun(std::chrono::seconds(1), dispatcher_, Dispatcher::RunType::Block); } TEST_F(ScaledRangeTimerManagerTest, DisableFrontScalingMaxTimer) { ScaledRangeTimerManagerImpl manager(dispatcher_); MockFunction<TimerCb> callback1, callback2; auto timer1 = manager.createTimer(AbsoluteMinimum(std::chrono::seconds(5)), callback1.AsStdFunction()); auto timer2 = manager.createTimer(AbsoluteMinimum(std::chrono::seconds(10)), callback2.AsStdFunction()); // These timers have the same max-min. timer1->enableTimer(std::chrono::seconds(30)); timer2->enableTimer(std::chrono::seconds(35)); simTime().advanceTimeAndRun(std::chrono::seconds(5), dispatcher_, Dispatcher::RunType::Block); simTime().advanceTimeAndRun(std::chrono::seconds(5), dispatcher_, Dispatcher::RunType::Block); timer1->disableTimer(); EXPECT_FALSE(timer1->enabled()); ASSERT_TRUE(timer2->enabled()); // Check that timer2 doesn't trigger when timer1 was originally going to, at start+30. simTime().advanceTimeAndRun(std::chrono::seconds(20), dispatcher_, Dispatcher::RunType::Block); // Advancing to timer2's max should trigger it. EXPECT_CALL(callback2, Call); simTime().advanceTimeAndRun(std::chrono::seconds(5), dispatcher_, Dispatcher::RunType::Block); } TEST_F(ScaledRangeTimerManagerTest, DisableLaterScalingMaxTimer) { ScaledRangeTimerManagerImpl manager(dispatcher_); MockFunction<TimerCb> callback1, callback2; auto timer1 = manager.createTimer(AbsoluteMinimum(std::chrono::seconds(5)), callback1.AsStdFunction()); auto timer2 = manager.createTimer(AbsoluteMinimum(std::chrono::seconds(10)), callback2.AsStdFunction()); // These timers have the same max-min. timer1->enableTimer(std::chrono::seconds(30)); timer2->enableTimer(std::chrono::seconds(35)); simTime().advanceTimeAndRun(std::chrono::seconds(5), dispatcher_, Dispatcher::RunType::Block); simTime().advanceTimeAndRun(std::chrono::seconds(5), dispatcher_, Dispatcher::RunType::Block); timer2->disableTimer(); EXPECT_FALSE(timer2->enabled()); ASSERT_TRUE(timer1->enabled()); // After the original windows for both timers have long expired, only the enabled one should fire. EXPECT_CALL(callback1, Call); simTime().advanceTimeAndRun(std::chrono::seconds(100), dispatcher_, Dispatcher::RunType::Block); } class ScaledRangeTimerManagerTestWithScope : public ScaledRangeTimerManagerTest, public testing::WithParamInterface<bool> { public: ScopeTrackedObject* getScope() { return GetParam() ? &scope_ : nullptr; } MockScopedTrackedObject scope_; }; TEST_P(ScaledRangeTimerManagerTestWithScope, ReRegisterOnCallback) { ScaledRangeTimerManagerImpl manager(dispatcher_); MockFunction<TimerCb> callback; auto timer = manager.createTimer(AbsoluteMinimum(std::chrono::seconds(1)), callback.AsStdFunction()); EXPECT_EQ(dispatcher_.scope_, nullptr); { InSequence s; EXPECT_CALL(callback, Call).WillOnce([&] { EXPECT_EQ(dispatcher_.scope_, getScope()); timer->enableTimer(std::chrono::seconds(2), getScope()); }); EXPECT_CALL(callback, Call).WillOnce([&] { EXPECT_EQ(dispatcher_.scope_, getScope()); }); } timer->enableTimer(std::chrono::seconds(2), getScope()); simTime().advanceTimeAndRun(std::chrono::seconds(1), dispatcher_, Dispatcher::RunType::Block); EXPECT_EQ(dispatcher_.scope_, nullptr); simTime().advanceTimeAndRun(std::chrono::seconds(1), dispatcher_, Dispatcher::RunType::Block); EXPECT_EQ(dispatcher_.scope_, nullptr); EXPECT_TRUE(timer->enabled()); simTime().advanceTimeAndRun(std::chrono::seconds(1), dispatcher_, Dispatcher::RunType::Block); simTime().advanceTimeAndRun(std::chrono::seconds(1), dispatcher_, Dispatcher::RunType::Block); EXPECT_FALSE(timer->enabled()); }; TEST_P(ScaledRangeTimerManagerTestWithScope, ScheduleWithScalingFactorZero) { ScaledRangeTimerManagerImpl manager(dispatcher_); MockFunction<TimerCb> callback; auto timer = manager.createTimer(AbsoluteMinimum(std::chrono::seconds(0)), callback.AsStdFunction()); manager.setScaleFactor(0); EXPECT_CALL(callback, Call).WillOnce([&] { EXPECT_EQ(dispatcher_.scope_, getScope()); }); timer->enableTimer(std::chrono::seconds(1), getScope()); simTime().advanceTimeAndRun(std::chrono::milliseconds(1), dispatcher_, Dispatcher::RunType::Block); } INSTANTIATE_TEST_SUITE_P(WithAndWithoutScope, ScaledRangeTimerManagerTestWithScope, testing::Bool()); TEST_F(ScaledRangeTimerManagerTest, SingleTimerTriggeredNoScaling) { ScaledRangeTimerManagerImpl manager(dispatcher_); bool triggered = false; MockFunction<TimerCb> callback; auto timer = manager.createTimer(AbsoluteMinimum(std::chrono::seconds(5)), callback.AsStdFunction()); EXPECT_CALL(callback, Call()).WillOnce([&] { triggered = true; }); timer->enableTimer(std::chrono::seconds(9)); simTime().advanceTimeAndRun(std::chrono::seconds(5), dispatcher_, Dispatcher::RunType::Block); EXPECT_FALSE(triggered); simTime().advanceTimeAndRun(std::chrono::seconds(4) - std::chrono::milliseconds(1), dispatcher_, Dispatcher::RunType::Block); EXPECT_FALSE(triggered); simTime().advanceTimeAndRun(std::chrono::milliseconds(1), dispatcher_, Dispatcher::RunType::Block); EXPECT_TRUE(triggered); } TEST_F(ScaledRangeTimerManagerTest, SingleTimerSameMinMax) { ScaledRangeTimerManagerImpl manager(dispatcher_); MockFunction<TimerCb> callback; auto timer = manager.createTimer(ScaledMinimum(UnitFloat(1.0)), callback.AsStdFunction()); EXPECT_CALL(callback, Call()); timer->enableTimer(std::chrono::seconds(1)); simTime().advanceTimeAndRun(std::chrono::seconds(1), dispatcher_, Dispatcher::RunType::Block); EXPECT_FALSE(timer->enabled()); } TEST_F(ScaledRangeTimerManagerTest, ScaledMinimumFactorGreaterThan1) { ScaledRangeTimerManagerImpl manager(dispatcher_); // If the minimum scale factor is > 1, it should be treated as if it was 1. MockFunction<TimerCb> callback; auto timer = manager.createTimer(ScaledMinimum(UnitFloat(2)), callback.AsStdFunction()); timer->enableTimer(std::chrono::seconds(10)); EXPECT_CALL(callback, Call); simTime().advanceTimeAndRun(std::chrono::seconds(10), dispatcher_, Dispatcher::RunType::Block); EXPECT_FALSE(timer->enabled()); } TEST_F(ScaledRangeTimerManagerTest, AbsoluteMinimumGreaterThanMax) { ScaledRangeTimerManagerImpl manager(dispatcher_); // If the minimum is greater than the maximum, it should be treated as if it was the same as the // max. MockFunction<TimerCb> callback; auto timer = manager.createTimer(AbsoluteMinimum(std::chrono::seconds(20)), callback.AsStdFunction()); timer->enableTimer(std::chrono::seconds(10)); EXPECT_CALL(callback, Call); simTime().advanceTimeAndRun(std::chrono::seconds(10), dispatcher_, Dispatcher::RunType::Block); EXPECT_FALSE(timer->enabled()); } TEST_F(ScaledRangeTimerManagerTest, MultipleTimersNoScaling) { ScaledRangeTimerManagerImpl manager(dispatcher_); std::vector<TrackedRangeTimer> timers; timers.reserve(3); const MonotonicTime start = simTime().monotonicTime(); timers.emplace_back(AbsoluteMinimum(std::chrono::seconds(1)), manager, simTime()); timers.emplace_back(AbsoluteMinimum(std::chrono::seconds(2)), manager, simTime()); timers.emplace_back(AbsoluteMinimum(std::chrono::seconds(0)), manager, simTime()); timers[0].timer->enableTimer(std::chrono::seconds(3)); timers[1].timer->enableTimer(std::chrono::seconds(6)); timers[2].timer->enableTimer(std::chrono::seconds(9)); for (int i = 0; i < 10; ++i) { simTime().advanceTimeAndRun(std::chrono::seconds(1), dispatcher_, Dispatcher::RunType::Block); } EXPECT_THAT(*timers[0].trigger_times, ElementsAre(start + std::chrono::seconds(3))); EXPECT_THAT(*timers[1].trigger_times, ElementsAre(start + std::chrono::seconds(6))); EXPECT_THAT(*timers[2].trigger_times, ElementsAre(start + std::chrono::seconds(9))); } TEST_F(ScaledRangeTimerManagerTest, MultipleTimersWithScaling) { ScaledRangeTimerManagerImpl manager(dispatcher_); std::vector<TrackedRangeTimer> timers; timers.reserve(3); timers.emplace_back(AbsoluteMinimum(std::chrono::seconds(1)), manager, simTime()); timers.emplace_back(AbsoluteMinimum(std::chrono::seconds(2)), manager, simTime()); timers.emplace_back(AbsoluteMinimum(std::chrono::seconds(6)), manager, simTime()); const MonotonicTime start = simTime().monotonicTime(); timers[0].timer->enableTimer(std::chrono::seconds(3)); timers[1].timer->enableTimer(std::chrono::seconds(6)); timers[2].timer->enableTimer(std::chrono::seconds(10)); manager.setScaleFactor(0.5); // Advance time to start = 1 second, so timers[0] hits its min. simTime().advanceTimeAndRun(std::chrono::seconds(1), dispatcher_, Dispatcher::RunType::Block); // Advance time to start = 2, which should make timers[0] hit its scaled max. simTime().advanceTimeAndRun(std::chrono::seconds(1), dispatcher_, Dispatcher::RunType::Block); // At 4x speed, timers[1] will fire in only 1 second. manager.setScaleFactor(0.25); // Advance time to start = 3, which should make timers[1] hit its scaled max. simTime().advanceTimeAndRun(std::chrono::seconds(1), dispatcher_, Dispatcher::RunType::Block); // Advance time to start = 6, which is the minimum required for timers[2] to fire. simTime().advanceTimeAndRun(std::chrono::seconds(3), dispatcher_, Dispatcher::RunType::Block); manager.setScaleFactor(0); // With a scale factor of 0, timers[2] should be ready to be fired immediately. dispatcher_.run(Dispatcher::RunType::Block); EXPECT_THAT(*timers[0].trigger_times, ElementsAre(start + std::chrono::seconds(2))); EXPECT_THAT(*timers[1].trigger_times, ElementsAre(start + std::chrono::seconds(3))); EXPECT_THAT(*timers[2].trigger_times, ElementsAre(start + std::chrono::seconds(6))); } TEST_F(ScaledRangeTimerManagerTest, MultipleTimersSameTimes) { ScaledRangeTimerManagerImpl manager(dispatcher_); std::vector<TrackedRangeTimer> timers; timers.reserve(3); const MonotonicTime start = simTime().monotonicTime(); for (int i = 0; i < 3; ++i) { timers.emplace_back(AbsoluteMinimum(std::chrono::seconds(1)), manager, simTime()); timers[i].timer->enableTimer(std::chrono::seconds(2)); } simTime().advanceTimeAndRun(std::chrono::seconds(1), dispatcher_, Dispatcher::RunType::Block); simTime().advanceTimeAndRun(std::chrono::seconds(1), dispatcher_, Dispatcher::RunType::Block); EXPECT_THAT(*timers[0].trigger_times, ElementsAre(start + std::chrono::seconds(2))); EXPECT_THAT(*timers[1].trigger_times, ElementsAre(start + std::chrono::seconds(2))); EXPECT_THAT(*timers[2].trigger_times, ElementsAre(start + std::chrono::seconds(2))); } TEST_F(ScaledRangeTimerManagerTest, MultipleTimersSameTimesFastClock) { ScaledRangeTimerManagerImpl manager(dispatcher_); std::vector<TrackedRangeTimer> timers; timers.reserve(3); const MonotonicTime start = simTime().monotonicTime(); for (int i = 0; i < 3; ++i) { timers.emplace_back(AbsoluteMinimum(std::chrono::seconds(1)), manager, simTime()); timers[i].timer->enableTimer(std::chrono::seconds(2)); } simTime().advanceTimeAndRun(std::chrono::seconds(1), dispatcher_, Dispatcher::RunType::Block); // The clock runs fast here before the dispatcher gets to the timer callbacks. simTime().advanceTimeAndRun(std::chrono::seconds(2), dispatcher_, Dispatcher::RunType::Block); EXPECT_THAT(*timers[0].trigger_times, ElementsAre(start + std::chrono::seconds(3))); EXPECT_THAT(*timers[1].trigger_times, ElementsAre(start + std::chrono::seconds(3))); EXPECT_THAT(*timers[2].trigger_times, ElementsAre(start + std::chrono::seconds(3))); } TEST_F(ScaledRangeTimerManagerTest, ScheduledWithScalingFactorZero) { ScaledRangeTimerManagerImpl manager(dispatcher_); manager.setScaleFactor(0); TrackedRangeTimer timer(AbsoluteMinimum(std::chrono::seconds(4)), manager, simTime()); // The timer should fire at start = 4 since the scaling factor is 0. const MonotonicTime start = simTime().monotonicTime(); timer.timer->enableTimer(std::chrono::seconds(10)); for (int i = 0; i < 10; ++i) { simTime().advanceTimeAndRun(std::chrono::seconds(4), dispatcher_, Dispatcher::RunType::Block); } EXPECT_THAT(*timer.trigger_times, ElementsAre(start + std::chrono::seconds(4))); } TEST_F(ScaledRangeTimerManagerTest, ScheduledWithMaxBeforeMin) { // When max < min, the timer behaves the same as if max == min. This ensures that min is always // respected, and max is respected as much as possible. ScaledRangeTimerManagerImpl manager(dispatcher_); TrackedRangeTimer timer(AbsoluteMinimum(std::chrono::seconds(4)), manager, simTime()); const MonotonicTime start = simTime().monotonicTime(); timer.timer->enableTimer(std::chrono::seconds(3)); for (int i = 0; i < 10; ++i) { simTime().advanceTimeAndRun(std::chrono::seconds(4), dispatcher_, Dispatcher::RunType::Block); } EXPECT_THAT(*timer.trigger_times, ElementsAre(start + std::chrono::seconds(4))); } TEST_F(ScaledRangeTimerManagerTest, MultipleTimersTriggeredInTheSameEventLoopIteration) { ScaledRangeTimerManagerImpl manager(dispatcher_); MockFunction<TimerCb> callback1, callback2, callback3; auto timer1 = manager.createTimer(AbsoluteMinimum(std::chrono::seconds(5)), callback1.AsStdFunction()); auto timer2 = manager.createTimer(AbsoluteMinimum(std::chrono::seconds(5)), callback2.AsStdFunction()); auto timer3 = manager.createTimer(AbsoluteMinimum(std::chrono::seconds(5)), callback3.AsStdFunction()); timer1->enableTimer(std::chrono::seconds(10)); timer2->enableTimer(std::chrono::seconds(10)); timer3->enableTimer(std::chrono::seconds(10)); simTime().advanceTimeAndRun(std::chrono::seconds(5), dispatcher_, Dispatcher::RunType::Block); DispatcherImpl* dispatcher_impl = static_cast<DispatcherImpl*>(dispatcher_.impl()); ASSERT(dispatcher_impl != nullptr); ReadyWatcher prepare_watcher; evwatch_prepare_new( &dispatcher_impl->base(), +[](evwatch*, const evwatch_prepare_cb_info*, void* arg) { // `arg` contains the ReadyWatcher passed in from evwatch_prepare_new. auto watcher = static_cast<ReadyWatcher*>(arg); watcher->ready(); }, &prepare_watcher); ReadyWatcher schedulable_watcher; SchedulableCallbackPtr schedulable_callback = dispatcher_.createSchedulableCallback([&] { schedulable_watcher.ready(); }); testing::Expectation first_prepare = EXPECT_CALL(prepare_watcher, ready()); testing::ExpectationSet after_first_prepare; after_first_prepare += EXPECT_CALL(schedulable_watcher, ready()).After(first_prepare).WillOnce([&] { schedulable_callback->scheduleCallbackNextIteration(); }); after_first_prepare += EXPECT_CALL(callback1, Call).After(first_prepare); after_first_prepare += EXPECT_CALL(callback2, Call).After(first_prepare); after_first_prepare += EXPECT_CALL(callback3, Call).After(first_prepare); testing::Expectation second_prepare = EXPECT_CALL(prepare_watcher, ready()).After(after_first_prepare).WillOnce([&] { schedulable_callback->scheduleCallbackNextIteration(); }); EXPECT_CALL(schedulable_watcher, ready()).After(second_prepare); // Running outside the event loop, this should schedule a run on the next event loop iteration. schedulable_callback->scheduleCallbackNextIteration(); simTime().advanceTimeAndRun(std::chrono::seconds(5), dispatcher_, Dispatcher::RunType::Block); dispatcher_.run(Dispatcher::RunType::Block); } TEST_F(ScaledRangeTimerManagerTest, MultipleTimersWithChangeInScalingFactor) { ScaledRangeTimerManagerImpl manager(dispatcher_); const MonotonicTime start = simTime().monotonicTime(); std::vector<TrackedRangeTimer> timers; timers.reserve(4); timers.emplace_back(AbsoluteMinimum(std::chrono::seconds(5)), manager, simTime()); timers.emplace_back(AbsoluteMinimum(std::chrono::seconds(12)), manager, simTime()); timers.emplace_back(AbsoluteMinimum(std::chrono::seconds(7)), manager, simTime()); timers.emplace_back(AbsoluteMinimum(std::chrono::seconds(10)), manager, simTime()); timers[0].timer->enableTimer(std::chrono::seconds(15)); timers[1].timer->enableTimer(std::chrono::seconds(14)); manager.setScaleFactor(0.1); timers[2].timer->enableTimer(std::chrono::seconds(21)); timers[3].timer->enableTimer(std::chrono::seconds(16)); // Advance to timer 0's min. simTime().advanceTimeAndRun(std::chrono::seconds(5), dispatcher_, Dispatcher::RunType::Block); manager.setScaleFactor(0.5); // Now that the scale factor is 0.5, fire times are 0: start+10, 1: start+13, 2: start+14, 3: // start+13. Advance to timer 2's min. simTime().advanceTimeAndRun(std::chrono::seconds(2), dispatcher_, Dispatcher::RunType::Block); // Advance to time start+9. simTime().advanceTimeAndRun(std::chrono::seconds(2), dispatcher_, Dispatcher::RunType::Block); manager.setScaleFactor(0.1); // Now that the scale factor is reduced, fire times are 0: start+6, 1: start+12.2, // 2: start+8.4, 3: start+10.6. Timers 0 and 2 should fire immediately since their // trigger times are in the past. dispatcher_.run(Dispatcher::RunType::Block); EXPECT_THAT(*timers[0].trigger_times, ElementsAre(start + std::chrono::seconds(9))); EXPECT_THAT(*timers[2].trigger_times, ElementsAre(start + std::chrono::seconds(9))); simTime().advanceTimeAndRun(std::chrono::seconds(1), dispatcher_, Dispatcher::RunType::Block); // The time is now start+10. Re-enable timer 0. ASSERT_FALSE(timers[0].timer->enabled()); timers[0].timer->enableTimer(std::chrono::seconds(13)); // Fire times are now 0: start+19, 1: start+13, 2: none, 3: start+13. manager.setScaleFactor(0.5); // Advance to timer 1's min. simTime().advanceTimeAndRun(std::chrono::seconds(2), dispatcher_, Dispatcher::RunType::Block); // Advance again to start+13, which should trigger both timers 1 and 3. simTime().advanceTimeAndRun(std::chrono::seconds(1), dispatcher_, Dispatcher::RunType::Block); EXPECT_THAT(*timers[1].trigger_times, ElementsAre(start + std::chrono::seconds(13))); EXPECT_THAT(*timers[3].trigger_times, ElementsAre(start + std::chrono::seconds(13))); simTime().advanceTimeAndRun(std::chrono::seconds(3), dispatcher_, Dispatcher::RunType::Block); // The time is now start+16. Setting the scale factor to 0 should make timer 0 fire immediately. manager.setScaleFactor(0); dispatcher_.run(Dispatcher::RunType::Block); EXPECT_THAT(*timers[0].trigger_times, ElementsAre(start + std::chrono::seconds(9), start + std::chrono::seconds(16))); } } // namespace } // namespace Event } // namespace Envoy
26,915
8,999
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include <pch.h> #include "winget/Yaml.h" #include "YamlWrapper.h" #include "AppInstallerErrors.h" #include "AppInstallerLogging.h" #include "AppInstallerStrings.h" namespace AppInstaller::YAML { using namespace std::string_view_literals; namespace { Node s_globalInvalidNode; std::string_view GetExceptionTypeStringView(Exception::Type type) { switch (type) { case Exception::Type::None: return "None"sv; case Exception::Type::Memory: return "Memory"sv; case Exception::Type::Reader: return "Reader"sv; case Exception::Type::Scanner: return "Scanner"sv; case Exception::Type::Parser: return "Parser"sv; case Exception::Type::Composer: return "Composer"sv; case Exception::Type::Writer: return "Writer"sv; case Exception::Type::Emitter: return "Emitter"sv; } return "Unknown"sv; } void OutputExceptionHeader(std::ostringstream& out, Exception::Type type) { out << "[YAML:" << GetExceptionTypeStringView(type) << "] "; } void OutputMark(std::ostringstream& out, const Mark& mark) { out << "[line " << mark.line << "; col " << mark.column << ']'; } } Exception::Exception(Type type) : wil::ResultException(APPINSTALLER_CLI_ERROR_LIBYAML_ERROR) { std::ostringstream out; OutputExceptionHeader(out, type); if (type == Type::Memory) { out << "Unable to (re)allocate memory"; } else { out << "An unknown error occurred"; } m_what = out.str(); } Exception::Exception(Type type, const char* problem, size_t offset, int value) : wil::ResultException(APPINSTALLER_CLI_ERROR_LIBYAML_ERROR) { std::ostringstream out; OutputExceptionHeader(out, type); out << (problem ? problem : "Unexplained error"); if (value != -1) { out << " [" << value << ']'; } out << " at " << offset; m_what = out.str(); } Exception::Exception(Type type, const char* problem, const Mark& problemMark, const char* context, const Mark& contextMark) : wil::ResultException(APPINSTALLER_CLI_ERROR_LIBYAML_ERROR) { std::ostringstream out; OutputExceptionHeader(out, type); if (context) { out << context << ' '; OutputMark(out, contextMark); out << ' ' << (problem ? problem : "unexplained error"); } else { out << (problem ? problem : "Unexplained error"); } out << ' '; OutputMark(out, problemMark); m_what = out.str(); } Exception::Exception(Type type, const char* problem) : wil::ResultException(APPINSTALLER_CLI_ERROR_LIBYAML_ERROR) { std::ostringstream out; OutputExceptionHeader(out, type); out << (problem ? problem : "Unexplained error"); m_what = out.str(); } const char* Exception::what() const noexcept { return m_what.c_str(); } Node::Node(Type type, std::string tag, const YAML::Mark& mark) : m_type(type), m_tag(std::move(tag)), m_mark(mark) { if (m_type == Type::Sequence) { m_sequence = decltype(m_sequence)::value_type{}; } else if (m_type == Type::Mapping) { m_mapping = decltype(m_mapping)::value_type{}; } } void Node::SetScalar(std::string value) { Require(Type::Scalar); m_scalar = std::move(value); } bool Node::operator<(const Node& other) const { Require(Type::Scalar); other.Require(Type::Scalar); return this->m_scalar < other.m_scalar; } Node& Node::operator[](std::string_view key) { Require(Type::Mapping); auto itrs = m_mapping->equal_range(key); if (itrs.first == itrs.second) { return s_globalInvalidNode; } Node& result = itrs.first->second; THROW_HR_IF(APPINSTALLER_CLI_ERROR_YAML_DUPLICATE_MAPPING_KEY, ++itrs.first != itrs.second); return result; } const Node& Node::operator[](std::string_view key) const { Require(Type::Mapping); auto itrs = m_mapping->equal_range(key); if (itrs.first == itrs.second) { return s_globalInvalidNode; } const Node& result = itrs.first->second; THROW_HR_IF(APPINSTALLER_CLI_ERROR_YAML_DUPLICATE_MAPPING_KEY, ++itrs.first != itrs.second); return result; } Node& Node::operator[](size_t index) { Require(Type::Sequence); return m_sequence.value()[index]; } const Node& Node::operator[](size_t index) const { Require(Type::Sequence); return m_sequence.value()[index]; } size_t Node::size() const { switch (m_type) { case Type::Invalid: case Type::None: case Type::Scalar: return 0; case Type::Sequence: return m_sequence->size(); case Type::Mapping: return m_mapping->size(); } THROW_HR(E_UNEXPECTED); } const std::vector<Node>& Node::Sequence() const { Require(Type::Sequence); return m_sequence.value(); } const std::multimap<Node, Node>& Node::Mapping() const { Require(Type::Mapping); return m_mapping.value(); } void Node::Require(Type type) const { THROW_HR_IF(APPINSTALLER_CLI_ERROR_YAML_INVALID_OPERATION, m_type != type); } std::string Node::as_dispatch(std::string*) const { return m_scalar; } int64_t Node::as_dispatch(int64_t*) const { return std::stoll(m_scalar); } int Node::as_dispatch(int*) const { // To allow HResult representation return static_cast<int>(std::stoll(m_scalar, 0, 0)); } bool Node::as_dispatch(bool*) const { if (Utility::CaseInsensitiveEquals(m_scalar, "true")) { return true; } else if (Utility::CaseInsensitiveEquals(m_scalar, "false")) { return false; } else { THROW_HR(APPINSTALLER_CLI_ERROR_YAML_INVALID_DATA); } } Node Load(std::string_view input) { Wrapper::Parser parser(input); Wrapper::Document document = parser.Load(); if (document.HasRoot()) { return document.GetRoot(); } else { return {}; } } Node Load(const std::string& input) { return Load(static_cast<std::string_view>(input)); } Node Load(std::istream& input, Utility::SHA256::HashBuffer* hashOut) { Wrapper::Parser parser(input, hashOut); Wrapper::Document document = parser.Load(); if (document.HasRoot()) { return document.GetRoot(); } else { return {}; } } Node Load(const std::filesystem::path& input, Utility::SHA256::HashBuffer* hashOut) { std::ifstream stream(input, std::ios_base::in | std::ios_base::binary); THROW_LAST_ERROR_IF(stream.fail()); return Load(stream, hashOut); } Node Load(const std::filesystem::path& input) { return Load(input, nullptr); } Node Load(const std::filesystem::path& input, Utility::SHA256::HashBuffer& hashOut) { return Load(input, &hashOut); } Emitter::Emitter() : m_document(std::make_unique<Wrapper::Document>(true)) { SetAllowedInputs<InputType::BeginMap, InputType::BeginSeq>(); } Emitter::Emitter(Emitter&&) noexcept = default; Emitter& Emitter::operator=(Emitter&&) noexcept = default; Emitter::~Emitter() = default; Emitter& Emitter::operator<<(EmitterEvent event) { switch (event) { case AppInstaller::YAML::BeginSeq: { CheckInput(InputType::BeginSeq); int id = m_document->AddSequence(); AppendNode(id); m_containers.emplace(id, false); SetAllowedInputsForContainer(); break; } case AppInstaller::YAML::EndSeq: CheckInput(InputType::EndSeq); m_containers.pop(); SetAllowedInputsForContainer(); break; case AppInstaller::YAML::BeginMap: { CheckInput(InputType::BeginMap); int id = m_document->AddMapping(); AppendNode(id); m_containers.emplace(id, true); SetAllowedInputsForContainer(); break; } case AppInstaller::YAML::EndMap: CheckInput(InputType::EndMap); m_containers.pop(); SetAllowedInputsForContainer(); break; case AppInstaller::YAML::Key: CheckInput(InputType::Key); m_scalarInfo = InputType::Key; SetAllowedInputs<InputType::Scalar>(); break; case AppInstaller::YAML::Value: CheckInput(InputType::Value); m_scalarInfo = InputType::Value; SetAllowedInputs<InputType::Scalar, InputType::BeginMap, InputType::BeginSeq>(); break; default: THROW_HR(E_UNEXPECTED); } return *this; } Emitter& Emitter::operator<<(std::string_view value) { CheckInput(InputType::Scalar); int id = m_document->AddScalar(value); if (!m_scalarInfo) { // Part of a sequence AppendNode(id); // No change to allowed inputs } else if (m_scalarInfo.value() == InputType::Key) { m_keyId = id; m_scalarInfo = std::nullopt; SetAllowedInputs<InputType::Value, InputType::BeginMap, InputType::BeginSeq>(); } else if (m_scalarInfo.value() == InputType::Value) { // Mapping pair complete AppendNode(id); m_scalarInfo = std::nullopt; SetAllowedInputsForContainer(); } else { THROW_HR(APPINSTALLER_CLI_ERROR_YAML_INVALID_EMITTER_STATE); } return *this; } Emitter& Emitter::operator<<(int64_t value) { std::ostringstream stream; stream << value; return operator<<(stream.str()); } Emitter& Emitter::operator<<(bool value) { return operator<<(value ? "true"sv : "false"sv); } std::string Emitter::str() { std::ostringstream stream; Wrapper::Emitter emitter(stream); emitter.Dump(*m_document); emitter.Flush(); return stream.str(); } void Emitter::Emit(std::ostream& out) { Wrapper::Emitter emitter(out); emitter.Dump(*m_document); emitter.Flush(); } void Emitter::AppendNode(int id) { if (!m_containers.empty()) { ContainerInfo& ci = m_containers.top(); if (ci.IsMapping) { THROW_HR_IF(APPINSTALLER_CLI_ERROR_YAML_INVALID_EMITTER_STATE, !m_keyId); m_document->AppendMappingPair(ci.Id, m_keyId.value(), id); m_keyId = std::nullopt; } else { m_document->AppendSequenceItem(ci.Id, id); } } } size_t Emitter::GetInputBitmask(InputType type) { return static_cast<size_t>(1) << static_cast<size_t>(type); } void Emitter::CheckInput(InputType type) { if ((m_allowedInputs & GetInputBitmask(type)) == 0) { AICLI_LOG(YAML, Error, << "Invalid emitter input [0x" << std::hex << std::setw(2) << std::setfill('0') << GetInputBitmask(type) << "], expected one of [0x" << std::hex << std::setw(2) << std::setfill('0') << m_allowedInputs << "]"); THROW_HR(APPINSTALLER_CLI_ERROR_YAML_INVALID_EMITTER_STATE); } } void Emitter::SetAllowedInputsForContainer() { if (m_containers.empty()) { m_allowedInputs = 0; } else { if (m_containers.top().IsMapping) { SetAllowedInputs<InputType::Key, InputType::EndMap>(); } else { SetAllowedInputs<InputType::Scalar, InputType::BeginMap, InputType::BeginSeq, InputType::EndSeq>(); } } } }
13,501
4,174
#pragma once #include "Location.hpp" class Unit { int _damage, _maxHP, _currentHP, _range, _moveCooldown, _weaponCooldown, _lastMove, _lastAttack; public: Unit() : _damage(0) , _maxHP(0) , _currentHP(0) , _range(0) , _moveCooldown(0) , _weaponCooldown(0) , _lastMove(-1) , _lastAttack(-1) { } Unit(const int & damage, const int & maxHP, const int & currentHP, const int & range, const int & moveCooldown, const int & weaponCooldown) : _damage(damage) , _maxHP(maxHP) , _currentHP(currentHP) , _range(range) , _moveCooldown(moveCooldown) , _weaponCooldown(weaponCooldown) , _lastMove(-1) , _lastAttack(-1) { } const int damage() const { return _damage; } const int maxHP() const { return _maxHP; } const int currentHP() const { return _currentHP; } const int range() const { return _range; } const int moveCooldown() const { return _moveCooldown; } const int weaponCooldown() const { return _weaponCooldown; } const int lastMove() const { return _lastMove; } const int lastAttack() const { return _lastAttack; } };
1,175
506
/*===================== begin_copyright_notice ================================== Copyright (c) 2017 Intel Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ======================= end_copyright_notice ==================================*/ #include <cmath> #include "HWConformity.h" #include "Optimizer.h" #include "visa_wa.h" #include "DebugInfo.h" #include "G4Verifier.h" using namespace vISA; static G4_CondModifier getReverseCondMod( G4_CondModifier mod ) { switch(mod) { case Mod_z: return Mod_z; case Mod_e: return Mod_e; case Mod_nz: return Mod_nz; case Mod_ne: return Mod_ne; case Mod_g: return Mod_l; case Mod_ge: return Mod_le; case Mod_l: return Mod_g; case Mod_le: return Mod_ge; default: MUST_BE_TRUE( 0, "Invalid conditional modifier input for reversed conditional modifier." ); } return Mod_cond_undef; } static bool isCompressedInst( G4_INST *inst ){ return inst->isComprInst(); } #define isUnitRegionRow( opnd, exec_size ) \ ( opnd->isImm() || \ opnd->isSrcRegRegion() && opnd->asSrcRegRegion()->getRegion()->width == exec_size || \ opnd->isSrcRegRegion() && opnd->asSrcRegRegion()->getRegion()->vertStride == 0 ) G4_SubReg_Align HWConformity::getDclAlignment( int opndBytes, G4_INST *inst, bool isScalar) { auto subAlign = Get_G4_SubRegAlign_From_Size( (uint16_t) opndBytes ); bool hasAccSrc = inst->hasACCSrc(); if( hasAccSrc && subAlign < GRFALIGN ) { subAlign = GRFALIGN; } if (!isScalar) { // certain instructions have additional alignment requirements for non-scalar sources, FIXME: what about 64 bytes? if (!builder.hasAlign1Ternary() && inst->getNumSrc() == 3 && !inst->isSend() && subAlign < Eight_Word) { subAlign = Eight_Word; } if (inst->isMath()) //FIXME: need confirm, used to be GRFALIGN { subAlign = GRFALIGN; } } return subAlign; } /* * create a new mov instruction and insert it before iter * mov (esize) dst tmp:type * where esize is "inst"'s execution size and insert it after "inst" * return value is the new temp variable as a dst operand * If dstAlign is specified, the new temp will at least be aligend to that size */ G4_DstRegRegion* HWConformity::insertMovAfter( INST_LIST_ITER& it, G4_DstRegRegion* dst, G4_Type type, G4_BB *bb, G4_SubReg_Align dstAlign ) { G4_INST* inst = *it; if( !dst ) { return dst; } if (inst->hasNULLDst() ) { return builder.createDstRegRegion(Direct, dst->getBase(), 0, 0, 1, type); } INST_LIST_ITER iter = it; iter++; unsigned char exec_size = inst->getExecSize(); G4_Type execType = inst->isRawMov() ? dst->getType() : inst->getExecType(); bool scalarSrc = true; for (int i = 0, numSrc = inst->getNumSrc(); i < numSrc; i++) { G4_Operand *src = inst->getSrc(i); if( !src->isImm() ) { if (!(inst->isMath() && i == 1 && src->isNullReg()) && (src->isSrcRegRegion() && !src->asSrcRegRegion()->isScalar())) { scalarSrc = false; } } else if( IS_VINTTYPE(src->getType()) || IS_VFTYPE(src->getType()) ) { scalarSrc = false; } } uint8_t newExecSize = ((inst->opcode() == G4_sel || inst->getImplAccSrc() || !scalarSrc) ? exec_size : 1); uint32_t opExecWidthBytes = newExecSize * G4_Type_Table[execType].byteSize; if( execType == Type_DF && IS_BTYPE( type ) ) { type = ( type == Type_UB ? Type_UW : Type_W ); } uint16_t dstWidthBytes = newExecSize * G4_Type_Table[type].byteSize; uint16_t scale = G4_Type_Table[execType].byteSize / G4_Type_Table[type].byteSize; /* so according to comments in function that call it MAD needs to have packed format. It ends up with hStride 2, due to DefHoisting. So it is trying to undo it. For every other type if srcType > dstCype we need to adjust regions. This is not necessary for HF. It's already packed. The src region of move is wrong. Since for HF it is packed, unlike other data types. mad (8) r56.0.xyzw:hf -r37.0.xyzw:f r59.0.xyzw:hf r58.0.xyzw:hf {Align16, NoMask} mov (16) r44.0<2>:hf r56.0<16;8,2>:hf {Align1, H1} // #??:$39:%66 */ if (scale == 0 || (getGenxPlatform() >= GENX_CHV && execType == Type_F && type == builder.getMixModeType())) { scale = 1; } G4_SubReg_Align subAlign = getDclAlignment(opExecWidthBytes > dstWidthBytes ? opExecWidthBytes : dstWidthBytes, inst, newExecSize == 1); if (subAlign < dstAlign) { subAlign = dstAlign; } RegionDesc* region = newExecSize > 1 ? builder.createRegionDesc(scale, 1, 0) : builder.getRegionScalar(); G4_Declare* dcl = builder.createTempVar( newExecSize == 1 ? 1 : newExecSize * scale, type, subAlign ); G4_SrcRegRegion *srcRegion = builder.Create_Src_Opnd_From_Dcl( dcl, region ); G4_Predicate *pred = NULL; if (inst->opcode() != G4_sel) { pred = inst->getPredicate(); inst->setPredicate( NULL ); // maintainDU4TempMov will update def-use } unsigned int new_option = inst->getMaskOption(); G4_INST* newInst = builder.createInternalInst( pred, G4_mov, NULL, inst->getSaturate(), exec_size, dst, srcRegion, NULL, new_option, inst->getLineNo(), inst->getCISAOff(), inst->getSrcFilename() ); bb->insert( iter, newInst ); // update propagation info maintainDU4TempMov( inst, newInst ); if( type == dst->getType() ) { newInst->setSaturate( false ); } else if (type == Type_F || type == Type_DF) { inst->setSaturate(false); } inst->setExecSize( newExecSize ); if (newExecSize == 1) { inst->setOptions((inst->getOption() & ~InstOpt_Masks ) | InstOpt_WriteEnable); } return builder.Create_Dst_Opnd_From_Dcl( dcl, scale); } // // replace instruction (*it)' source srcPos, which must be a scalar/immediate, // with a temp variable after inserting // mov (esize) tmp<1>:type imm/scalar {options} // before the instruction // This is like insertMovBefore(), except that the latter will always use // simd1 move for scalar/imm values, which may not be what we want // NOTE: This does not check for redundant moves. We are counting on a later LVN pass // to clean them up // void HWConformity::broadcast( G4_BB* bb, INST_LIST_ITER it, int srcPos, G4_SubReg_Align align) { G4_INST* inst = *it; G4_Operand* src = inst->getSrc(srcPos); MUST_BE_TRUE(src->isImm() || (src->isSrcRegRegion() && src->asSrcRegRegion()->isScalar()), "source must be an immediate or scalar"); G4_Type type = src->getType(); uint8_t execSize = inst->getExecSize(); uint32_t instMask = inst->getMaskOption(); // avoid simd16 Qword moves MUST_BE_TRUE(execSize * G4_Type_Table[type].byteSize <= 2u * GENX_GRF_REG_SIZ, "move can't exceed 2 GRFs"); G4_Declare* dcl = builder.createTempVar( execSize, type, align ); G4_DstRegRegion* dst = builder.createDstRegRegion( Direct, dcl->getRegVar(), 0, 0, 1, type); G4_INST* newInst = builder.createMov(execSize, dst, src, instMask, false); bb->insert(it, newInst); RegionDesc* srcRegion = builder.getRegionStride1(); G4_SrcRegRegion* newSrc = builder.Create_Src_Opnd_From_Dcl(dcl, srcRegion); inst->setSrc(newSrc, srcPos); newInst->addDefUse(inst, inst->getSrcOperandNum(srcPos)); } // // A simplified version of insertMovBefore(), this copies raw bytes from source to a temp // and replaces the original source with tmp. This is primarily used to ensure operand alignment and region restrictions // op (esize) ... (mod) src<region>:type // --> // mov (esize) tmp<1>:type src<region>:type // op (esize) ... (mod) tmp<1;1,0>:type // // source must be a G4_SrcRegRegion (direct or indirect), immediates are not supported // note that modifier is propagated from source to tmp, but region is not // // G4_SrcRegRegion* HWConformity::insertCopyBefore(INST_LIST_ITER it, uint32_t srcNum, G4_SubReg_Align tmpAlign, G4_BB *bb) { G4_INST* inst = *it; G4_Operand* src = inst->getSrc(srcNum); MUST_BE_TRUE(src != nullptr && src->isSrcRegRegion(), "source must be a SrcRegRegion"); G4_SrcRegRegion* origSrc = src->asSrcRegRegion(); uint8_t newExecSize = origSrc->isScalar() ? 1 : inst->getExecSize(); G4_Declare* dcl = builder.createTempVar(newExecSize, origSrc->getType(), tmpAlign); G4_SrcModifier modifier = origSrc->getModifier(); origSrc->setModifier(Mod_src_undef); G4_DstRegRegion* dst = builder.Create_Dst_Opnd_From_Dcl(dcl, 1); G4_INST* movInst = builder.createMov(newExecSize, dst, origSrc, InstOpt_WriteEnable, false); bb->insert(it, movInst); G4_SrcRegRegion* newSrc = builder.createSrcRegRegion(modifier, Direct, dcl->getRegVar(), 0, 0, newExecSize == 1 ? builder.getRegionScalar() : builder.getRegionStride1(), dcl->getElemType()); return newSrc; } /* * create a new mov instruction * mov (esize) tmp<1>:type src * where esize is "inst"'s execution size and insert it before "inst" * return value is the new temp variable as a source operand */ G4_Operand* HWConformity::insertMovBefore( INST_LIST_ITER it, uint32_t srcNum, G4_Type type, G4_BB *bb, G4_SubReg_Align tmpAlign ) { G4_INST* inst = *it; G4_SubReg_Align subAlign; RegionDesc* region = NULL; unsigned short vs = 0, hs = 0, wd = 1; unsigned char exec_size = inst->getExecSize(); G4_Operand *src = inst->getSrc( srcNum ); unsigned short scale = IS_BTYPE( src->getType() ) && src->getType() == type ? 2 : 1; uint8_t newExecSize = ((src->isImm() && !IS_VTYPE(src->getType())) || (src->isSrcRegRegion() && src->asSrcRegRegion()->isScalar())) ? 1 : exec_size; if( newExecSize > 1 ) { if (scale == 1 && !IS_VTYPE(src->getType())) { scale = (unsigned short) (G4_Type_Table[src->getType()].byteSize / G4_Type_Table[type].byteSize); } if( scale == 0 ) { scale = 1; } hs = scale; if( isCompressedInst(inst) || G4_Type_Table[type].byteSize * exec_size * hs > G4_GRF_REG_NBYTES ) { wd = exec_size / 2; } else { wd = exec_size; } vs = wd * hs; } else { vs = 0; wd = 1; hs = 0; scale = (unsigned short)(G4_Type_Table[src->getType()].byteSize / G4_Type_Table[type].byteSize); if (scale == 0) { scale = 1; } } region = builder.createRegionDesc(vs, wd, hs); int opExecWidthBytes = IS_VINTTYPE(src->getType()) ? G4_GRF_REG_NBYTES/2 * ( exec_size > 8 ? exec_size/8 : 1 ) : ( src->getType() == Type_VF ? G4_GRF_REG_NBYTES/2 * ( exec_size > 4 ? exec_size/4 : 1 ) : newExecSize * G4_Type_Table[type].byteSize * scale ); subAlign = getDclAlignment( opExecWidthBytes, inst, newExecSize == 1); if (subAlign < tmpAlign) { subAlign = tmpAlign; } uint32_t newInstEMask = newExecSize == 1 ? InstOpt_WriteEnable : inst->getMaskOption(); // due to old BDW regioning rule we need NoMask inst here so they can be split if (builder.getOptions()->isTargetCM() && getGenxPlatform() == GENX_BDW) { if (bb->isInSimdFlow()) { newInstEMask = InstOpt_WriteEnable; } } G4_Declare* dcl = builder.createTempVar( newExecSize == 1 ? 1 : newExecSize * scale, type, subAlign ); G4_DstRegRegion *dstRegion = builder.Create_Dst_Opnd_From_Dcl(dcl, scale); G4_INST* newInst = builder.createMov(newExecSize, dstRegion, builder.duplicateOperand(src), newInstEMask, false); bb->insert( it, newInst ); inst->transferDef( newInst, Gen4_Operand_Number(srcNum + 1), Opnd_src0 ); newInst->addDefUse(inst, Gen4_Operand_Number(srcNum + 1)); G4_SrcModifier modifier = Mod_src_undef; if (src->isSrcRegRegion() && src->asSrcRegRegion()->getModifier() == Mod_Not) { // mov doesn't support logic modifiers, so we keep it on the new source modifier = Mod_Not; newInst->getSrc(0)->asSrcRegRegion()->setModifier(Mod_src_undef); } return builder.createSrcRegRegion( modifier, Direct, dcl->getRegVar(), 0, 0, region, dcl->getElemType()); } void HWConformity::fixPackedSource(INST_LIST_ITER it, G4_BB *bb, G4_Type extype) { G4_INST* inst = *it; bool nonTypeWFound = false, nonTypeFFound = false, incompatibleTypeFound = false; for( int i = 0; i < G4_Inst_Table[inst->opcode()].n_srcs; i++ ) { G4_Operand *src = inst->getSrc(i); if( !src || !(IS_VTYPE(src->getType()))) { // Make sure other src operands are of word type only as this is a HW requirement if( src && ( src->getType() != Type_W && src->getType() != Type_UW ) ) { nonTypeWFound = true; } if( src && ( src->getType() != Type_F ) ) { nonTypeFFound = true; } continue; } G4_Type target_type = Type_W; if( src->getType() == Type_VF ) { target_type = Type_F; } if( target_type == Type_W && nonTypeWFound == true ) { // non-word type src is not allowed to co-exist with :v src incompatibleTypeFound = true; } else if( target_type == Type_F && nonTypeFFound == true ) { // non-float type src is not allowed to co-exist with :vf src incompatibleTypeFound = true; } // Insert a move only if immediate operand is not // last src operand if( i != G4_Inst_Table[inst->opcode()].n_srcs - 1 || incompatibleTypeFound == true ) { inst->setSrc( insertMovBefore( it, i, target_type, bb), i ); } } } /* * fixMathInst() checks the following: * The math instruction can only use GRF registers as source(s) and destination. * The math instruction does not support indirect addressing modes. * source horizontal stride must be 1 with the exception of scalar sources and destination horizontal stride must be always 1. * Source and destination offset must be the same, except the case of scalar source * DW and UD is the only source format supported for INT DIV, FP16/FP32 is the only source format supported for all the other functions. * Mixed DW and UD sources are not allowed for the INT DIV function. * For single source math function, <src1> must be programmed as ARF-NULL register. */ bool HWConformity::fixMathInst(INST_LIST_ITER it, G4_BB *bb) { G4_INST* inst = *it; G4_DstRegRegion *dst = inst->getDst(); G4_Operand *src0 = inst->getSrc(0), *src1 = inst->getSrc(1); bool mov_dst = false; MUST_BE_TRUE(inst->isMath(), "Expect math instruction"); if (inst->asMathInst()->getMathCtrl() == MATH_INVM || inst->asMathInst()->getMathCtrl() == MATH_RSQRTM) { if (IS_DFTYPE(inst->getDst()->getType()) && ((uint32_t) (inst->getExecSize() * 2)) > builder.getNativeExecSize()) { // need to scale exec size by two since it's 64b type evenlySplitInst(it, bb); return true; } return false; } // covers MATH_INT_DIV, MATH_INT_DIV_QUOT, MATH_INT_DIV_REM bool isIntDivide = inst->asMathInst()->isMathIntDiv(); bool hasSameOffset = hasSameSubregOffset(inst); // check if the source needs a move and if so the new move type auto needsMove = [this, inst, isIntDivide, hasSameOffset](int srcID, G4_Type& newType) { assert((srcID == 0 || srcID == 1) && "math can have at most two sources"); G4_Operand* src = inst->getSrc(srcID); newType = src->getType(); if (isIntDivide) { G4_Type divType = IS_UNSIGNED_INT(inst->getSrc(0)->getType()) && IS_UNSIGNED_INT(inst->getSrc(1)->getType()) ? Type_UD : Type_D; if (newType != divType) { newType = divType; return true; } } else if ((src->getType() != Type_F && src->getType() != Type_VF) && (getGenxPlatform() == GENX_BDW || src->getType() != Type_HF)) { // CHV+ supports F/HF math, while BDW only supports F math // mix mode math is handled in fixMixedHFInst() newType = Type_F; return true; } if (src->isImm()) { if (srcID == 0 && inst->asMathInst()->getMathCtrl() >= MATH_FDIV) { return true; } } else if (src->isSrcRegRegion()) { G4_SrcRegRegion *srcRegion = src->asSrcRegRegion(); RegionDesc *rd = srcRegion->getRegion(); if (srcRegion->getModifier() != Mod_src_undef && isIntDivide) { // no source modifer for int divide return true; } else if (srcRegion->getRegAccess() != Direct) { return true; } else if (!srcRegion->isScalar()) { if (!hasSameOffset && !builder.isOpndAligned(srcRegion, GENX_GRF_REG_SIZ)) { return true; } else if (!rd->isContiguous(inst->getExecSize())) { return true; } } } else { ASSERT_USER(false, "Unexpected math source!"); } return false; }; if (src0) { G4_Type src0_type = src0->getType(); bool needsSrc0Mov = needsMove(0, src0_type); if (needsSrc0Mov) { inst->setSrc(insertMovBefore(it, 0, src0->isImm() ? getNonVectorType(src0_type) : src0_type, bb), 0); src0 = inst->getSrc(0); } } bool nullSrc1 = src1 && src1->isNullReg(); if (!nullSrc1 && src1) { G4_Type src1_type = src1->getType(); bool needsSrc1Move = needsMove(1, src1_type); if (needsSrc1Move) { if (isIntDivide && src1->isImm() && !IS_VINTTYPE(src1->getType())) { // just change the immediate's type uint32_t immVal = (uint32_t)src1->asImm()->getImm(); inst->setSrc(builder.createImm(immVal, src1_type), 1); } else { inst->setSrc(insertMovBefore(it, 1, src1->isImm() ? getNonVectorType(src1_type) : src1_type, bb), 1); } src1 = inst->getSrc(1); } } if (nullSrc1 && src0 && src1->getType() != src0->getType()) { G4_SrcRegRegion *src1_opnd = builder.createNullSrc(inst->getSrc(0)->getType()); inst->setSrc(src1_opnd, 1); } // recompute as src0 and src1 may have been modified hasSameOffset = hasSameSubregOffset(inst); G4_Type extype = inst->getExecType2(); bool cond1 = (dst->getType() != extype && !(dst->getType() == Type_UD && extype == Type_D)); if (dst->getRegAccess() != Direct || dst->getHorzStride() != 1 || cond1 || (!hasSameOffset && inst->getExecSize() != 1 && !builder.isOpndAligned(dst, GENX_GRF_REG_SIZ))) { mov_dst = true; G4_DstRegRegion *new_dst = insertMovAfter(it, dst, extype, bb); inst->setDest(new_dst); } return mov_dst; } // find a common (integer) type for constant folding. The rules are: // -- both types must be int // -- Q and UQ are not folded // -- UD if one of the type is UD // -- D otherwise // // returns Type_UNDEF if no appropriate type can be found // static G4_Type findConstFoldCommonType( G4_Type type1, G4_Type type2 ) { if (IS_TYPE_INT(type1) && IS_TYPE_INT(type2)) { if (G4_Type_Table[type1].byteSize == 8 || G4_Type_Table[type2].byteSize == 8) { return Type_UNDEF; } if (type1 == Type_UD || type2 == Type_UD) { return Type_UD; } else { return Type_D; } } return Type_UNDEF; } // // returns true if all sources and dst in this inst have the same fixed subreg offset // null src/dst, scalar sources and immediates are excluded from the check // bool HWConformity::hasSameSubregOffset(G4_INST* inst) const { bool anyOffset = true; // true means offset is not fixed yet uint32_t byteOffset = 0; if (inst->getDst()) { G4_DstRegRegion* dst = inst->getDst(); if (dst->isNullReg()) { // do nothing } else if (dst->hasFixedSubregOffset(byteOffset)) { anyOffset = false; } else { return false; } } for (int i = 0; i < inst->getNumSrc(); ++i) { G4_Operand* src = inst->getSrc(i); if (src->isSrcRegRegion()) { uint32_t srcOffset = 0; G4_SrcRegRegion* srcRegion = src->asSrcRegRegion(); if (srcRegion->isNullReg() || srcRegion->isScalar()) { continue; } else if (srcRegion->hasFixedSubregOffset(srcOffset)) { if (anyOffset) { byteOffset = srcOffset; anyOffset = false; } else if (srcOffset != byteOffset) { return false; } } else { return false; } } } return true; } // Check the following rules // -- src0 in 2 source instructions may not be immediate. We try to swap for src0 and src1 for // commutative instructions in such cases // -- ARF may not be in src1 void HWConformity::fixImmAndARFSrc(INST_LIST_ITER it, G4_BB *bb) { G4_INST* inst = *it; if (inst->mayExceedTwoGRF()) { return; } G4_Operand *src0, *src1, *src2; src0 = inst->getSrc(0); src1 = inst->getSrc(1); src2 = inst->getSrc(2); /* Check for usage of two constants in binary operations */ if (src0 != NULL && (src0->isImm() || src0->isAddrExp()) && G4_Inst_Table[inst->opcode()].n_srcs == 2) { if (INST_COMMUTATIVE(inst->opcode()) && !src1->isImm()) { //all commutative inst must have 2 sources if (inst->opcode() == G4_mul) { bool needConstMov; //for DW and W mul, src0 must be DW and src1 W needConstMov = IS_DTYPE(src0->getType()) && !IS_DTYPE(src1->getType()); if (needConstMov) { G4_Type tmpType = getNonVectorType(src0->getType()); G4_Operand* newSrc0 = insertMovBefore(it, 0, tmpType, bb); inst->setSrc(newSrc0, 0); } else { // swap operands inst->setSrc(src1, 0); inst->setSrc(src0, 1); inst->swapDefUse(); } } else { // swap operands inst->setSrc(src1, 0); inst->setSrc(src0, 1); inst->swapDefUse(); } } /* * A select operation isn't commutative, but we may commute the * operands provided we perform a predicate inversion as well. * (v0) sel ... const V1 * => * (-v0) sel ... V1 const */ else if (inst->opcode() == G4_sel && !src1->isImm()) { bool SwapOpnd = false; G4_CondMod *cond = inst->getCondMod(); if (cond != NULL) { switch (cond->getMod()) { case Mod_ne: { inst->setCondMod(builder.createCondMod(Mod_e, cond->getBase(), 0)); SwapOpnd = true; break; } case Mod_e: { inst->setCondMod(builder.createCondMod(Mod_ne, cond->getBase(), 0)); SwapOpnd = true; break; } default: SwapOpnd = true; break; } } else { G4_Predicate* pred = inst->getPredicate(); MUST_BE_TRUE(pred != NULL, "predicate must not be null"); G4_PredState reverse = pred->getState() == PredState_Minus ? PredState_Plus : PredState_Minus; inst->setPredicate(builder.createPredicate( reverse, pred->getBase(), pred->getSubRegOff(), pred->getControl())); SwapOpnd = true; } if (SwapOpnd) { inst->setSrc(src1, 0); inst->setSrc(src0, 1); inst->swapDefUse(); } else { G4_Type tmpType = getNonVectorType(src0->getType()); G4_Operand* newSrc0 = insertMovBefore(it, 0, tmpType, bb); inst->setSrc(newSrc0, 0); } } else if (!inst->isMath()) { // math immediate src0 is handled separately in fixMathInst() if ((inst->opcode() == G4_add || inst->opcode() == G4_mul) && src0->isImm() && src1->isImm() && IS_TYPE_INT(src0->getType()) && IS_TYPE_INT(src1->getType()) && inst->getSaturate() == false) { // FIXME: this is duplicating the functionality of Optimizer::doConsFolding. G4_Type src0T = src0->getType(), src1T = src1->getType(), resultType = src0T; resultType = findConstFoldCommonType(src0T, src1T); if (resultType != Type_UNDEF) { G4_Imm *newSrc = NULL; int64_t res = inst->opcode() == G4_add ? ((int64_t)(src0->asImm()->getInt()) + (int64_t)(src1->asImm()->getInt())) : ((int64_t)(src0->asImm()->getInt()) * (int64_t)(src1->asImm()->getInt())); // don't fold if the value overflows D/UD if (G4_Imm::isInTypeRange(res, resultType)) { newSrc = builder.createImmWithLowerType(res, resultType); // change instruction into a MOV inst->setOpcode(G4_mov); inst->setSrc(newSrc, 0); inst->setSrc(NULL, 1); return; } } } // If src0 is not 64-bit, src1 is 64-bit, swap them to save one move. if (INST_COMMUTATIVE(inst->opcode()) && src0->isImm() && src1->isImm() && G4_Type_Table[src0->getType()].byteSize != 8 && G4_Type_Table[src1->getType()].byteSize == 8) { inst->setSrc(src1, 0); inst->setSrc(src0, 1); inst->swapDefUse(); src0 = inst->getSrc(0); src1 = inst->getSrc(1); } if (INST_COMMUTATIVE(inst->opcode()) && src0->isAddrExp() && src1->isImm()) { // The original IR has both addr expr and immediate // add(8) A0(0, 0)<1>:uw &V36 + 0 0xeca86420 : uv{ Align1, Q1 } // We insert a move for src1 which is an immediate // mov(8) TV0(0, 0)<1> : uw 0xeca86420 : uv{ Align1 } // add(8) A0(0, 0)<1> : uw &V36 + 0 TV0(0, 0)<8; 8, 1> : uw{ Align1, Q1 } G4_Type type = src1->getType(); inst->setSrc(insertMovBefore(it, 1, getNonVectorType(type), bb), 1); // And we swap addr expr and the new variable // add(8) A0(0, 0)<1> : uw TV0(0, 0)<8; 8, 1> : uw &V36 + 0 {Align1, Q1} // The final code sequence is // mov(8) r13.0<1>:uw 0xeca86420 : uv{ Align1 } // #26:$9:%79 // add(8) a0.0<1> : uw r13.0<8; 8, 1> : uw 0x60 : uw{ Align1, Q1 } inst->setSrc(inst->getSrc(1), 0); inst->setSrc(src0, 1); inst->swapDefUse(); } else { G4_Type newSrcType = inst->needsDWType() ? (IS_UNSIGNED_INT(src0->getType()) ? Type_UD : Type_D) : src0->getType(); inst->setSrc(insertMovBefore(it, 0, newSrcType, bb), 0); } } } src0 = inst->getSrc(0); src1 = inst->getSrc(1); src2 = inst->getSrc(2); // check for non-mad 3src inst if (G4_Inst_Table[inst->opcode()].n_srcs == 3 && src1->isImm()) { inst->setSrc(insertMovBefore(it, 1, INST_FLOAT_SRC_ONLY(inst->opcode()) ? Type_F : src1->getType(), bb), 1); } // Architecture registers may not appear as src1. auto isARF = [](G4_Operand* opnd) { return opnd->isAreg() || opnd->isFlag(); }; if (src1 != nullptr && isARF(src1) && !src1->isNullReg()) { /* See if we can swap the src1 */ if (INST_COMMUTATIVE(inst->opcode()) && !isARF(src0)) { inst->setSrc(src1, 0); inst->setSrc(src0, 1); inst->swapDefUse(); } /* Otherwise introduce a tmp */ inst->setSrc(insertMovBefore(it, 1, INST_FLOAT_SRC_ONLY(inst->opcode()) ? Type_F : src1->getType(), bb), 1); } src2 = inst->getSrc(2); /* 3 src instructions can't have any constants */ if (!builder.hasAlign1Ternary() && src2 != nullptr && src2->isImm()) { inst->setSrc(insertMovBefore(it, 2, src2->getType(), bb), 2); } } bool HWConformity::fixLine(INST_LIST_ITER it, G4_BB *bb) { G4_INST* inst = *it; if (inst->opcode() == G4_line) { bool badRegion = false; G4_Operand* src0 = inst->getSrc(0); // assumption: there are 4 elements in src0 if (src0->isSrcRegRegion()) { RegionDesc *rd = src0->asSrcRegRegion()->getRegion(); badRegion = (rd->vertStride != 0 || rd->width != 4 || rd->horzStride != 1); } if (!IS_FTYPE(src0->getType()) || src0->isImm() || badRegion || !builder.isOpndAligned(src0, G4_GRF_REG_NBYTES / 2)) { // insertMovBefore() is not used here // due to the special region <0;4,1> of src0 of line G4_Declare *src0_dcl; G4_DstRegRegion *new_dst_opnd; G4_SrcRegRegion *new_src0_opnd; unsigned char mov_size = 4; src0_dcl = builder.createTempVar(mov_size, Type_F, Eight_Word); /* Create temporary variable */ // Actully we set region to be <0;4,1> directly here. RegionDesc *rd = builder.createRegionDesc(0, 4, 1); new_src0_opnd = builder.Create_Src_Opnd_From_Dcl(src0_dcl, rd); new_dst_opnd = builder.Create_Dst_Opnd_From_Dcl(src0_dcl, 1); G4_INST* newInst = builder.createMov(mov_size, new_dst_opnd, src0, InstOpt_NoOpt, false); if (bb->isInSimdFlow()) { newInst->setOptions((newInst->getOption() & ~InstOpt_Masks) | InstOpt_WriteEnable); } bb->insert(it, newInst); inst->setSrc(new_src0_opnd, 0); return true; } } return false; } bool HWConformity::fixOpndType(INST_LIST_ITER it, G4_BB *bb) { /* * Check for instruction that only accept float/int operands, as well as * instruction with mixed operand types. Even though the CISA itself forbids * mixed type instructions, optimizations such as copy propagation * may reintroduce them and so we do the checks here */ G4_INST* inst = *it; bool changed = false; int numSrc = inst->getNumSrc(); bool has_float = false; bool has_int = false; if (inst->mayExceedTwoGRF()) { return false; } for (int i = 0; i < numSrc; i++) { if (!inst->getSrc(i)) { continue; } G4_Type ty = inst->getSrc(i)->getType(); if (IS_TYPE_FLOAT_ALL(ty)) { has_float = true; } else { has_int = true; } } if (has_float && has_int) { for (int i = 0; i < numSrc; i++) { if (inst->getSrc(i) && !IS_FTYPE(inst->getSrc(i)->getType()) && !IS_DFTYPE(inst->getSrc(i)->getType())) { if (!((inst->opcode() == G4_smov) && (i == 1))) { inst->setSrc(insertMovBefore(it, i, Type_F, bb), i); changed = true; } } } } if (builder.noSrc1Byte()) { if (numSrc > 1) { G4_Operand* src0 = inst->getSrc(0); G4_Operand* src1 = inst->getSrc(1); if (src0 != nullptr && src1 != nullptr && IS_BTYPE(src1->getType())) { if (!IS_BTYPE(src0->getType()) && inst->canSwapSource()) { inst->setSrc(src1, 0); inst->setSrc(src0, 1); } else { inst->setSrc(insertMovBefore(it, 1, Type_W, bb), 1); changed = true; } } } } return changed; } /* * fixOpnds() looks for operands conformity: * 1. checks can operand be a constant. * 2. checks if operand's type is conformant to operation. * 3. check if only src0 uses VxH * 4. check if indirect scalar is used in compressed inst * It tries to fix these cases by changing operands order if possible * or by insertion if temporary location with appropriate conversion. */ void HWConformity::fixOpnds( INST_LIST_ITER it, G4_BB *bb, G4_Type& exType ) { G4_INST* inst = *it; if (inst->isSend()) { return; } G4_Operand *src0, *src1, *src2; src0 = inst->getSrc(0); src1 = inst->getSrc(1); src2 = inst->getSrc(2); if( inst->opcode() == G4_mul ) { if (IS_DTYPE(src1->getType()) && !(IS_DTYPE(src0->getType()) || IS_FTYPE(src0->getType()))) { // check if src0 uses VxH bool src0_use_VxH = false; if( src0->isSrcRegRegion() && src0->asSrcRegRegion()->getRegAccess() != Direct && src0->asSrcRegRegion()->getRegion()->isRegionWH() ) // is this safe? { src0_use_VxH = true; } if( src0_use_VxH ) { src0 = insertMovBefore( it, 0, src0->getType(), bb ); } inst->setSrc( src1, 0 ); inst->setSrc( src0, 1 ); inst->swapDefUse(); src0 = inst->getSrc(0); src1 = inst->getSrc(1); } if( src1->isSrcRegRegion() && src1->asSrcRegRegion()->getRegAccess() != Direct && src1->asSrcRegRegion()->getRegion()->isRegionWH() ) { if (IS_DTYPE(src0->getType()) && !(IS_DTYPE(src1->getType()) || IS_FTYPE(src1->getType()) ) ) { inst->setSrc( insertMovBefore( it, 1, src1->getType(), bb ), 1 ); } else { inst->setSrc( src1, 0 ); inst->setSrc( src0, 1 ); inst->swapDefUse(); } src0 = inst->getSrc(0); src1 = inst->getSrc(1); } } fixImmAndARFSrc(it, bb); src0 = inst->getSrc(0); src1 = inst->getSrc(1); src2 = inst->getSrc(2); // Vx1 and VxH can only be used for src0 bool src0_use_VxH = false, src1_use_VxH = false; if( src2 && src2->isSrcRegRegion() && src2->asSrcRegRegion()->getRegion()->isRegionWH() ) { inst->setSrc(insertMovBefore(it, 2, exType, bb), 2); } if (src0 != NULL && src0->isSrcRegRegion() && src0->asSrcRegRegion()->getRegion()->isRegionWH()) { src0_use_VxH = true; } if (src1 != NULL && src1->isSrcRegRegion() && src1->asSrcRegRegion()->getRegion()->isRegionWH()) { src1_use_VxH = true; } if (src1_use_VxH) { if ((INST_COMMUTATIVE(inst->opcode()) || inst->opcode() == G4_cmp) && !src0_use_VxH && !(inst->opcode() == G4_mul && IS_DTYPE(src0->getType()))) { inst->setSrc( src1, 0 ); inst->setSrc( src0, 1 ); if( inst->opcode() == G4_cmp ) { // change condMod G4_CondMod *condMod = inst->getCondMod(); if( condMod ) { G4_CondMod *newCondModOpnd = builder.createCondMod( getReverseCondMod(condMod->getMod()), condMod->getBase(), condMod->getSubRegOff()); inst->setCondMod( newCondModOpnd ); } } } else { inst->setSrc(insertMovBefore(it, 1, exType, bb), 1); } } // at this point only src0 may be VxH // VxH regioning and conditional modifiers may not co-exist if (getGenxPlatform() >= GENX_CNL) { src0 = inst->getSrc(0); if (src0 && src0->isSrcRegRegion() && src0->asSrcRegRegion()->getRegion()->isRegionWH()) { if (inst->getCondMod()) { inst->setSrc(insertMovBefore(it, 0, src0->getType(), bb), 0); } } } } void HWConformity::fixAlign13SrcInst(INST_LIST_ITER iter, G4_BB* bb) { // again mad should already conform by construction G4_INST* inst = *iter; MUST_BE_TRUE(inst->getNumSrc() == 3 && !inst->isSend(), "expect 3src inst"); if (inst->opcode() != G4_mad) { G4_DstRegRegion* dst = inst->getDst(); if (!isGoodAlign1TernaryDst(inst)) { auto alignment = builder.noSrc2Regioning() ? GRFALIGN : Four_Word; G4_DstRegRegion* tmpDst = insertMovAfter(iter, dst, dst->getType(), bb, alignment); inst->setDest(tmpDst); } bool canBeImm = true; for (int i = 0; i < inst->getNumSrc(); ++i) { if (!isGoodAlign1TernarySrc(inst, i, canBeImm)) { if (i == 2 && builder.noSrc2Regioning()) { // some additional handling for src2 when src2 regioning is not available fixSrc2(iter, bb, false); } else { G4_SubReg_Align subalign = (i == 2) ? Four_Word : Any; inst->setSrc(insertMovBefore(iter, i, inst->getSrc(i)->getType(), bb, subalign), i); } } else { if (inst->getSrc(i)->isImm()) { canBeImm = false; } } } } } void HWConformity::fix3SrcInst(INST_LIST_ITER iter, G4_BB* bb) { G4_INST* inst = *iter; if (inst->getNumSrc() != 3 || inst->mayExceedTwoGRF() || inst->opcode() == G4_madm) { return; } if (builder.hasAlign1Ternary()) { fixAlign13SrcInst(iter, bb); return; } if (inst->opcode() != G4_mad) { // check that dst and srcs are legal for 3src. We do not check // mad since they should already conform by construction uint8_t execSize = inst->getExecSize(); G4_DstRegRegion* dst = inst->getDst(); if (dst->getRegAccess() != Direct || dst->getHorzStride() != 1 || !builder.isOpndAligned(dst, (execSize >= 8) ? 32 : execSize * 4)) { G4_DstRegRegion* tmpDst = insertMovAfter(iter, dst, dst->getType(), bb); inst->setDest(tmpDst); } for (int i = 0; i < 3; i++) { if (!isGoodAlign16Src(inst, i)) { inst->setSrc( insertMovBefore(iter, i, inst->getSrc(i)->getType(), bb), i); } } } //When it is set (Align16), the instruction uses 16-byte-aligned addressing for source and destination operands. if ((inst->getExecSize() == 1)) { if (inst->getDst() && inst->getDst()->getBase()->isRegVar()) { if (!builder.isOpndAligned(inst->getDst(), 16)) { G4_DstRegRegion *new_dst = insertMovAfter(iter, inst->getDst(), inst->getDst()->getType(), bb); G4_Declare* tmpDstDcl = new_dst->getTopDcl(); tmpDstDcl->setSubRegAlign(Eight_Word); inst->setDest( new_dst ); } } } if (inst->getExecSize() == 16) { bool wa3rc = (VISA_WA_CHECK(builder.getPWaTable(), WaDisableSIMD16On3SrcInstr) && !(inst->getExecType() == Type_HF && inst->getOperand(Opnd_src1)->isSrcRegRegion() && inst->getOperand(Opnd_src1)->getType() == Type_HF && !inst->getOperand(Opnd_src1)->asSrcRegRegion()->crossGRF())); if (wa3rc) { evenlySplitInst(iter, bb); } } } void HWConformity::fixCompareInst( INST_LIST_ITER i, G4_BB *bb, G4_Type exType, int dst_elsize ) { G4_INST *inst = *i; G4_Operand *dst = inst->getDst(); if (dst && dst->isNullReg()) { // change dst hstride if necessary if (G4_Type_Table[exType].byteSize != G4_Type_Table[dst->getType()].byteSize) { // create a new dst with new stride G4_DstRegRegion *new_null = builder.createNullDst( exType ); inst->setDest( new_null ); } } } // For integer packing moves, we can replace the src type with the dst type instead of inserting // a new move to satisfy dst alignment, since integer down conversion is based on truncation // an inst has to satisfy the following properties: // -- is a move (duh) and does not have conditional modifiers or saturation // -- dst must be a direct DstRegRegion that is GRF-aligned // -- src must be a direct SrcRegRegion with GRF base, no modifiers, and packed/scalar region // -- both dst and src have integer type, with source stride > dst stride // returns true if we have successfully down cast the src type static bool canReplaceMovSrcType(IR_Builder& builder, G4_INST* inst, uint32_t extypesize) { if (inst->opcode() != G4_mov || inst->getCondMod() != NULL || inst->getSaturate()) { return false; } if (!inst->getSrc(0)->isSrcRegRegion()) { return false; } G4_DstRegRegion* dst = inst->getDst(); G4_SrcRegRegion* src0 = inst->getSrc(0)->asSrcRegRegion(); int dstByteOffset = dst->getByteOffset(); if (dstByteOffset % extypesize != 0 || dst->getRegAccess() != Direct) { // don't do this if dst is not GRF aligned, since we have to fix it later anyway return false; } if (src0->getRegAccess() != Direct || src0->getModifier() != Mod_src_undef || (src0->getTopDcl() == NULL || src0->getTopDcl()->getRegFile() != G4_GRF)) { return false; } bool isIntPackingMove = false; if (IS_TYPE_INT(dst->getType()) && IS_TYPE_INT(src0->getType())) { uint32_t dstAlign = G4_Type_Table[dst->getType()].byteSize * dst->getHorzStride(); if (dstAlign < G4_Type_Table[src0->getType()].byteSize) { isIntPackingMove = true; } } if (!isIntPackingMove) { return false; } // we only handle direct contiguous and scalar source region for now, // as VxH and strided regions are a bit harder to update if (src0->getRegion()->isContiguous(inst->getExecSize())) { uint16_t newHS = extypesize / G4_Type_Table[dst->getType()].byteSize; if (newHS > 4) { // rule out Q -> B moves if Q is not scalar return false; } } else if (!src0->isScalar()) { // only handle scalar and contiguous regions for now return false; } // instead of inserting a move, we change src's type to be same as dst type // e.g., // mov (8) r1.0<1>:b r2.4<8;8,1>:d // becomes // mov (8) r1.0<1>:b r2.16<32;8,4>:b // This is safe since integer down conversion is based on truncation uint32_t typeSizeRatio = extypesize / G4_Type_Table[dst->getType()].byteSize; uint32_t numElt = src0->isScalar() ? 1 : inst->getExecSize() * typeSizeRatio; G4_Declare* newDcl = builder.createTempVar(numElt, dst->getType(), Any); newDcl->setAliasDeclare(src0->getBase()->asRegVar()->getDeclare(), 0); RegionDesc* region = src0->isScalar() ? builder.getRegionScalar() : builder.createRegionDesc((uint16_t)inst->getExecSize(), (uint16_t)inst->getExecSize() * typeSizeRatio, inst->getExecSize(), (uint16_t)typeSizeRatio); G4_SrcRegRegion* newSrc = builder.createSrcRegRegion( Mod_src_undef, Direct, newDcl->getRegVar(), src0->getRegOff(), src0->getSubRegOff() * typeSizeRatio, region, dst->getType()); inst->setSrc(newSrc, 0); return true; } // implement HW restrictions on mov // -- There is no direct conversion from B/UB to DF or DF to B/UB. // Use two instructions and a word or DWord intermediate type. // -- There is no direct conversion from B/UB to Q/UQ or Q/UQ to B/UB. // Use two instructions and a word or DWord intermediate integer type. // -- There is no direct conversion from HF to DF or DF to HF. // Use two instructions and F (Float) as an intermediate type. // -- There is no direct conversion from HF to Q/UQ or Q/UQ to HF. // Use two instructions and F (Float) or a word integer type or a DWord integer type as an intermediate type. // returns true if a move is inserted bool HWConformity::fixMov(INST_LIST_ITER i, G4_BB* bb) { G4_INST* inst = *i; if (inst->opcode() != G4_mov) { return false; } G4_Type dstType = inst->getDst()->getType(); G4_Type srcType = inst->getSrc(0)->getType(); auto src = inst->getSrc(0); bool scalarByteToFloat = builder.noScalarByteToFloat() && IS_BTYPE(srcType) && IS_FTYPE(dstType) && src->isSrcRegRegion() && src->asSrcRegRegion()->isScalar(); bool dstByteSrc64b = IS_BTYPE(dstType) && (IS_DFTYPE(srcType) || IS_QTYPE(srcType)); if (scalarByteToFloat || dstByteSrc64b) { inst->setDest(insertMovAfter(i, inst->getDst(), Type_W, bb)); return true; } if (IS_BTYPE(srcType) && (IS_DFTYPE(dstType) || IS_QTYPE(dstType))) { // mov Q/DF B inst->setDest(insertMovAfter(i, inst->getDst(), Type_W, bb)); return true; } if (isLowPrecisionFloatTy(dstType) && (IS_DFTYPE(srcType) || IS_QTYPE(srcType))) { // mov HF Q/DF inst->setDest(insertMovAfter(i, inst->getDst(), Type_F, bb)); return true; } if (isLowPrecisionFloatTy(srcType) && (IS_DFTYPE(dstType) || IS_QTYPE(dstType))) { // mov Q/DF HF inst->setDest(insertMovAfter(i, inst->getDst(), Type_F, bb)); return true; } return false; } bool HWConformity::fixRotate(INST_LIST_ITER i, G4_BB* bb) { // rotate requires src0 and dst to have the same datatype precision // It also does not support *B/*Q types, but that should be enforced at the vISA level // returns true if new instruction is inserted bool changed = false; G4_INST* inst = *i; if (inst->opcode() != G4_rol && inst->opcode() != G4_ror) { return false; } G4_DstRegRegion* dst = inst->getDst(); G4_SrcRegRegion* src = inst->getSrc(0)->asSrcRegRegion(); MUST_BE_TRUE(IS_WTYPE(dst->getType()) || IS_DTYPE(dst->getType()), "dst type must be *W or *D"); MUST_BE_TRUE(IS_WTYPE(src->getType()) || IS_DTYPE(src->getType()), "src type must be *W or *D"); if (G4_Type_Table[dst->getType()].byteSize != G4_Type_Table[src->getType()].byteSize) { // keep exec type same and change dst to be same type as src inst->setDest(insertMovAfter(i, dst, src->getType(), bb)); changed = true; } if (dst->getType() == Type_W) { dst->setType(Type_UW); } else if (dst->getType() == Type_D) { dst->setType(Type_UD); } if (src->getType() == Type_W) { src->setType(Type_UW); } else if (src->getType() == Type_D) { src->setType(Type_UD); } return changed; } bool HWConformity::fixDstAlignment( INST_LIST_ITER i, G4_BB* bb, G4_Type extype, unsigned int dst_elsize ) { G4_INST *inst = *i; bool insertMOV = false; unsigned char exec_size = inst->getExecSize(); G4_DstRegRegion *dst = inst->getDst(); G4_Operand *src0 = inst->getSrc(0); unsigned h_stride = dst->getHorzStride(); unsigned int extypesize = G4_Type_Table[extype].byteSize; if (inst->hasNULLDst()) { if (dst_elsize * h_stride < extypesize) { uint16_t newHStride = extypesize / dst_elsize; if (newHStride == 8) { // dst is a null byte, this can be produced by logical optimization // we chagne the type to W here; this should be safe since the conditional modifier // is either .ez or .nz MUST_BE_TRUE(dst_elsize == 1, "expect B/UB dst"); dst->setType(dst->getType() == Type_B ? Type_W : Type_UW); dst->setHorzStride(4); } else { MUST_BE_TRUE(newHStride <= 4, "horizontal stride must be <=4"); dst->setHorzStride(newHStride); } } return insertMOV; } // optimize initialization instructions if( inst->opcode() == G4_mov && src0->isImm() && ( !bb->isInSimdFlow() || inst->isWriteEnableInst() ) && !inst->getPredicate() && dst->getRegAccess() == Direct && dst->getHorzStride() == 1 && inst->getSaturate() == false && IS_BTYPE(dst->getType()) && !IS_TYPE_F32_F64(src0->getType()) && builder.isOpndAligned( dst, getTypeSize(src0->getType()) ) ) { // inst is a mov with packed byte dst and int imm source int64_t value = src0->asImm()->getInt(); uint64_t new_value = ( value & 0xFF ) | ( value << 0x8 ); int scale = 2; if (IS_DTYPE(src0->getType())) { scale = 4; new_value = ( new_value & 0xFFFF ) | ( new_value << 0x10 ); } if (exec_size >= scale) { G4_Type new_type = ( scale == 2 ) ? Type_UW : Type_UD; dst->setHorzStride( 1 ); dst->setSubRegOff( (short) (dst->getSubRegOff() / scale) ); dst->setType( new_type ); inst->setSrc( builder.createImm( new_value, new_type ), 0 ); inst->setExecSize( (unsigned char) (exec_size / scale) ); return insertMOV; } } bool byteDst = IS_BTYPE(dst->getType()); // Byte can not be used as dstination of INT*INT if ((byteDst && inst->opcode() == G4_mul && IS_TYPE_INT(inst->getSrc(0)->getType()) && IS_TYPE_INT(inst->getSrc(1)->getType()))) { // change dst type to W inst->setDest( insertMovAfter( i, dst, Type_W, bb ) ); return true; } if (byteDst && extypesize == 8) { // Gen doesn't support hstride 8, so we add a W move here inst->setDest(insertMovAfter(i, dst, Type_W, bb)); return true; } bool dstHFMixModeInst = inst->getDst()->getType() == builder.getMixModeType() && extype == Type_F; bool dstNotAlignedToExecType = exec_size > 1 && (dst_elsize * h_stride) < extypesize && !(builder.hasMixMode() && dstHFMixModeInst); unsigned short dst_byte_offset; builder.isOpndAligned(dst, dst_byte_offset, extypesize); if (!((dst_byte_offset % extypesize == 0) || (byteDst && !VISA_WA_CHECK(builder.getPWaTable(), WaByteDstAlignRelaxedRule) && (dst_byte_offset % extypesize == 1)) ) || /* * Dynamic offset can be odd for serialized instructions * or when horizontal offset is dynamic. * Probably we need the same for any dst with dynamic offsets. */ ( dst_elsize < extypesize && dst->getRegAccess() != Direct && !( byteDst && extypesize == 2 && exec_size == 1 ) ) || dstNotAlignedToExecType) { /* * 10.3 * For byte dst type: * 1. no 1 horstride * 2. no odd start subreg * There is only one excpetion - raw mov op * Raw means src operand has no attribute. * * Note: Actually all these cases are now controlled * by extypesize value. */ if (inst->isRawMov() && ( dst_byte_offset % extypesize == 0 || ( byteDst && dst_byte_offset % extypesize == 1 ) ) ) { return insertMOV; } if (canReplaceMovSrcType(builder, inst, extypesize)) { return false; } if (inst->opcode() == G4_mov) { bool intHFConversion = false; G4_Operand* src0 = inst->getSrc(0); if (isLowPrecisionFloatTy(dst->getType()) && IS_TYPE_INT(src0->getType())) { intHFConversion = true; } else if (isLowPrecisionFloatTy(src0->getType()) && IS_TYPE_INT(dst->getType())) { intHFConversion = true; } // we allow packed destination for F to HF. if (getGenxPlatform() >= GENX_CHV && !intHFConversion && inst->isMixedMode()) { return insertMOV; } } if( !VISA_WA_CHECK(builder.getPWaTable(), WaByteDstAlignRelaxedRule) ) { if( splitInstListForByteDst( i, bb, (uint16_t) extypesize ) ) { return true; } } inst->setDest(insertMovAfter(i, dst, dst->getType(), bb)); insertMOV = true; } return insertMOV; } /* * This function checks to see if the instruction's indirect operands * potentially require totally more than 8 distinct addr reg sub-registers, and * then determines which of the operands to spill into temporary GRFs so * as to limit total number of distinct sub-registers used by the instruction * to 8. This is a requirement imposed by the CM register allocator. */ bool HWConformity::fixIndirectOpnd( INST_LIST_ITER i, G4_BB *bb ) { G4_INST *inst = *i; G4_Operand *src0 = inst->getSrc(0), *src1 = inst->getSrc(1); G4_DstRegRegion *dst = inst->getDst(); bool null_dst = ( !dst || inst->hasNULLDst() ); bool null_src0 = !src0; bool null_src1 = !src1 || ( inst->isMath() && src1->isNullReg() ); const int addr_reg_max_count = 16; const int addr_reg_size = G4_Type_Table[Type_UW].byteSize; int src_uniq_count = 0; int src1_count = 0; int src0_count = 0; int dst_uniq_count = 0; int dst_count = 0; bool nospill_src1 = false; bool nospill_src0 = false; bool nospill_dst = false; bool spill_src1 = false; bool spill_src0 = false; bool spill_dst = false; G4_Declare *addr_dcl0 = NULL, *addr_dcl1 = NULL, *addr_dcl2 = NULL; if( !null_src0 && src0->isSrcRegRegion() && src0->getRegAccess() != Direct && src0->asSrcRegRegion()->getBase()->isRegVar() ){ addr_dcl0 = src0->asSrcRegRegion()->getBase()->asRegVar()->getDeclare(); while( addr_dcl0->getAliasDeclare() != NULL ){ addr_dcl0 = addr_dcl0->getAliasDeclare(); } // is the following precise? src0_count = addr_dcl0->getNumElems() * addr_dcl0->getNumRows() * addr_dcl0->getElemSize() / addr_reg_size; MUST_BE_TRUE( src0_count <= addr_reg_max_count, "More than 8 address subregisters required for one oerand." ); src_uniq_count += src0_count; } if( !null_src1 && src1->isSrcRegRegion() && src1->getRegAccess() != Direct && src1->asSrcRegRegion()->getBase()->isRegVar() ){ addr_dcl1 = src1->asSrcRegRegion()->getBase()->asRegVar()->getDeclare(); while( addr_dcl1->getAliasDeclare() != NULL ){ addr_dcl1 = addr_dcl1->getAliasDeclare(); } src1_count = addr_dcl1->getNumElems() * addr_dcl1->getNumRows() * addr_dcl1->getElemSize() / addr_reg_size; MUST_BE_TRUE( src1_count <= addr_reg_max_count, "More than 8 address subregisters required for one oerand." ); if (addr_dcl1 != addr_dcl0) { // should we use top level dcl here? src_uniq_count += src1_count; } else { nospill_src1 = true; nospill_src0 = true; } } if( !null_dst && dst->getRegAccess() != Direct && dst->getBase()->isRegVar() ) { addr_dcl2 = dst->getBase()->asRegVar()->getDeclare(); while( addr_dcl2->getAliasDeclare() != NULL ){ addr_dcl2 = addr_dcl2->getAliasDeclare(); } dst_count = addr_dcl2->getNumElems() * addr_dcl2->getNumRows() * addr_dcl2->getElemSize() / addr_reg_size; MUST_BE_TRUE( dst_count <= addr_reg_max_count, "More than 8 address subregisters required for one oerand." ); if (addr_dcl2 != addr_dcl0 && addr_dcl2 != addr_dcl1) { dst_uniq_count += dst_count; } else if( addr_dcl2 != addr_dcl0 ){ nospill_dst = true; nospill_src0 = true; }else{ nospill_dst = true; nospill_src1 = true; } } if (src_uniq_count > addr_reg_max_count) { if (src0_count > src1_count || nospill_src1) { MUST_BE_TRUE(nospill_src0 == false, "Address of source0 should be spilled." ); spill_src0 = true; src_uniq_count -= src0_count; } else { MUST_BE_TRUE(nospill_src1 == false, "Address of source1 should be spilled."); spill_src1 = true; src_uniq_count -= src1_count; } } if (src_uniq_count + dst_uniq_count > addr_reg_max_count) { MUST_BE_TRUE(nospill_dst == false, "Address of dst should be spilled." ); if (nospill_src1 && nospill_src0) { spill_dst = true; dst_uniq_count = 0; } else if (dst_uniq_count > src0_count && dst_uniq_count > src1_count) { spill_dst = true; dst_uniq_count = 0; } else if (spill_src0 ) { spill_src1 = true; src_uniq_count -= src1_count; } else if (spill_src1 ) { spill_src0 = true; src_uniq_count -= src0_count; } else if (src0_count > src1_count) { spill_src0 = true; src_uniq_count -= src0_count; } else { spill_src1 = true; src_uniq_count -= src1_count; } } MUST_BE_TRUE (src_uniq_count + dst_uniq_count <= addr_reg_max_count, "Remianed number of address registers should be no more than 8 after spill."); // Is this only for iselect? // What if a scalar with indirect addressing is used? if (spill_src0) { G4_Operand *new_src0 = insertMovBefore(i, 0, src0->getType(), bb); inst->setSrc( new_src0, 0 ); } if (spill_src1 && src1) { G4_Operand *new_src1 = insertMovBefore(i, 1, src1->getType(), bb); inst->setSrc( new_src1, 1 ); } if (spill_dst && dst) { G4_DstRegRegion *new_dst = insertMovAfter( i, dst, dst->getType(), bb ); inst->setDest( new_dst ); if( dst != new_dst && ( IS_FTYPE(dst->getType()) || IS_DFTYPE(dst->getType()) ) ) { inst->setSaturate( false ); } } return spill_dst; } // If an accumulator is a source operand, its register region must match that of the // destination register (which means GRF-aligned since we always GRF-align Acc) // also check for restrictions on explicit acc dst bool HWConformity::fixAcc(INST_LIST_ITER iter, G4_BB* bb) { G4_INST *inst = *iter; bool changed = false; auto dst = inst->getDst(); if ((dst != NULL && dst->isAccReg()) || inst->opcode() == G4_mach) { if (!builder.accDstforIndirectSrc()) { if (inst->getSrc(0)->isSrcRegRegion() && inst->getSrc(0)->asSrcRegRegion()->getRegAccess() == IndirGRF) { inst->setSrc(insertMovBefore(iter, 0, inst->getSrc(0)->getType(), bb), 0); changed = true; } } } bool useAcc = inst->hasImplicitAccSrc(); if (!useAcc) { for (int i = 0; i < inst->getNumSrc(); ++i) { G4_Operand* src = inst->getSrc(i); if (src && src->isAccReg()) { useAcc = true; break; } } } if (useAcc && dst && dst->getBase() && dst->getBase()->isRegVar()) { if (!builder.isOpndAligned(dst, GENX_GRF_REG_SIZ)) { inst->setDest(insertMovAfter(iter, dst, dst->getType(), bb, GRFALIGN)); changed = true; } } return changed; } /* * When operation execution size is 1, destination horizontal stride is set * according to rule 10.2: * * 10.1.2. If ExecSize is greater than 1, dst.HorzStride*sizeof(dst.Type) must * be equal to or greater than the size of the execution data type. * 10.2. If ExecSize is 1, dst.HorzStride must not be 0. Note that this is * relaxed from rule 10.1.2. Also note that this rule for destination * horizontal stride is different from that for source as stated * in rule #7. * * There are some instructions which work unpredictably if both ExecSize * and dst.HorzStride are 1. But they work fine if dst.HorzStride is set * according to rule 10.1.2. So we have to correct all such cases. * * This supposed to be the last operation before emitting final assembly code. */ void HWConformity::fixDstHstride( INST_LIST_ITER i, int extypesize ) { G4_INST *inst = *i; G4_DstRegRegion *dst = inst->getDst(); int dst_elsize = G4_Type_Table[dst->getType()].byteSize; if (dst) { unsigned short hs = dst->getHorzStride(); if( hs * dst_elsize < extypesize ) { dst->setHorzStride( (unsigned short) (extypesize/dst_elsize) ); } } } template<class T> bool isPreAssignedRegOffsetNonZero(T* region) { // T is non-NULL and either // G4_SrcRegRegion or G4_DstRegRegion bool ret = false; if ((region->isSrcRegRegion() || region->isDstRegRegion()) && region->getBase() && region->getBase()->isRegVar() && region->getBase()->asRegVar()->isPhyRegAssigned() && region->getBase()->asRegVar()->getPhyRegOff() != 0) { ret = true; } return ret; } void HWConformity::generateMacl(INST_LIST_ITER it, G4_BB* bb) { G4_INST* mulInst = *it; MUST_BE_TRUE(mulInst->opcode() == G4_mul, "expect mul instruction"); if (mulInst->getExecSize() > builder.getNativeExecSize()) { auto startIter = it; bool isFirstInst = startIter == bb->begin(); if (!isFirstInst) { --startIter; } evenlySplitInst(it, bb); if (!isFirstInst) { ++startIter; } // startIter now points to first mul created by split auto endIter = it; ++endIter; // endIter points to the first inst after the original mul for (auto iter = startIter; iter != endIter;) { auto nextIter = iter; ++nextIter; G4_INST* currInst = *iter; if (currInst->opcode() == G4_mul) { doGenerateMacl(iter, bb); } iter = nextIter; } } else { doGenerateMacl(it, bb); } } // convert vISA mul (8) dst src0 src1 into // mul (8) acc0.0<1>:d src0:d src1:w // mach (8) dst:d src0:d src1:d // void HWConformity::doGenerateMacl(INST_LIST_ITER it, G4_BB *bb) { G4_INST* mulInst = *it; MUST_BE_TRUE(mulInst->opcode() == G4_mul, "expect mul instruction"); assert(mulInst->getExecSize() <= builder.getNativeExecSize() && "expect single register inst"); G4_Operand* src0 = mulInst->getSrc(0); G4_Operand* src1 = mulInst->getSrc(1); MUST_BE_TRUE(IS_DTYPE(src0->getType()) && IS_DTYPE(src1->getType()), "both sources must have dword type"); if (src1->isSrcRegRegion()) { G4_SrcRegRegion* src1Region = src1->asSrcRegRegion(); if (src1Region->getModifier() != Mod_src_undef) { // need extra move for the modifier src1 = insertMovBefore(it, 1, src1->getType(), bb); mulInst->setSrc(src1, 1); } } // sat cannot be used at all in the macro sequence // this effectivly means sat is broken for mul D D D mulInst->setSaturate(false); G4_DstRegRegion* origDst = mulInst->getDst(); G4_Type accType = (IS_UNSIGNED_INT(src0->getType()) && IS_UNSIGNED_INT(src1->getType())) ? Type_UD : Type_D; G4_DstRegRegion *accDstOpnd = builder.createDstRegRegion(Direct, builder.phyregpool.getAcc0Reg(), 0, 0, 1, accType); mulInst->setDest(accDstOpnd); uint32_t origOptions = mulInst->getOption(); fixMulSrc1(it, bb); mulInst->setOptionOn(InstOpt_WriteEnable); G4_Predicate* predicate = mulInst->getPredicate(); if (predicate != nullptr) { // move pred to mach mulInst->setPredicate(nullptr); } if (mulInst->getCondMod() != nullptr) { // conditional modifier cannot be used // when the MUL source operand is of dword type. MUST_BE_TRUE(false, "Dw multiply does not support conditional modifiers"); mulInst->setCondMod(nullptr); } // create a mach inst G4_INST* machInst = builder.createInternalInst(predicate, G4_mach, nullptr, false, mulInst->getExecSize(), origDst, builder.duplicateOperand(src0), builder.duplicateOperand(src1), origOptions, mulInst->getLineNo(), mulInst->getCISAOff(), mulInst->getSrcFilename()); // maintain du chain as fixAccDst uses it later G4_SrcRegRegion *accSrcOpnd = builder.createSrcRegRegion(Mod_src_undef, Direct, builder.phyregpool.getAcc0Reg(), 0, 0, builder.getRegionStride1(), accType); machInst->setImplAccSrc(accSrcOpnd); mulInst->addDefUse(machInst, Opnd_implAccSrc); INST_LIST_ITER machIter = it; machIter = bb->insert(++machIter, machInst); if (!IS_DTYPE(origDst->getType()) || origDst->getHorzStride() != 1 || !builder.isOpndAligned(origDst, 32)) { // mach dst must be grf-aligned, packed D/UD as it is also used for the implicit acc source's region G4_DstRegRegion* tmpDst = insertMovAfter(machIter, origDst, accType, bb); machInst->setDest(tmpDst); } } // get rid of source modifiers on this inst[srcPos] bool HWConformity::checkSrcMod(INST_LIST_ITER it, G4_BB* bb, int srcPos) { bool changed = false; G4_INST* inst = *it; assert(srcPos < inst->getNumSrc() && "invalid srcPos"); auto src = inst->getSrc(srcPos); if (src->isSrcRegRegion()) { G4_SrcRegRegion* srcRegion = src->asSrcRegRegion(); if (srcRegion->getModifier() != Mod_src_undef) { G4_Type type = IS_DTYPE(src->getType()) ? src->getType() : Type_D; src = insertMovBefore(it, srcPos, type, bb); inst->setSrc(src, srcPos); changed = true; } } return changed; } // If both source operands of an MUL instruction are of dword integer type, // only the lower 16 bits of data elements in src0 are used. // The full precision multiplication results can be only produced together // with the mach and mov instructions. bool HWConformity::fixMULInst( INST_LIST_ITER &i, G4_BB *bb ) { bool insertedInst = false; G4_INST *inst = *i; G4_DstRegRegion *dst = inst->getDst(); uint8_t exec_size = inst->getExecSize(); bool srcExchanged = false; if (dst->isAccReg()) { return false; } uint32_t inst_opt = inst->getOption(); G4_Operand *src0 = inst->getSrc(0), *src1 = inst->getSrc(1); // MUL is commutative and only // allows src1 to be a constant. // If src1 is a constant and src1 // is not, they are swapped here. // If both are constants, they // will be fixed in checking HW conformity. // this is fixed in fixOpnd. if (src0->isImm() && !src1->isImm()) { inst->setSrc( src1, 0 ); inst->setSrc( src0, 1 ); srcExchanged = true; } if (!builder.supportSrcModforMul() && (IS_DTYPE(src0->getType()) || IS_DTYPE(src1->getType())) && ((getTypeSize(src0->getType()) < 4) || (getTypeSize(src1->getType()) < 4))) { checkSrcMod(i, bb, 0); checkSrcMod(i, bb, 1); } src0 = inst->getSrc(0); src1 = inst->getSrc(1); // Q dst needs 64-bit support regardless of src type bool isDMul = IS_QTYPE(dst->getType()) || (IS_DTYPE(src0->getType()) && IS_DTYPE(src1->getType())); if (!isDMul) { return false; } if (builder.hasMacl() && !IS_QTYPE(dst->getType()) && (builder.noDwDstForDwordMul() || inst->getExecSize() > 1)) { // use macl for D = D x D. We use macl when possible // except on scalar inst on platforms that support native DMul generateMacl(i, bb); return true; } bool doNativeMul = false; if (!builder.no64bitRegioning()) { // platform natively supports DW-DW multiply, no need to generate mul/mach/mov sequence doNativeMul = true; } else { if ((getGenxPlatform() == GENX_CHV || getGenxPlatform() == GENX_BXT)) { if (inst->getExecSize() == 1) { // scalar insts are a-ok return false; } // ok if source is scalar or qword-aligned doNativeMul = (getTypeSize(dst->getType()) * dst->getHorzStride() == 8); auto isQWordStride = [inst, this](G4_SrcRegRegion* src) { RegionDesc* region = src->getRegion(); if (!region->isScalar()) { uint16_t stride = 0; (void) region->isSingleNonUnitStride(inst->getExecSize(), stride); if (stride != 2) { return false; } // check that source is GRF-aligned to ensure that every element is qword-aligned return builder.isOpndAligned(src, 32); } return true; }; if (doNativeMul && src0->isSrcRegRegion()) { doNativeMul = isQWordStride(src0->asSrcRegRegion()); } if (doNativeMul && src1->isSrcRegRegion()) { doNativeMul = isQWordStride(src1->asSrcRegRegion()); } } } if (doNativeMul) { // promote source to D type if necessary if (IS_QTYPE(dst->getType())) { G4_Type newTy; G4_Operand* newOpnd; if (!IS_DTYPE(src0->getType())) { newTy = IS_SIGNED_INT(src0->getType()) ? Type_D : Type_UD; newOpnd = insertMovBefore(i, 0, newTy, bb); inst->setSrc(newOpnd, 0); insertedInst = true; } if (!IS_DTYPE(src1->getType())) { newTy = IS_SIGNED_INT(src1->getType()) ? Type_D : Type_UD; if (src1->isImm()) { newOpnd = builder.createImm(src1->asImm()->getImm(), newTy); } else { newOpnd = insertMovBefore(i, 1, newTy, bb); } inst->setSrc(newOpnd, 1); insertedInst = true; } } return insertedInst; } // both sources are dword, replace with mul/mach/mov sequence // At this point, src0 and src1 are both DW, so we simply make // acc's type (i.e. dst_type) be DW/UD G4_CondMod *condmod = builder.duplicateOperand(inst->getCondMod()); G4_Predicate *pred = builder.duplicateOperand(inst->getPredicate()); // check if the following inst is mulh and uses the same srcs as this mul. // if true, translate them into // mul acc src0 src1 // mach dst_mulh src0 src1 // mov mul_dst src0 src1 INST_LIST_ITER next_i = i; next_i++; G4_Type tmp_type = (IS_UNSIGNED_INT(src0->getType()) && IS_UNSIGNED_INT(src1->getType())) ? Type_UD : Type_D; bool isCompressed = isCompressedInst(inst); if (src1->isSrcRegRegion()) { G4_SrcRegRegion* src1Region = src1->asSrcRegRegion(); if (src1Region->getModifier() != Mod_src_undef) { // need extra move for the modifier src1 = insertMovBefore(i, 1, src1->getType(), bb); inst->setSrc(src1, 1); } } bool sat_mod = inst->getSaturate(); inst->setSaturate(false); // see if we can combine this mul with a mulh following it if (next_i != bb->end()) { G4_INST *next_inst = *next_i; if (next_inst->opcode() == G4_mulh && next_inst->getExecSize() == exec_size && inst->getPredicate() == next_inst->getPredicate() && ((srcExchanged && src0->getType() == next_inst->getSrc(1)->getType() && src0->compareOperand(next_inst->getSrc(1)) == Rel_eq && src1->getType() == next_inst->getSrc(0)->getType() && src1->compareOperand(next_inst->getSrc(0)) == Rel_eq) || (!srcExchanged && src0->getType() == next_inst->getSrc(0)->getType() && src0->compareOperand(next_inst->getSrc(0)) == Rel_eq && src1->getType() == next_inst->getSrc(1)->getType() && src1->compareOperand(next_inst->getSrc(1)) == Rel_eq))) { // change current mul inst G4_DstRegRegion *acc_dst_opnd = builder.createDstRegRegion( Direct, builder.phyregpool.getAcc0Reg(), 0, 0, 1, tmp_type); inst->setDest(acc_dst_opnd); fixMulSrc1(i, bb); inst->transferUse(next_inst, true); inst->addDefUse(next_inst, Opnd_implAccSrc); // change mulh inst next_inst->setOpcode(G4_mach); G4_DstRegRegion *next_dst = next_inst->getDst(); if (next_dst != NULL && (next_inst->getSaturate() || next_dst->getByteOffset() % GENX_GRF_REG_SIZ != 0 || (bb->isInSimdFlow() && next_inst->isWriteEnableInst() == false) || (next_dst && ((next_dst->getExecTypeSize() > G4_Type_Table[Type_D].byteSize) || isPreAssignedRegOffsetNonZero<G4_DstRegRegion>(next_dst))))) { // add a tmp mov G4_DstRegRegion *new_next_dst = insertMovAfter(next_i, next_dst, next_dst->getType(), bb); next_inst->setDest(new_next_dst); } // set implicit source/dst for MACH RegionDesc *rd = exec_size == 1 ? builder.getRegionScalar() : builder.getRegionStride1(); G4_SrcRegRegion *acc_src_opnd = builder.createSrcRegRegion(Mod_src_undef, Direct, builder.phyregpool.getAcc0Reg(), 0, 0, rd, tmp_type); next_inst->setImplAccSrc(acc_src_opnd); next_inst->setImplAccDst(builder.createDstRegRegion(*acc_dst_opnd)); // create mov inst G4_SrcRegRegion* movAccSrc = builder.createSrcRegRegion(Mod_src_undef, Direct, builder.phyregpool.getAcc0Reg(), 0, 0, rd, tmp_type); G4_INST* newMov = builder.createInternalInst(pred, G4_mov, condmod, false, exec_size, dst, movAccSrc, NULL, inst_opt, inst->getLineNo(), inst->getCISAOff(), inst->getSrcFilename()); INST_LIST_ITER iter = next_i; iter++; bb->insert(iter, newMov); next_inst->addDefUse(newMov, Opnd_src0); INST_LIST_ITER last_iter = iter; last_iter--; if (dst != NULL && (sat_mod || (dst && ((dst->getExecTypeSize() > G4_Type_Table[Type_D].byteSize) || (isPreAssignedRegOffsetNonZero<G4_DstRegRegion>(dst)))))) { // add a tmp mov iter--; G4_DstRegRegion *new_next_dst = insertMovAfter(iter, dst, dst->getType(), bb); newMov->setDest(new_next_dst); if (new_next_dst != dst && sat_mod) { MUST_BE_TRUE(iter != bb->end() && (*iter)->opcode() == G4_mov, "Next instruciton should be the MOV generated for consistent Dst and ACC source region."); (*iter)->setSaturate(false); } } next_inst->setOptionOn(InstOpt_AccWrCtrl); if (exec_size > builder.getNativeExecSize()) { splitDWMULInst(i, last_iter, bb); } return true; } } G4_DstRegRegion *acc_dst_opnd = builder.createDstRegRegion(Direct, builder.phyregpool.getAcc0Reg(), 0, 0, 1, tmp_type); inst->setDest(acc_dst_opnd); fixMulSrc1(i, bb); if (bb->isInSimdFlow()) { inst->setOptions((inst->getOption() & ~InstOpt_Masks) | InstOpt_WriteEnable); } if (pred != NULL) { // conditional modifier cannot be used // when the MUL source operand is of dword type. inst->setCondMod(NULL); } // Dst is either null, or a temp D if the original dst is Q/UQ G4_DstRegRegion *machDst = NULL; G4_Declare* high32BitDcl = NULL; if (IS_QTYPE(dst->getType())) { high32BitDcl = builder.createTempVar(exec_size, Type_D, Any); machDst = builder.Create_Dst_Opnd_From_Dcl(high32BitDcl, 1); } else { machDst = builder.createNullDst(Type_D); } // create a mach inst G4_INST* newInst = builder.createInternalInst( NULL, G4_mach, NULL, false, exec_size, machDst, builder.duplicateOperand(src0), builder.duplicateOperand(src1), inst_opt, inst->getLineNo(), inst->getCISAOff(), inst->getSrcFilename()); newInst->setOptionOn(InstOpt_AccWrCtrl); INST_LIST_ITER iter = i; iter++; bb->insert(iter, newInst); inst->setPredicate(NULL); inst->copyDef(newInst, Opnd_src0, Opnd_src0); inst->copyDef(newInst, Opnd_src1, Opnd_src1); inst->transferUse(newInst); inst->addDefUse(newInst, Opnd_implAccSrc); // create an implicit source for MACH RegionDesc *rd = NULL; unsigned short vs = 0, wd = exec_size, hs = 0; if (exec_size > 1){ if (isCompressed){ wd = wd / 2; } hs = 1; vs = wd; } rd = builder.createRegionDesc(vs, wd, hs); G4_SrcRegRegion *acc_src_opnd = builder.createSrcRegRegion(Mod_src_undef, Direct, builder.phyregpool.getAcc0Reg(), 0, 0, rd, tmp_type); newInst->setImplAccSrc(acc_src_opnd); // set an implicit dst for MACH newInst->setImplAccDst(builder.createDstRegRegion(*acc_dst_opnd)); insertedInst = true; if (IS_QTYPE(dst->getType())) { // we have to produce two additional moves to form the Q/UQ: // mul (8) acc0:d r2.0<8;8,1>:d r3.0<16;8,2>:uw // mach (8) r5.0<1>:d r2.0<8;8,1>:d r3.0<8;8,1>:d // mov (8) r6.0<1>:d acc0:d // Low 32 bits. // mov (8) dst.0<2>:d r6.0<1>:d // mov (8) dst.1<2>:d r5.0<1>:d // Note that we don't try to combine the moves because of the HW restriction that // "If an accumulator is an explicit source operand, its register region must match that of the destination register" G4_Declare* low32BitDcl = builder.createTempVar(exec_size, Type_D, Any); G4_INST* movInst = builder.createMov(exec_size, builder.Create_Dst_Opnd_From_Dcl(low32BitDcl, 1), builder.createSrcRegRegion(*acc_src_opnd), inst_opt, false); bb->insert(iter, movInst); G4_DstRegRegion* origDst = dst; bool needsExtraMov = origDst->getHorzStride() > 1 || condmod != NULL || sat_mod; G4_Declare* dstAlias = builder.createTempVar(exec_size * 2, Type_D, Any); if (!needsExtraMov) { uint32_t aliasOffset = origDst->getRegOff() * GENX_GRF_REG_SIZ + origDst->getSubRegOff() * 8; dstAlias->setAliasDeclare(origDst->getBase()->asRegVar()->getDeclare(), aliasOffset); } G4_INST* lowMove = builder.createInternalInst(pred, G4_mov, NULL, false, exec_size, builder.Create_Dst_Opnd_From_Dcl(dstAlias, 2), builder.Create_Src_Opnd_From_Dcl(low32BitDcl, builder.getRegionStride1()), NULL, inst_opt); bb->insert(iter, lowMove); MUST_BE_TRUE(high32BitDcl != NULL, "mach dst must not be null"); G4_INST* highMove = builder.createInternalInst(pred, G4_mov, NULL, false, exec_size, builder.createDstRegRegion(Direct, dstAlias->getRegVar(), 0, 1, 2, dstAlias->getElemType()), builder.Create_Src_Opnd_From_Dcl(high32BitDcl, builder.getRegionStride1()), NULL, inst_opt); bb->insert(iter, highMove); if (needsExtraMov) { // this will take care of non-packed dst/cond mod/saturate G4_Declare* dstAliasAsQ = builder.createTempVar(exec_size, Type_Q, Any); dstAliasAsQ->setAliasDeclare(dstAlias, 0); G4_INST* moveInst = builder.createInternalInst(NULL, G4_mov, condmod, sat_mod, exec_size, dst, builder.Create_Src_Opnd_From_Dcl(dstAliasAsQ, builder.getRegionStride1()), NULL, inst_opt); bb->insert(iter, moveInst); } return true; } INST_LIST_ITER last_iter; // create a mov inst if (sat_mod == false) { bool extra_mov = dst && dst->getExecTypeSize() > G4_Type_Table[Type_D].byteSize; extra_mov |= (isPreAssignedRegOffsetNonZero<G4_DstRegRegion>(dst)); G4_INST* movInst = builder.createInternalInst(pred, G4_mov, condmod, false, exec_size, dst, builder.createSrcRegRegion(*acc_src_opnd), NULL, inst_opt, inst->getLineNo(), inst->getCISAOff(), inst->getSrcFilename()); newInst->transferUse(movInst); newInst->addDefUse(movInst, Opnd_src0); bb->insert(iter, movInst); last_iter = iter; last_iter--; if (extra_mov) { // add a tmp mov iter--; G4_DstRegRegion *new_next_dst = insertMovAfter(iter, dst, dst->getType(), bb); movInst->setDest(new_next_dst); movInst->setPredicate(NULL); } } else { // create an extra mov inst G4_Declare *dcl = builder.createTempVar( exec_size, tmp_type, GRFALIGN); G4_DstRegRegion *tmp_dst_opnd = builder.createDstRegRegion( Direct, dcl->getRegVar(), 0, 0, 1, tmp_type); G4_INST* movInst = builder.createInternalInst(NULL, G4_mov, condmod, false, exec_size, tmp_dst_opnd, builder.createSrcRegRegion(*acc_src_opnd), NULL, InstOpt_NoOpt, inst->getLineNo(), inst->getCISAOff(), inst->getSrcFilename()); bb->insert(iter, movInst); last_iter = iter; last_iter--; G4_SrcRegRegion *tmp_src_opnd = builder.createSrcRegRegion(Mod_src_undef, Direct, dcl->getRegVar(), 0, 0, rd, tmp_type); G4_INST *newInst2 = builder.createInternalInst(pred, G4_mov, condmod, sat_mod, exec_size, dst, tmp_src_opnd, NULL, inst_opt, inst->getLineNo(), inst->getCISAOff(), inst->getSrcFilename()); newInst->transferUse(newInst2); newInst->addDefUse(movInst, Opnd_src0); movInst->addDefUse(newInst2, Opnd_src0); bb->insert(iter, newInst2); iter++; } if (exec_size > builder.getNativeExecSize()) { splitDWMULInst(i, last_iter, bb); } return insertedInst; } // Translate MULH into // MUL acc src0 src1 // MACH dst src0 src1 void HWConformity::fixMULHInst( INST_LIST_ITER &i, G4_BB *bb ) { G4_INST *inst = *i; INST_LIST_ITER iter = i; uint8_t exec_size = inst->getExecSize(); int inst_opt = inst->getOption(); G4_Operand *src0 = inst->getSrc(0), *src1 = inst->getSrc(1); if (src0->isImm() && !src1->isImm()) { inst->setSrc( src1, 0 ); inst->setSrc( src0, 1 ); src0 = inst->getSrc(0); src1 = inst->getSrc(1); } bool useMulQDD = false; if (exec_size <= builder.getNativeExecSize() && !builder.no64bitRegioning() && builder.supportFloatOr64bRegioning()) { useMulQDD = true; if (!IS_DTYPE(src0->getType()) || !IS_DTYPE(src1->getType())) { if (src1->isImm() && IS_DTYPE(src0->getType()) && (IS_WTYPE(src1->getType()) || IS_BTYPE(src1->getType()))) { // Ensure src1 has the same type size as src0. const G4_Imm *oldImm = src1->asImm(); G4_Imm *newImm = builder.createImm(oldImm->getInt(), src0->getType()); inst->setSrc(newImm, 1); } else { useMulQDD = false; } } } if (useMulQDD) { // use mul Q D D to get the upper 32-bit // note that we don't do this for CHV/BXT due to the 64-bit type restrictions inst->setOpcode(G4_mul); G4_DstRegRegion *dst = inst->getDst(); G4_Type dstType = dst->getType(); if (dstType == Type_UD) dstType = Type_UQ; else dstType = Type_Q; G4_Declare *dstDcl = dst->getBase()->asRegVar()->getDeclare(); G4_Declare *tmpDcl = builder.createTempVar( dstDcl->getNumElems(), dstType, Any, "TV"); tmpDcl->copyAlign(dstDcl); G4_DstRegRegion* tmpDst = builder.Create_Dst_Opnd_From_Dcl(tmpDcl, 1); inst->setDest(tmpDst); //need move to cast back to D/UD type G4_SrcRegRegion *tmpSrc = builder.createSrcRegRegion( Mod_src_undef, Direct, tmpDcl->getRegVar(), 0, 1, exec_size > 1 ? builder.getRegionStride2() : builder.getRegionScalar(), dst->getType()); ++iter; G4_INST *tmpMov = builder.createInternalInst( builder.duplicateOperand(inst->getPredicate()), G4_mov, NULL, false, exec_size, dst, tmpSrc, NULL, NULL, inst->getOption(), inst->getLineNo(), inst->getCISAOff(), inst->getSrcFilename()); bb->insert(iter, tmpMov); //it will decrement back to mov i = iter; /* Need to remove dst from uses list of mulh, and add them to movInst useList add movInst to uselist of mulh. Add mulh to def instruction list of movInst */ inst->transferUse(tmpMov); inst->addDefUse(tmpMov, Opnd_src0); return; } if (!builder.supportSrcModforMul() && (IS_DTYPE(src0->getType()) || IS_DTYPE(src1->getType())) && ((getTypeSize(src0->getType()) < 4) || (getTypeSize(src1->getType()) < 4))) { checkSrcMod(i, bb, 0); src0 = inst->getSrc(0); } if (src1->isSrcRegRegion() && src1->asSrcRegRegion()->getModifier() != Mod_src_undef) { // src1 does not support modifiers checkSrcMod(i, bb, 1); src1 = inst->getSrc(1); } G4_Type tmp_type = (IS_UNSIGNED_INT(src0->getType()) && IS_UNSIGNED_INT(src1->getType())) ? Type_UD : Type_D; assert(IS_DTYPE(src0->getType()) && "src0 must be DW type"); G4_DstRegRegion* acc_dst_opnd = builder.createDstRegRegion( Direct, builder.phyregpool.getAcc0Reg(), 0, 0, 1, tmp_type); G4_INST* newMul = builder.createInternalInst(nullptr, G4_mul, NULL, false, exec_size, acc_dst_opnd, builder.duplicateOperand(src0), builder.duplicateOperand(src1), inst_opt, inst->getLineNo(), inst->getCISAOff(), inst->getSrcFilename()); bb->insert(iter, newMul); inst->copyDefsTo(newMul, false); newMul->addDefUse(inst, Opnd_implAccSrc); iter = i; iter--; fixMulSrc1(iter, bb); if (bb->isInSimdFlow()) { newMul->setOptions( ( inst_opt & ~InstOpt_Masks ) | InstOpt_WriteEnable ); } inst->setOpcode( G4_mach ); if (src1->isImm() && src0->getType() != src1->getType()) { G4_Imm *oldImm = src1->asImm(); // Ensure src1 has the same type as src0. G4_Imm *newImm = builder.createImm(oldImm->getInt(), src0->getType()); inst->setSrc(newImm, 1); } //set implicit src/dst for mach RegionDesc *rd = exec_size > 1 ? builder.getRegionStride1() : builder.getRegionScalar(); G4_SrcRegRegion *acc_src_opnd = builder.createSrcRegRegion(Mod_src_undef, Direct, builder.phyregpool.getAcc0Reg(), 0, 0, rd, tmp_type); inst->setImplAccSrc( acc_src_opnd ); inst->setImplAccDst( builder.createDstRegRegion( *acc_dst_opnd ) ); INST_LIST_ITER end_iter = i; // check if the ACC source is aligned to mach dst G4_DstRegRegion *dst = inst->getDst(); if ((inst->getSaturate()) || (dst && ((dst->getExecTypeSize() > G4_Type_Table[Type_D].byteSize) || (isPreAssignedRegOffsetNonZero<G4_DstRegRegion>(dst))))) { // add a tmp mov inst->setDest( insertMovAfter( i, dst, dst->getType(), bb ) ); end_iter++; } inst->setOptionOn(InstOpt_AccWrCtrl); if (exec_size > builder.getNativeExecSize()) { auto start_iter = std::prev(i); splitDWMULInst( start_iter, end_iter, bb ); i = end_iter; } } // // insert move instructions to copy numDwords dwords from src to dst at the specified location // a NoMask UD move is used. // dst and src must be dword-aligned. // srcOffset and dstOffset are in bytes // numDwords must be one of {1,2,4,8,16} // ToDo: may want to generalize this into a copyBytes function that selects the appropriate move type // based on dst and src type // void HWConformity::copyDwords(G4_Declare* dst, int dstOffset, G4_Declare* src, int srcOffset, int numDwords, G4_BB* bb, INST_LIST_ITER iter) { MUST_BE_TRUE(numDwords == 1 || numDwords == 2 || numDwords == 4 || numDwords == 8 || numDwords == 16, "invalid number of dwords to copy"); G4_Declare* newDst = dst; if (dst->getElemType() != Type_UD) { // create an alias with type UD newDst = builder.createTempVar(numDwords, Type_UD, Any); newDst->setAliasDeclare(dst, 0); } G4_Declare* newSrc = src; if (src->getElemType() != Type_UD) { // create an alias with type UD newSrc = builder.createTempVar(numDwords, Type_UD, Any); newSrc->setAliasDeclare(src, 0); } G4_SrcRegRegion* srcOpnd = builder.createSrcRegRegion(Mod_src_undef, Direct, newSrc->getRegVar(), srcOffset / GENX_GRF_REG_SIZ, (srcOffset % GENX_GRF_REG_SIZ) / G4_Type_Table[Type_UD].byteSize, builder.getRegionStride1(), Type_UD); G4_DstRegRegion* dstOpnd = builder.createDstRegRegion(Direct, newDst->getRegVar(), dstOffset / GENX_GRF_REG_SIZ, (dstOffset % GENX_GRF_REG_SIZ) / G4_Type_Table[Type_UD].byteSize, 1, Type_UD); G4_INST* movInst = builder.createMov((uint8_t) numDwords, dstOpnd, srcOpnd, InstOpt_WriteEnable, false); INST_LIST_ITER movPos = bb->insert(iter, movInst); if (numDwords == 16 && ((dstOffset % GENX_GRF_REG_SIZ) != 0 || (srcOffset % GENX_GRF_REG_SIZ) != 0)) { // move crosses 2 GRF boundary, needs splitting evenlySplitInst(movPos, bb); } } // like the above, but source is an indirect 64-bit source and dst offset is always 0 // If source is Indirect 1x1, we generate // mov (esize*2) tmp<1>:ud r[A0]<1;1,0>:ud // ... tmpSrc<region>:q // If source is VxH indirect, we have to generate instead // mov (esize*2) tmp<1>:ud r[A0]<2,1>:ud // ... tmpSrc<1;1,0>:q // as we can't have the indirect region on the 64-bit type operand // A0 is not changed otherwise void HWConformity::copyDwordsIndirect(G4_Declare* dst, G4_SrcRegRegion* src, int numDwords, G4_BB* bb, INST_LIST_ITER iter) { MUST_BE_TRUE(G4_Type_Table[dst->getElemType()].byteSize >= 4 && G4_Type_Table[src->getType()].byteSize >= 4, "dst and src must have dword or qword type"); MUST_BE_TRUE(src->getRegAccess() == IndirGRF, "source must be indirect GRF"); G4_Declare* newDst = dst; if (dst->getElemType() != Type_UD) { // create an alias with type UD newDst = builder.createTempVar(numDwords, Type_UD, Any); newDst->setAliasDeclare(dst, 0); } G4_SrcRegRegion* newSrc = builder.duplicateOperand(src); MUST_BE_TRUE(G4_Type_Table[newSrc->getType()].byteSize == 8, "only support 64-bit type source so far"); newSrc->setType(Type_UD); newSrc->setModifier(Mod_src_undef); if (newSrc->getRegion()->isRegionWH()) { MUST_BE_TRUE(newSrc->getRegion()->width == 1, "only handle <1,0> region for now"); newSrc->setRegion(builder.createRegionDesc(UNDEFINED_SHORT, 2, 1)); } else { newSrc->setRegion(builder.getRegionStride1()); } G4_DstRegRegion* dstOpnd = builder.createDstRegRegion(Direct, newDst->getRegVar(), 0, 0, 1, Type_UD); G4_INST* movInst = builder.createMov((uint8_t) numDwords, dstOpnd, newSrc, InstOpt_WriteEnable, false); bb->insert(iter, movInst); } // copy numRegs GRFs from src[srcOffset] to dst[dstOffset] // dst[dstOffset] and src[srcOffset] are both GRF-aligned void HWConformity::copyRegs(G4_Declare* dst, int dstOffset, G4_Declare* src, int srcOffset, int numRegs, G4_BB* bb, INST_LIST_ITER iter) { int numByteCopied = 0; for (; numRegs >= 2; numRegs -= 2, numByteCopied += 64) { copyDwords(dst, dstOffset + numByteCopied, src, srcOffset + numByteCopied, 16, bb, iter); } if (numRegs != 0) { copyDwords(dst, dstOffset + numByteCopied, src, srcOffset + numByteCopied, 8, bb, iter); } } void HWConformity::fix64bInst( INST_LIST_ITER iter, G4_BB* bb ) { // HW restrictions: // [DevCHV, DevBXT]: When source or destination datatype is 64b, indirect addressing must not be used. // the region rules are: // Source and Destination horizontal stride must be aligned to the execution datatype. // Example: // mov (4) r10.0:df r11.0<16;8,2>:f // Source stride must be 2 since datatype is smaller // move (4) r10.0<2>:f r11.0<4;4,1>:df // Destination stride must be 2 since datatype is smaller. // as this would require splitting in some cases // Regioning must ensure Src.Vstride = Src.Width * Src.Hstride // Source and Destination offset must be the same, except the case of scalar source // [DevCHV, DevBXT]: When source or destination datatype is 64b, indirect addressing must not be used. // [DevCHV, DevBXT]: ARF registers must never be used with 64b datatype. if (!builder.no64bitRegioning()) { return; } G4_INST* inst = *iter; bool uses64BitType = false; bool isDWMultiply = false; uint8_t execSize = inst->getExecSize(); if (inst->mayExceedTwoGRF()) { return; } if (inst->getDst() != NULL && G4_Type_Table[inst->getDst()->getType()].byteSize == 8) { uses64BitType = true; } for (int i = 0, size = G4_Inst_Table[inst->opcode()].n_srcs; !uses64BitType && i < size; i++) { G4_Operand* src = inst->getSrc(i); if (src && G4_Type_Table[src->getType()].byteSize == 8) { uses64BitType = true; } } if (inst->opcode() == G4_mul && IS_DTYPE(inst->getSrc(0)->getType()) && IS_DTYPE(inst->getSrc(1)->getType())) { //WA: dw*dw multiply is considered to use 64bit data type since the result is 64-bit uses64BitType = true; isDWMultiply = true; } if (uses64BitType) { if (builder.no64bitType() && inst->opcode() == G4_mov) { // while input should not have any ALU inst with 64b type, we may still end up // with 64b moves generated when preparing send payload (e.g., 64b atomics, // A64 messages). We fix such moves here by breaking them into 2 32b moves // For now only handle copy moves. auto dst = inst->getDst(); auto src0 = inst->getSrc(0); assert(getTypeSize(dst->getType()) == 8 && getTypeSize(src0->getType()) == 8 && "must be copy moves"); assert(src0->isSrcRegRegion() && (src0->asSrcRegRegion()->isScalar() || src0->asSrcRegRegion()->getRegion()->isContiguous(inst->getExecSize())) && "expect src0 to be scalar or contiguous"); auto src0RR = src0->asSrcRegRegion(); assert(inst->isRawMov() && dst->getHorzStride() == 1 && "expect only copy moves"); // 1st half auto newDst = builder.createDstRegRegion(Direct, dst->getBase(), dst->getRegOff(), dst->getSubRegOff() * 2, 2, Type_UD); auto newSrc = builder.createSrcRegRegion(Mod_src_undef, Direct, src0RR->getBase(), src0RR->getRegOff(), src0RR->getSubRegOff() * 2, src0RR->isScalar() ? builder.getRegionScalar() : builder.getRegionStride2(), Type_UD); auto newInst = builder.createMov(inst->getExecSize(), newDst, newSrc, inst->getOption(), false); bb->insert(iter, newInst); // second half newDst = builder.createDstRegRegion(Direct, dst->getBase(), dst->getRegOff(), dst->getSubRegOff() * 2 + 1, 2, Type_UD); newSrc = builder.createSrcRegRegion(Mod_src_undef, Direct, src0RR->getBase(), src0RR->getRegOff(), src0RR->getSubRegOff() * 2 + 1, src0RR->isScalar() ? builder.getRegionScalar() : builder.getRegionStride2(), Type_UD); newInst = builder.createMov(inst->getExecSize(), newDst, newSrc, inst->getOption(), false); *iter = newInst; return; } int numSrc = G4_Inst_Table[inst->opcode()].n_srcs; // handle indirect sources first for (int i = 0; i < numSrc; ++i) { G4_Operand* src = inst->getSrc(i); if (src != nullptr && src->isSrcRegRegion() && src->asSrcRegRegion()->getRegAccess() == IndirGRF) { G4_SrcRegRegion* srcAsRegion = src->asSrcRegRegion(); RegionDesc* region = srcAsRegion->getRegion(); int byteSize = G4_Type_Table[srcAsRegion->getType()].byteSize; if (byteSize == 8) { // right bound is not available for indirect operands // FIXME: this code should be moved to getRightBound() int rightBound = 0; // we must change move type to UD if (region->isScalar()) { rightBound = byteSize; } else if (region->isRegionWH()) { rightBound = inst->getExecSize() * byteSize; } else { int num_rows = inst->getExecSize() / region->width; rightBound = (num_rows - 1) * region->vertStride * byteSize + region->horzStride * (region->width - 1) * byteSize + byteSize; } int numDwords = rightBound / G4_Type_Table[Type_UD].byteSize; numDwords = Round_Up_Pow2(numDwords); G4_Declare* tmpSrc = builder.createTempVar(numDwords / 2, src->getType(), GRFALIGN); // new source's region varies depending on whether it's VxH or 1x1 RegionDesc* newRegion = region->isRegionWH() ? builder.getRegionStride1() : region; copyDwordsIndirect(tmpSrc, srcAsRegion, numDwords, bb, iter); G4_SrcRegRegion* tmpSrcOpnd = builder.createSrcRegRegion(srcAsRegion->getModifier(), Direct, tmpSrc->getRegVar(), 0, 0, newRegion, tmpSrc->getElemType()); inst->setSrc(tmpSrcOpnd, i); } else { // use the good ol' insertMovBefore G4_Operand* tmpSrc = insertMovBefore(iter, i, src->getType(), bb); G4_Declare* tmpSrcDcl = tmpSrc->getTopDcl(); tmpSrcDcl->setSubRegAlign(GRFALIGN); inst->setSrc(tmpSrc, i); } } } // now handle direct sources with bad region/alignment bool hasSameOffset = hasSameSubregOffset(inst); for (int i = 0; i < numSrc; i++) { G4_Operand* src = inst->getSrc(i); if (src != NULL && src->isSrcRegRegion()) { G4_SrcRegRegion* srcAsRegion = src->asSrcRegRegion(); RegionDesc* region = srcAsRegion->getRegion(); int byteSize = G4_Type_Table[srcAsRegion->getType()].byteSize; if (!isDWMultiply && !region->isScalar() && (byteSize != 8 && (byteSize * region->horzStride) < 8)) { // source is not 8 byte aligned // this can happen e.g. for // mov (8) r1.0<1>:df (mod)r3<8;8,1>:f // which we'd need to change to // mov (8) r10.0<2>:f (mod)r3.0<8;8,1>:f // mov (8) r1.0<1>:df r10.0<8;4,2>:f // to satisfy rule 1 uint8_t exSize = inst->getExecSize(); uint16_t multFactor = (uint16_t)(8 / byteSize); G4_Type tmpType = srcAsRegion->getType(); if (multFactor == 8) { // byte type needs special handling since we can't have stride 8 tmpType = (tmpType == Type_B) ? Type_W : Type_UW; multFactor = 4; } MUST_BE_TRUE(multFactor != 8, "does not support 64b operation with byte source"); G4_Declare* tmp = builder.createTempVar(exSize * multFactor, tmpType, GRFALIGN); G4_DstRegRegion* tmpDst = builder.Create_Dst_Opnd_From_Dcl(tmp, multFactor); G4_INST* movInst = builder.createMov(inst->getExecSize(), tmpDst, src, inst->getOption(), false); bb->insert(iter, movInst); uint16_t width = exSize; if (width * 8 > GENX_GRF_REG_SIZ) { // can't have width cross GRF width = 4; } G4_SrcRegRegion* newSrc = builder.Create_Src_Opnd_From_Dcl(tmp, builder.createRegionDesc((uint16_t)multFactor * width, width, multFactor)); inst->setSrc(newSrc, i); } else if (region->isScalar()) { #if 0 // scalar region still must be aligned to qword, though it can be any qword if (byteSize < 8 && !builder.isOpndAligned(srcAsRegion, 8)) { G4_Operand* tmpSrc = insertCopyBefore(iter, i, Four_Word, bb); inst->setSrc(tmpSrc, i); } #endif } else if (!hasSameOffset) { // we need a temp src that is GRF-aligned if (byteSize == 8) { // the same src/dst offset restriction applies to move as well, so we have to generate // a packed move with UD type to work around the restriction // e.g., for // add (2) ... r1.1<4;2,2>:q // we turn it into // mov (8) r10.0<1>:ud r1.2<1;1,0>:ud {NoMask} // add (2) ... r10.0<4;2,2>:q int numDwords = (src->getRightBound() - src->getLeftBound() + 1) / G4_Type_Table[Type_UD].byteSize; numDwords = Round_Up_Pow2(numDwords); G4_Declare* tmpSrc = builder.createTempVar(numDwords / 2, src->getType(), GRFALIGN); copyDwords(tmpSrc, 0, src->getTopDcl(), src->getLeftBound(), numDwords, bb, iter); G4_SrcRegRegion* tmpSrcOpnd = builder.createSrcRegRegion(srcAsRegion->getModifier(), Direct, tmpSrc->getRegVar(), 0, 0, srcAsRegion->getRegion(), tmpSrc->getElemType()); inst->setSrc(tmpSrcOpnd, i); } else { // use the good ol' insertMovBefore G4_Operand* tmpSrc = insertMovBefore(iter, i, src->getType(), bb); G4_Declare* tmpSrcDcl = tmpSrc->getTopDcl(); tmpSrcDcl->setSubRegAlign(GRFALIGN); inst->setSrc(tmpSrc, i); } } } } for (int i = 0; i < numSrc; i++) { // rewrite <1;1,0> to <2;2,1> since HW does not like the former G4_Operand* src = inst->getSrc(i); if (src != nullptr && src->isSrcRegRegion()) { G4_SrcRegRegion* srcAsRegion = src->asSrcRegRegion(); RegionDesc* region = srcAsRegion->getRegion(); if (!region->isRegionWH() && region->vertStride != region->horzStride * region->width) { // see if we can fix the region to satisfy VS = W * HS if (region->width == inst->getExecSize()) { // vs is a don't care, change to <w*hs, w, hz> srcAsRegion->setRegion(builder.createRegionDesc(region->width * region->horzStride, region->width, region->horzStride)); } else if (region->width == 1) { // hs is a don't care, change it to <esize*vs, esize, vs> MUST_BE_TRUE(region->vertStride <= 4, "illegal vertical stride"); uint16_t wd = inst->getExecSize(); uint16_t hs = region->vertStride; if (src->crossGRF()) { // Make sure the new hs does not cross GRF uint32_t nbytesIn1stGRF = GENX_GRF_REG_SIZ - (src->getLeftBound() % GENX_GRF_REG_SIZ); uint32_t eltBytes = G4_Type_Table[srcAsRegion->getType()].byteSize; uint32_t neltsIn1stGRF = nbytesIn1stGRF / eltBytes; MUST_BE_TRUE((nbytesIn1stGRF % eltBytes) == 0, "Bad region with element crossing GRF"); MUST_BE_TRUE((neltsIn1stGRF % hs) == 0, "hs cannot cross GRF"); wd = neltsIn1stGRF / hs; // Get the largest powOfTwo that can divide wd wd = wd & (-wd); //MUST_BE_TRUE( wd > 1, "Cannot select non-1 width w/o crossing GRF"); } srcAsRegion->setRegion(builder.createRegionDesc(wd * hs, wd, hs)); } else { // FIXME: Both VS and HS are used by the region, so we have to either split inst or insert multiple moves to pack the source // both are painful, so we assert for now and fix later if we encounter such a case MUST_BE_TRUE(false, "Unhandled bad 64b region on CHV/BXT"); } } } } G4_DstRegRegion* dst = inst->getDst(); if (dst != NULL && !dst->isNullReg()) { bool needsTmpDst = dst->getRegAccess() != Direct || (execSize > 1 && !hasSameOffset) || dst->isAreg(); if (needsTmpDst) { // we need to have a temp dst that is direct and GRF-aligned if (dst->getRegAccess() == Direct && G4_Type_Table[dst->getType()].byteSize == 8) { // the same src/dst offset restriction applies to move as well, so we have to generate // a move with UD type to work around the restriction // e.g., for // add (2) r1.2<1>:q ... // we generate // add (2) r3.0<1>:q ... // mov (4) r1.4<1>:ud r3.0<1;1,0>:ud {NoMask} // If dst is not contiguous, we additionally add a move to pre-load the old values: // add (2) r1.2<2>:q ... // becomes // mov (8) r3.0<1>:ud r1.4<1;1,0>:ud {NoMask} // add (2) r3.0<2>:q ... // mov (8) r1.4<1>:ud r3.0<1;1,0>:ud {NoMask} int numDwords = (dst->getRightBound() - dst->getLeftBound() + 1) / G4_Type_Table[Type_UD].byteSize; numDwords = Round_Up_Pow2(numDwords); G4_Declare* tmpDst = builder.createTempVar(numDwords / 2, dst->getType(), GRFALIGN); if (numDwords > execSize * 2) { // dst is not packed, need a move to pre-load the dst value into tmp copyDwords(tmpDst, 0, dst->getTopDcl(), dst->getLeftBound(), numDwords, bb, iter); } INST_LIST_ITER next = iter; ++next; copyDwords(dst->getTopDcl(), dst->getLeftBound(), tmpDst, 0, numDwords, bb, next); inst->setDest(builder.Create_Dst_Opnd_From_Dcl(tmpDst, dst->getHorzStride())); } else { // use the good ol' insertMoveAfter G4_DstRegRegion* tmpDst = insertMovAfter(iter, dst, dst->getType(), bb); G4_Declare* tmpDstDcl = tmpDst->getTopDcl(); tmpDstDcl->setSubRegAlign(GRFALIGN); inst->setDest(tmpDst); if (G4_Type_Table[dst->getType()].byteSize == 8) { // tmpDst is indirect and thus still does not conform // we rewrite // mov (e) r[a0.0]<1>:q src<1;1,0>:q // into // mov (e*2) r[a0.0]<1>:ud src<1;1,0>:ud {NoMask} ++iter; G4_INST* movInst = *iter; MUST_BE_TRUE(movInst->opcode() == G4_mov && movInst->getDst() == dst && movInst->getSrc(0)->isSrcRegRegion(), "unexpected instruction created by insertMovAfter"); MUST_BE_TRUE(dst->getHorzStride() == 1, "only stride 1 is supported for now"); dst->setType(Type_UD); G4_SrcRegRegion* src = movInst->getSrc(0)->asSrcRegRegion(); G4_Declare* tmpAsUD = builder.createTempVar(tmpDstDcl->getNumElems() * 2, Type_UD, Any); tmpAsUD->setAliasDeclare(tmpDstDcl, 0); RegionDesc* newRegion = src->getRegion()->isScalar() ? builder.createRegionDesc(0, 2, 1) : builder.getRegionStride1(); G4_SrcRegRegion* srcAsUD = builder.createSrcRegRegion(src->getModifier(), src->getRegAccess(), tmpAsUD->getRegVar(), src->getRegOff(), src->getSubRegOff() * 2, newRegion, tmpAsUD->getElemType()); movInst->setSrc(srcAsUD, 0); movInst->setExecSize(inst->getExecSize() * 2); // NoMask is set on the mov instruction, but if we fall outside of the new execution size, // it won't be executed fully // e.g., we have to change // (W) mov (16|M24) r[a0.0,64]<1>:ud r67.0<8;8,1>:ud // into // (W) mov (16|M0) r[a0.0,64]<1>:ud r67.0<8;8,1>:ud movInst->setMaskOption(InstOpt_M0); // mov saturate/pred to the original inst movInst->setOptionOn(InstOpt_WriteEnable); if (movInst->getSaturate()) { movInst->setSaturate(false); inst->setSaturate(true); } G4_Predicate* pred = movInst->getPredicate(); if (pred) { MUST_BE_TRUE(inst->getPredicate() == nullptr, "both inst and movInst have predicates"); movInst->setPredicate(nullptr); inst->setPredicate(pred); } } } } } } } //------------------------------------------------------------------------------ // // For BDW, 32 bits integer multiply is implemented as the following macro // // mul (8) acc0:d r2.0<8;8,1>d r3.0<16;8,2>:uw // mach (8) rTemp<1>:d r2.0<8;8,1>d r3.0<8;8,1>:d // mov (8) r5.0<1>:d rTemp:d // hi-32bits // mov (8) r6.0<1>:d acc0:d // lo-32bits // // Note that this only changes the mul instruction's src1, mach and mov is generated elsewhere //------------------------------------------------------------------------------ void HWConformity::fixMulSrc1( INST_LIST_ITER i, G4_BB* bb ) { G4_INST *inst = *i; G4_Operand *src1 = inst->getSrc(1); if (!IS_DTYPE(src1->getType())) { // this could happen if dst is Q return; } if (src1->isImm()) { uint64_t truncVal = src1->asImm()->getImm() & 0xFFFF; G4_Imm *new_src1 = builder.createImm(truncVal, Type_UW); inst->setSrc(new_src1, 1); } else { assert(src1->isSrcRegRegion() && "region expected"); G4_SrcRegRegion *srcRegion = src1->asSrcRegRegion(); RegionDesc *rd = srcRegion->getRegion(); if (rd->horzStride >= 4) { G4_Operand* new_src1 = insertMovBefore(i, 1, Type_UW, bb); inst->setSrc(new_src1, 1); } else { // create a new opnd with type UW unsigned short scale = G4_Type_Table[Type_D].byteSize / G4_Type_Table[Type_UW].byteSize; unsigned short newHS = rd->horzStride * scale; unsigned short newVS = rd->vertStride * scale; RegionDesc *new_rd = builder.createRegionDesc(newVS, rd->width, newHS); short subRegOff = srcRegion->getSubRegOff(); if (srcRegion->getRegAccess() == Direct) { subRegOff *= scale; } auto new_src1 = builder.createSrcRegRegion( srcRegion->getModifier(), srcRegion->getRegAccess(), srcRegion->getBase(), srcRegion->getRegOff(), subRegOff, new_rd, Type_UW); inst->setSrc(new_src1, 1); if (srcRegion->getRegAccess() != Direct) { new_src1->setImmAddrOff(srcRegion->getAddrImm()); } } } G4_Operand *src0 = inst->getSrc(0); if (!builder.supportSrcModforMul() && IS_DTYPE(src0->getType())) { checkSrcMod(i, bb, 0); checkSrcMod(i, bb, 1); } } /* * only acc0 may be used in DWord operations, so we have to break a * SIMD16 DWord multiply into two mul-mach-mov sequences. * * Input: * (f0) mul (16) dst:d src0:d src1:d * * Output: * mul (8) acc0:d src0:d src1:d * mach (8) null:d src0:d src1:d * (f0) mov (8) dst:d acc0:d * mul (8) acc0:d src0+1:d src1+1:d * mach (8) null:d src0+1:d src1+1:d * (f1) mov (8) dst+1:d acc0:d * */ void HWConformity::splitDWMULInst( INST_LIST_ITER &start, INST_LIST_ITER &end, G4_BB *bb ) { // split simd16 inst into SIMD8 ones, since D is not supported for acc1 INST_LIST_ITER iter = start, last_iter = end; //iter--; last_iter++; INST_LIST_ITER curr_iter; while( iter != end ) { curr_iter = iter; evenlySplitInst( curr_iter, bb ); // curr_iter points to the second half after instruction splitting G4_INST *expand_sec_half_op = *curr_iter; iter++; bb->insert( last_iter, expand_sec_half_op ); if( curr_iter == start ) { start--; } bb->erase( curr_iter ); } // handle the last inst if( iter == end ) { evenlySplitInst( iter, bb ); G4_INST *expand_sec_half_op = *iter; bb->insert( last_iter, expand_sec_half_op ); end--; bb->erase( iter ); } } static bool isGoodMadType(G4_Type type) { switch (type) { case Type_F: case Type_HF: case Type_DF: return true; default: return false; } } bool HWConformity::isGoodAlign1TernaryDst(G4_INST* inst) const { // Align1 MAD requirements: // -- dst must be direct GRF/acc with horizontal stride 1 or 2 G4_Type execType = inst->getExecType(); G4_DstRegRegion* dst = inst->getDst(); MUST_BE_TRUE(!IS_QTYPE(dst->getType()) && !IS_BTYPE(dst->getType()), "3Src inst don't support Q and B dst types"); if (!builder.hasMixMode() && isLowPrecisionFloatTy(dst->getType()) && !isLowPrecisionFloatTy(execType)) { return false; } int alignInBytes = 8; // if src2 is not a scalar, then align it to 32 bytes. if (builder.noSrc2Regioning()) { unsigned src2Pos = inst->opcode() == G4_pseudo_mad ? 0 : 2; auto src2 = inst->getSrc(src2Pos); if (src2->isSrcRegRegion() && !src2->asSrcRegRegion()->isScalar()) { alignInBytes = 32; } } if (!builder.isOpndAligned(dst, alignInBytes)) { // dst must be 8 byte aligned due to encoding issues return false; } uint32_t effectiveStride = dst->getHorzStride(); if (G4_Type_Table[dst->getType()].byteSize < G4_Type_Table[execType].byteSize) { if (IS_TYPE_INT(dst->getType())) { effectiveStride *= G4_Type_Table[execType].byteSize / G4_Type_Table[dst->getType()].byteSize; } else { // we have mixed HF and F inst // dst can be packed HF, but then it must be oword aligned // this should be checked later for mixed mode inst } } return dst->getRegAccess() == Direct && effectiveStride <= 2; } // // check for legal align1 ternary inst sources // bool HWConformity::isGoodAlign1TernarySrc(G4_INST* inst, int srcPos, bool canBeImm) { MUST_BE_TRUE(srcPos >= 0 && srcPos < 3, "illegal source pos"); uint8_t execSize = inst->getExecSize(); G4_Operand* src = inst->getSrc(srcPos); // for pseudo_mad we have to swap src0 and src2 bool isSrc2 = inst->opcode() == G4_pseudo_mad ? srcPos == 0 : srcPos == 2; if (!builder.hasMixMode()) { G4_Type execType = inst->getExecType(); if (isLowPrecisionFloatTy(src->getType()) && !isLowPrecisionFloatTy(execType)) { return false; } } if (IS_QTYPE(src->getType())) { return false; } if (inst->opcode() == G4_pseudo_mad && isSrc2) { if (IS_DTYPE(src->getType())) { return false; } if (builder.noSrc2Regioning() && IS_BTYPE(src->getType())) { return false; } } if (src->isImm()) { // either src0 or src2 can be 16b imm, but not both // permanent WA: simd16 inst can't have src0 imm. // Instead of splitting, we just add a move if (canBeImm && (srcPos == 0 || srcPos == 2) && G4_Type_Table[src->getType()].byteSize <= 2) { if (VISA_WA_CHECK(builder.getPWaTable(), WaNoSimd16TernarySrc0Imm)) { return !isSrc2 && inst->getExecSize() == 16 ? false : true; } return true; } return false; } else if (src->isSrcRegRegion()) { if (src->asSrcRegRegion()->getRegAccess() != Direct) { return false; } auto checkSingleStrideRegion = [](G4_SrcRegRegion* src, int stride, uint8_t execSize, IR_Builder& builder) { RegionDesc* srcRegion = src->getRegion(); if (stride > 4) { return false; } else if (srcRegion->isContiguous(execSize)) { // Normalize the region if it is not. if (srcRegion->width != 1) { src->setRegion(builder.getRegionStride1(), /*invariant*/ true); } if (!builder.encodeUnitStrideTernary()) { // we have to make sure width is not being used to cross GRF, as <1;1,0> // is not a legal region for align1 ternary source (vs 1 not supported) // mad doesn't support <1;1,0>, the width is at least 2 int minAlignment = G4_Type_Table[src->getType()].byteSize * 2; return builder.isOpndAligned(src, minAlignment); } } return true; }; // the following regions are supported: // <N;N,0> // <0;1,0> // <W*H;W,H> RegionDesc* srcRegion = src->asSrcRegRegion()->getRegion(); if (srcRegion->isScalar()) { return true; } // src0 and src1 (for psuedo-mad, it's src1 and src2) may use the <N;N,0> region // as they come with a vStride in encoding // TODO: we may consider swapping src1 and src2 to catch more regions if (!isSrc2) { uint16_t stride = 0; if (srcRegion->isSingleStride(execSize, stride)) { return checkSingleStrideRegion(src->asSrcRegRegion(), stride, execSize, builder); } if (builder.encodeUnitStrideTernary()) { // <4;4,0> and <8;8,0> are ok return srcRegion->vertStride == srcRegion->width && srcRegion->horzStride == 0 && (srcRegion->width == 4 || srcRegion->width == 8); } else { // <2;2,0>, <4;4,0> and <8;8,0> are ok return srcRegion->vertStride == srcRegion->width && srcRegion->horzStride == 0 && srcRegion->width <= 8; } } else { if (!builder.noSrc2Regioning()) { // src2 (src0 for pseudo-mad) is without vstride, and its region must be // <esize*H;esize,H>, with vstride derived from exSize and hstride uint16_t stride = 0; if (srcRegion->isSingleStride(execSize, stride)) { return checkSingleStrideRegion(src->asSrcRegRegion(), stride, execSize, builder); } } else { // not a scalar, src2 must be GRF aligned. if (!builder.isOpndAligned(src, G4_GRF_REG_NBYTES)) { return false; } uint16_t stride = 0; if (srcRegion->isSingleStride(execSize, stride)) { unsigned short dstExecSize = inst->getDst()->getExecTypeSize(); unsigned short srcExecSize = stride * src->asSrcRegRegion()->getElemSize(); // Source 2 and destination stride must be aligned to the same execution type. // E.g. mad (4) r10.0<1>:hf src0 src1 r13.0<1>:hf // mad (4) r10.0<2>:hf src0 src1 r13.0<1>:f // mad (4) r10.0<1>:f src0 src1 r13.0<2>:hf // this rule is relaxed if mix mode is enabled (packed HF ok) if (dstExecSize == srcExecSize) { return true; } if (builder.hasPartialMixMode() && inst->isMixedMode()) { return true; } } } return false; } } return true; } // // a source is good for align16 if: // -- it is a direct srcRegRegion // -- it has contiguous region and can be made either GRF-aligned (for exec size >= 8) // or oword aligned (for exec size == 4) // -- or it has scalar region and is not non-simd1 double bool HWConformity::isGoodAlign16Src(G4_INST* inst, int srcPos) { MUST_BE_TRUE(srcPos >= 0 && srcPos < 3, "illegal source pos"); uint8_t execSize = inst->getExecSize(); G4_Operand* src = inst->getSrc(srcPos); G4_Type opnd_type = src->getType(); // Constants are not allowed as MAD opnds. if (src->isSrcRegRegion()) { RegionDesc* region = src->asSrcRegRegion()->getRegion(); G4_RegAccess regAcc = src->asSrcRegRegion()->getRegAccess(); if (regAcc != Direct) { return false; } if (region->isContiguous(execSize)) { if (getGenxPlatform() == GENX_BDW && getTypeSize(opnd_type) < 4) { // BDW HF has to be 32-byte aligned if (!builder.isOpndAligned(src, 32)) { return false; } } else { if (execSize >= 8) { // operand must be GRF aligned, or oword aligned for HF/W uint32_t align = std::min<uint32_t>(execSize * getTypeSize(src->getType()), 32); if (!builder.isOpndAligned(src, align)) { return false; } } else if (execSize == 4 || execSize == 2) { // operand must be oword-aligned if (!builder.isOpndAligned(src, 16)) { return false; } } } } else if (src->asSrcRegRegion()->isScalar()) { if (opnd_type == Type_DF && execSize != 1) { // scalar region is illegal for DF since replicate is not supported return false; } if (opnd_type == Type_HF && getGenxPlatform() == GENX_BDW) { return false; } } else { // all other regions are illegal return false; } return true; } else { return false; } } // // Move modifiers of src2 in pseudo_mad to its defining instruction. // // mul (16) V66(0,0)<1>:d V46(23,0)<16;16,1>:w 0x39db:w {Align1, H1} // psuedo_mad (16) V67(0,0)<1>:d V469,0)<8;8,1>:w 0x1b5d:w -V66(0,0)<16;16,1>:d // // becomes // // mul (16) V66(0,0)<1>:d -V46(23,0)<16;16,1>:w 0x39db:w {Align1, H1} // psuedo_mad (16) V67(0,0)<1>:d V469,0)<8;8,1>:w 0x1b5d:w V66(0,0)<16;16,1>:d // static void tryTransferSrcModifier(IR_Builder &builder, G4_INST *def, G4_Operand *src) { // Only when def has no other users. if (!def->hasOneUse()) return; // Only transfer for integer types. if (!IS_SIGNED_INT(src->getType())) return; // In case the use type is different from the def type. if (!def->getDst() || (def->getDst()->getType() != src->getType())) return; switch (def->opcode()) { default: break; // Probably this is the only interesting op, since G4_math will not be // used to generate mac. case G4_mul: { // Chances are src1 is an immediate. G4_Operand *defSrc1 = def->getSrc(1); if (!IS_SIGNED_INT(defSrc1->getType())) return; if (defSrc1->isImm()) { G4_Imm *val = defSrc1->asImm(); // Mod_Minus is assumed. G4_Imm *newVal = builder.createImm(-val->getInt(), val->getType()); def->setSrc(newVal, 1); src->asSrcRegRegion()->setModifier(Mod_src_undef); } else if (defSrc1->isSrcRegRegion()) { G4_SrcRegRegion *reg = defSrc1->asSrcRegRegion(); if (reg->getModifier() == Mod_src_undef) { reg->setModifier(src->asSrcRegRegion()->getModifier()); src->asSrcRegRegion()->setModifier(Mod_src_undef); } else if (reg->getModifier() == Mod_Minus) { reg->setModifier(Mod_src_undef); src->asSrcRegRegion()->setModifier(Mod_src_undef); } } } break; } } // Try to move source modifiers on MAD's src2 into its defintion. This allows // pseudo_mad ops to be translated into mac ops. void HWConformity::tryEliminateMadSrcModifier(IR_Builder &builder, G4_INST *inst) { ASSERT_USER(inst->opcode() == G4_pseudo_mad, "not a speudo-mad"); // For pseudo_mad, src2 is the major source operand to be examined later. // If there is no modifier on src2, then nothing to do. G4_Operand *src2 = inst->getSrc(2); if (!src2->isSrcRegRegion()) return; // Currently, only handle modifier minus. To handle others, we may need // to insert extra instructions. if (src2->asSrcRegRegion()->getModifier() != Mod_Minus) return; // Only when src2 has a single definition. if (G4_INST *def = inst->getSingleDef(Opnd_src2, true)) { tryTransferSrcModifier(builder, def, src2); } } /// Heuristic to decide whether this fp pseudo-mad should be lowered into a /// GEN mad or not. Returns true if mad is preferred, false otherwise. /// /// We flavor generating non-mad when this vISA mad is part of b2b mads that /// share the same dst. /// bool HWConformity::isFpMadPreferred(G4_BB *bb, INST_LIST_ITER iter) { G4_INST *inst = *iter; G4_Operand *dst = inst->getDst(); MUST_BE_TRUE(inst->opcode() == G4_pseudo_mad, "expect pseudo mad"); // Check whether test_inst is sharing the same dst. auto equal_mad_dst = [](G4_INST *test_inst, G4_Operand *dst) { if (test_inst->opcode() == G4_pseudo_mad) { G4_Operand *test_dst = test_inst->getDst(); if (test_dst->compareOperand(dst) == Rel_eq) return true; } return false; }; auto next_iter = std::next(iter); if (next_iter != bb->end()) { G4_INST *next_inst = *next_iter; if (equal_mad_dst(next_inst, dst)) return false; } if (iter != bb->begin()) { auto prev_iter = std::prev(iter); G4_INST *prev_inst = *prev_iter; if (equal_mad_dst(prev_inst, dst)) return false; } // FIXME: remove possile duplicate calls to isGoodAlign16Src, Cm only. // This will go away if we use an extra opcode to represent muladd. unsigned extraMov = 0; for (int k = 0; k < inst->getNumSrc(); k++) { if (!isGoodAlign16Src(inst, k)) { // If need to insert >1 number of moves, then do not use mad. if (++extraMov > 1) return false; } } return true; } // generate align1 mad, inserting moves if necessary // returns true if conversion is successful // for floating point mad this must succeed due to precision requirements bool HWConformity::generateAlign1Mad(G4_BB* bb, INST_LIST_ITER iter) { G4_INST* inst = *iter; MUST_BE_TRUE(inst->opcode() == G4_pseudo_mad, "expect pseudo mad"); bool mustDoMad = IS_TYPE_FLOAT_ALL(inst->getDst()->getType()); if (!isGoodAlign1TernaryDst(inst)) { if (mustDoMad) { auto alignment = builder.noSrc2Regioning() ? GRFALIGN : Four_Word; inst->setDest(insertMovAfter(iter, inst->getDst(), inst->getDst()->getType(), bb, alignment)); } else { return false; } } // try swapping src0 and src1 if src0 is D, as MAD only supports D + D * W, // and pseudo-mad src0 becomes mad src2 { G4_Operand* src0 = inst->getSrc(0); G4_Operand* src1 = inst->getSrc(1); if (IS_DTYPE(src0->getType()) && src0->isSrcRegRegion()) { if (!IS_DTYPE(src1->getType())) { inst->setSrc(src1, 0); inst->setSrc(src0, 1); } } else if (src1->isImm() && getTypeSize(src1->getType()) == 2) { //swap src0 and src1 as src0 supports imm inst->setSrc(src1, 0); inst->setSrc(src0, 1); } else if (!isGoodAlign1TernarySrc(inst, 0, true) && src1->isSrcRegRegion() && src1->asSrcRegRegion()->isScalar()) { // Swap src0 and src1 if src1 is scalar but src0 is not a good Align1TernarySrc // when src2 regioning support is quite limited. inst->setSrc(src1, 0); inst->setSrc(src0, 1); } } // check src bool canBeImm = true; for (int k = 0; k < inst->getNumSrc(); k++) { G4_Operand* src = inst->getSrc(k); if (!isGoodAlign1TernarySrc(inst, k, canBeImm)) { if (mustDoMad) { bool isSrc2 = (k == 0); if (builder.noSrc2Regioning() && isSrc2) { fixSrc2(iter, bb, true); } else { inst->setSrc(insertMovBefore(iter, k, src->getType(), bb), k); } } else { return false; } } else { if (src->isImm()) { canBeImm = false; } } } inst->setOpcode(G4_mad); //swap src0 and src2 (vISA MAD is src0*src1+src2, while GEN MAD is src1*src2+src0) G4_Operand* src0 = inst->getSrc(0); G4_Operand* src2 = inst->getSrc(2); inst->setSrc(src2, 0); inst->setSrc(src0, 2); return true; } // convert a FP (HF/F/DF) pseudo-mad into a GEN mad, // inserting moves if necessary // returns true if conversion is successful // note that this must return true for IGC due to precision requirements bool HWConformity::generateFPMad(G4_BB* bb, INST_LIST_ITER iter) { G4_INST* inst = *iter; MUST_BE_TRUE(inst->opcode() == G4_pseudo_mad, "expect pseudo mad"); uint8_t execSize = inst->getExecSize(); G4_DstRegRegion *dst = inst->getDst(); // Align16 MAD requirements: // -- dst and all 3 srcs have the same F/HF/DF type (mixed F/HF is allowed on CHV+) // -- dst and all 3 srcs have direct access // -- execution size is 16/8/4/1 // -- dst and src must be packed // -- if src region is not scalar, its subregister must be 16 byte aligned // do not force fma for CM since it doesn't have precision requirements bool preferFpMad = builder.getOption(vISA_forceFPMAD) || builder.favorFpMad(); if (!preferFpMad) { preferFpMad = isFpMadPreferred(bb, iter); } auto alignMent = execSize * G4_Type_Table[dst->getType()].byteSize; alignMent = (alignMent > 32) ? 32 : alignMent; alignMent = (alignMent < 16) ? 16 : alignMent; if (dst->getRegAccess() != Direct || dst->getHorzStride() != 1 || !builder.isOpndAligned(dst, alignMent)) { if (preferFpMad) { G4_DstRegRegion* tmpDst = insertMovAfter(iter, dst, dst->getType(), bb); inst->setDest(tmpDst); } else { return false; } } // check src for (int k = 0; k < inst->getNumSrc(); k++) { G4_Type type = inst->getSrc(k)->getType(); bool goodSrc = isGoodAlign16Src(inst, k); if (!goodSrc && preferFpMad) { // insert moves if type is legal mad type if (isGoodMadType(type)) { G4_Operand* src = inst->getSrc(k); bool isReplicated = (type == Type_DF) && src->isSrcRegRegion() && (src->asSrcRegRegion()->getRegion()->width == 2) && (src->asSrcRegRegion()->getRegion()->horzStride == 0) && (src->asSrcRegRegion()->getRegion()->vertStride == 2); if ((type == Type_DF || (type == Type_HF && getGenxPlatform() == GENX_BDW)) && execSize > 1 && (src->isImm() || src->asSrcRegRegion()->isScalar())) { // MAD DF does not support .r, so we have to broadcast the value // '.r' on MAD HF on BDW is not a replication of that // scalar element but a pair of half. auto align = type == Type_HF ? GRFALIGN : Eight_Word; broadcast(bb, iter, k, align); } // No need to insert mov for replicated DF src with <2;2,0> region, // which can be encoded as "xyxy" or "zwzw" swizzle based on offfset else if (!isReplicated) { inst->setSrc(insertMovBefore(iter, k, type, bb), k); } goodSrc = true; } } if (!goodSrc) { return false; } } inst->setOpcode(G4_mad); //swap src0 and src2 (vISA MAD is src0*src1+src2, while GEN MAD is src1*src2+src0) G4_Operand* src0 = inst->getSrc(0); G4_Operand* src2 = inst->getSrc(2); inst->setSrc(src2, 0); inst->setSrc(src0, 2); return true; } // If the LF MAD does not conform to Genx ISA semantics, then translate // it into a valid GenX sequence - either an equivalent MUL/ADD sequence // or an equivalent MAC. // ASSUMPTION: // This phase must be called at the end of all other optimizations // phases and just prior to testing for ACC spilling. void HWConformity::fixMADInst( G4_BB* bb ) { INST_LIST expand_list; // trace the MAD instrcutions that may be converted into MAC later std::vector<G4_INST*> madList; bool doAlign1Mad = builder.hasAlign1Ternary(); bb->resetLocalId(); INST_LIST_ITER i = bb->begin(); for (auto iterEnd = bb->end(); i != iterEnd; ++i ) { G4_INST *inst = *i; // predicated mad is not allowed? if( inst->opcode() != G4_pseudo_mad ) { continue; } tryEliminateMadSrcModifier(builder, inst); G4_DstRegRegion *dst = inst->getDst(); int exec_size = inst->getExecSize( ); G4_Operand *src0 = inst->getSrc(0), *src1 = inst->getSrc(1), *src2 = inst->getSrc(2); bool conforming_genx_mad = true; bool generate_genx_mac; if (exec_size == 32) { conforming_genx_mad = false; } else { switch (dst->getType()) { case Type_F: case Type_HF: case Type_DF: break; case Type_W: case Type_UW: case Type_D: case Type_UD: if (!doAlign1Mad) { conforming_genx_mad = false; } break; default: conforming_genx_mad = false; } } if (conforming_genx_mad) { bool doMad = doAlign1Mad ? generateAlign1Mad(bb, i) : generateFPMad(bb, i); if (doMad) { // done with this pseudo-mad continue; } } // Translate the LF MAD to an equivalent GenX sequence. if (builder.getOption(vISA_LocalMACopt)) { generate_genx_mac = true; } else { generate_genx_mac = false; } if (IS_TYPE_FLOAT_ALL(dst->getType()) && exec_size > 8) { // no float mac following the original code generate_genx_mac = false; } if (generate_genx_mac) { int emask = inst->getMaskOption(); if (emask != InstOpt_WriteEnable && inst->getMaskOffset() != 0) { generate_genx_mac = false; } // If either src1 or src0 are DWORD then we cannot generate a MAC. // ACC does not support B type if (generate_genx_mac && (IS_BTYPE(src2->getType()) || IS_DTYPE(src0->getType()) || IS_DTYPE(src1->getType()))) { generate_genx_mac = false; } // If there is a modifier for src2, or src2 is accessed somewhere indirectly then we will // not generate a MAC. if (generate_genx_mac) { if (src2->isImm() || (src2->isSrcRegRegion() && (src2->asSrcRegRegion()->getModifier() != Mod_src_undef || src2->asSrcRegRegion()->getRegAccess() != Direct || (src2->getTopDcl() && src2->getTopDcl()->getAddressed()))) || src2->getType() == Type_DF) { generate_genx_mac = false; } } } // we can't do mac if src2 is global or it has >1 def or its single def is global if( generate_genx_mac ) { G4_INST *mad_src2_def_inst = inst->getSingleDef(Opnd_src2); if (!mad_src2_def_inst || kernel.fg.globalOpndHT.isOpndGlobal(src2) || kernel.fg.globalOpndHT.isOpndGlobal(mad_src2_def_inst->getDst())) { generate_genx_mac = false; } if( madList.size() > 0 && mad_src2_def_inst != madList.back()) { // terminate the last mad list as this mad has a different definition int32_t lastMadId = madList.back()->getLocalId(); bool macGenerated = convertMAD2MAC( i, madList, bb ); madList.clear(); if (generate_genx_mac && macGenerated && mad_src2_def_inst->getLocalId() < lastMadId) { // mad's definition is before the last use of acc generate_genx_mac = false; } } if( generate_genx_mac && ( mad_src2_def_inst->getPredicate() || mad_src2_def_inst->getSaturate() || mad_src2_def_inst->isMath() || mad_src2_def_inst->opcode() == G4_shl || mad_src2_def_inst->opcode() == G4_mad || !mad_src2_def_inst->hasOneUse() || ( isCompressedInst(mad_src2_def_inst) ^ isCompressedInst(inst) )) ) { generate_genx_mac = false; } if( generate_genx_mac && madList.size() == 0 && IS_DTYPE(mad_src2_def_inst->getExecType()) ) { // We don't generate mac in this case since by default we use w type for acc, // and it would violate dst alignment restriction // if mad_src2_def_inst is itself a psuedo_mad, however, then it's ok // since both sources for mac must have word type. generate_genx_mac = false; } if( generate_genx_mac ) { // We will try to generate a MAC if it is possible to hoist // the definition for src2 into ACC, otherwise we will need to // generate a MOV/MAC; in which case we might as well // generate a MUL/ADD sequence anyway. // If the src2_def_op does not immediately precede the // MAD then we will attempt to schedule backward op to // immediately after src2_def_op. This will increase // the MAC reduction opportunities as it has the // effect of keeping ACC live ranges to very // short intervals. // NOTE: We do not attempt to schedule the src2_def_op // to just before op, as src2_def_op may be a // previously scheduled MAD. INST_LIST_ITER mov_iter = i; mov_iter--; uint16_t movDist = 0; if ((*mov_iter) != mad_src2_def_inst) { // check if src and dst of MAD are re-defined in between and // if dst is used in between if (!findHoistLocation(i, mov_iter, movDist, mad_src2_def_inst)) { generate_genx_mac = false; } else { if (movDist > 0) { mov_iter++; bb->insert(mov_iter, inst); INST_LIST_ITER tmpIter = i; i--; bb->erase(tmpIter); } } } // if instruction moving is blocked by some re-def, we need to check if it is possible that the ACC def instruction // will be split later. If yes, we do not use ACC and MAC here. // push this decision to convertMAC2MAD if (generate_genx_mac) { if (madList.size() == 0) { // push src2 def into list madList.push_back(mad_src2_def_inst); } madList.push_back(inst); } } } // translate MAD into MUL/ADD if (!generate_genx_mac) { convertMAD2MulAdd(i, bb); i++; } } if( madList.size() > 0 ) { i--; convertMAD2MAC( i, madList, bb ); } } struct AccInterval { G4_INST* inst; int lastUse; bool mustBeAcc0 = false; bool isPreAssigned = false; int assignedAcc = -1; int bundleConflictTimes = 0; int bankConflictTimes = 0; AccInterval(G4_INST* inst_, int lastUse_, bool preAssigned = false) : inst(inst_), lastUse(lastUse_), isPreAssigned(preAssigned) { if (isPreAssigned) { mustBeAcc0 = true; assignedAcc = 0; } } double getSpillCost() { if (isPreAssigned) { // don't spill pre-assigned return (double) 1000000; } int dist = lastUse - inst->getLocalId(); return std::pow((double)inst->use_size(), 3) / dist; } // see if this interval needs both halves of the acc bool needBothAcc(IR_Builder& builder) const { switch (inst->getDst()->getType()) { case Type_F: return inst->getExecSize() == (builder.getNativeExecSize() * 2); case Type_HF: return false; case Type_DF: return inst->getExecSize() > (builder.getNativeExecSize() / 2); default: return true; } } void dump() { std::cerr << "Interval: [" << inst->getLocalId() << ", " << lastUse << "]\n"; std::cerr << "\t"; inst->dump(); if (assignedAcc != -1) { std::cerr << "\tAssigned to Acc" << assignedAcc << "\n"; } std::cerr << "\n"; } }; // returns true if the inst is a candidate for acc substitution // lastUse is also update to point to the last use id of the inst static bool isAccCandidate(G4_INST* inst, G4_Kernel& kernel, int& lastUse, bool& mustBeAcc0) { mustBeAcc0 = false; G4_DstRegRegion* dst = inst->getDst(); if (!dst || kernel.fg.globalOpndHT.isOpndGlobal(dst) || !inst->canDstBeAcc()) { return false; } // check that every use may be replaced with acc int lastUseId = 0; std::vector<G4_INST*> madSrc0Use; std::vector<G4_INST*> threeSrcUses; //3src inst that use this dst for (auto I = inst->use_begin(), E = inst->use_end(); I != E; ++I) { auto&& use = *I; G4_INST* useInst = use.first; Gen4_Operand_Number opndNum = use.second; lastUseId = std::max(lastUseId, useInst->getLocalId()); // acc may be src0 of two-source inst or src1 of three-source inst // ToDo: may swap source here if (useInst->getNumSrc() == 3) { if (!kernel.fg.builder->relaxedACCRestrictions() && std::find(threeSrcUses.begin(), threeSrcUses.end(), useInst) != threeSrcUses.end()) { // don't allow acc to appear twice in a 3-src inst return false; } threeSrcUses.push_back(useInst); switch (opndNum) { case Opnd_src1: break; //OK case Opnd_src0: if (kernel.fg.builder->canMadHaveSrc0Acc()) { // OK } else if (useInst->opcode() == G4_mad) { // we can turn this mad into a mac mustBeAcc0 = true; if (useInst->getSrc(0)->getType() == Type_HF && useInst->getMaskOffset() == 16) { // we must use acc1, and need to check that inst does not have an acc0 source // so that dst and src won't have different acc source if (inst->isAccSrcInst()) { bool hasAcc0Src = false; auto isAcc0 = [](G4_SrcRegRegion* src) { return src->getBase()->asAreg()->getArchRegType() == AREG_ACC0; }; if (inst->getSrc(0)->isSrcRegRegion() && inst->getSrc(0)->asSrcRegRegion()->getBase()->isAccReg()) { hasAcc0Src = isAcc0(inst->getSrc(0)->asSrcRegRegion()); } else if (inst->getSrc(1)->isSrcRegRegion() && inst->getSrc(1)->asSrcRegRegion()->getBase()->isAccReg()) { hasAcc0Src = isAcc0(inst->getSrc(1)->asSrcRegRegion()); } if (hasAcc0Src) { return false; } } } madSrc0Use.push_back(useInst); } else { return false; } break; default: return false; } } else if (opndNum != Opnd_src0) { return false; } if (useInst->getSingleDef(opndNum) == nullptr) { // def must be the only define for this use return false; } int srcId = opndNum == Opnd_src0 ? 0 : 1; G4_Operand* src = useInst->getSrc(srcId); if (dst->getType() != src->getType() || kernel.fg.globalOpndHT.isOpndGlobal(src) || dst->compareOperand(src) != Rel_eq) { return false; } if (!useInst->canSrcBeAcc(opndNum)) { return false; } } // we have to avoid the case where the dst is used as both src0 and src1 of a mad for (auto madUse : madSrc0Use) { for (auto I = inst->use_begin(), E = inst->use_end(); I != E; ++I) { auto&& use = *I; G4_INST* useInst = use.first; Gen4_Operand_Number opndNum = use.second; if (madUse == useInst && opndNum == Opnd_src1) { return false; } } } if (lastUseId == 0) { // no point using acc for a dst without local uses return false; } lastUse = lastUseId; return true; } // replace an inst's dst and all of its (local) uses with acc // note that this may fail due to HW restrictions on acc static bool replaceDstWithAcc(G4_INST* inst, int accNum, IR_Builder& builder) { G4_DstRegRegion* dst = inst->getDst(); bool useAcc1 = (accNum & 0x1) != 0; accNum &= ~0x1; if (!builder.relaxedACCRestrictions()) { auto myAcc = useAcc1 ? AREG_ACC1 : AREG_ACC0; // check that dst and src do not have different accumulator for (int i = 0, numSrc = inst->getNumSrc(); i < numSrc; ++i) { if (inst->getSrc(i)->isAccReg()) { auto base = inst->getSrc(i)->asSrcRegRegion()->getBase(); if (base->isPhyAreg()) { if (base->asAreg()->getArchRegType() != myAcc) { return false; } } } } } for (auto I = inst->use_begin(), E = inst->use_end(); I != E; ++I) { auto&& use = *I; G4_INST* useInst = use.first; if (!builder.canMadHaveSrc0Acc() && useInst->opcode() == G4_mad && use.second == Opnd_src0) { // if we are replacing mad with mac, additionally check if acc1 needs to be used if (useInst->getMaskOffset() == 16 && dst->getType() == Type_HF) { if (builder.doMultiAccSub()) { // this is not legal since acc1 may be taken by another interval already return false; } useAcc1 = true; } } if (!builder.relaxedACCRestrictions()) { // do not allow an inst to have multiple acc source operands if (useInst->getNumSrc() == 3) { if (useInst->getSrc(0)->isAccReg() || useInst->getSrc(1)->isAccReg()) { return false; } } else if (useInst->opcode() == G4_mac) { // this can happen if we have to convert mad into mac (some platforms don't allow // src0 acc for mad), and the mad's src1 is also an acc candidate. return false; } } } // at this point acc substitution must succeed G4_Areg* accReg = useAcc1 ? builder.phyregpool.getAcc1Reg() : builder.phyregpool.getAcc0Reg(); G4_DstRegRegion* accDst = builder.createDstRegRegion(Direct, accReg, (short)accNum, 0, 1, dst->getType()); accDst->setAccRegSel(inst->getDst()->getAccRegSel()); inst->setDest(accDst); for (auto I = inst->use_begin(), E = inst->use_end(); I != E; ++I) { auto&& use = *I; G4_INST* useInst = use.first; int srcId = use.second == Opnd_src0 ? 0 : 1; G4_SrcRegRegion* oldSrc = useInst->getSrc(srcId)->asSrcRegRegion(); G4_SrcRegRegion* accSrc = builder.createSrcRegRegion(oldSrc->getModifier(), Direct, accReg, (short)accNum, 0, builder.getRegionStride1(), dst->getType()); accSrc->setAccRegSel(oldSrc->getAccRegSel()); if (useInst->opcode() == G4_mad && srcId == 0 && !builder.canMadHaveSrc0Acc()) { // change mad to mac as src0 of 3-src does not support acc auto updateDefSrcPos = [](G4_INST* useInst, Gen4_Operand_Number origPos) { for (auto DI = useInst->def_begin(), DE = useInst->def_end(); DI != DE; ++DI) { auto&& def = *DI; if (def.second == origPos) { for (auto UI = def.first->use_begin(), UE = def.first->use_end(); UI != UE; ++UI) { auto& use = *UI; if (use.first == useInst && use.second == origPos) { switch (use.second) { case Opnd_src1: use.second = Opnd_src0; break; case Opnd_src2: use.second = Opnd_src1; break; default: assert(false && "unexpectd src pos"); } } } } } }; assert(accNum == 0 && "mad src0 may only use acc0"); G4_Operand* macSrc0 = useInst->getSrc(1); updateDefSrcPos(useInst, Opnd_src1); G4_Operand* macSrc1 = useInst->getSrc(2); updateDefSrcPos(useInst, Opnd_src2); useInst->setSrc(macSrc0, 0); useInst->setSrc(macSrc1, 1); useInst->setOpcode(G4_mac); useInst->setImplAccSrc(accSrc); } else { useInst->setSrc(accSrc, srcId); } } return true; } struct AccAssignment { std::vector<bool> freeAccs; std::list<AccInterval*> activeIntervals; IR_Builder& builder; AccAssignment(int numGeneralAcc, IR_Builder& m_builder) : builder (m_builder) { freeAccs.resize(numGeneralAcc * 2, true); } // expire all intervals that end before the given interval void expireIntervals(AccInterval* interval) { for (auto iter = activeIntervals.begin(), iterEnd = activeIntervals.end(); iter != iterEnd;) { AccInterval* active = *iter; if (active->lastUse <= interval->inst->getLocalId()) { assert(!freeAccs[active->assignedAcc] && "active interval's acc should not be free"); freeAccs[active->assignedAcc] = true; if (active->needBothAcc(builder)) { assert(!freeAccs[active->assignedAcc + 1] && "active interval's acc should not be free"); freeAccs[active->assignedAcc + 1] = true; } iter = activeIntervals.erase(iter); } else { ++iter; } } } // spill interval that is assigned to accID and remove it from active list void spillInterval(int accID) { auto acc0Iter = std::find_if(activeIntervals.begin(), activeIntervals.end(), [accID](AccInterval* interval) { return interval->assignedAcc == accID; }); assert(acc0Iter != activeIntervals.end() && "expect to find interval with acc0"); auto spillInterval = *acc0Iter; assert(!spillInterval->isPreAssigned && "overlapping pre-assigned acc0"); spillInterval->assignedAcc = -1; activeIntervals.erase(acc0Iter); freeAccs[accID] = true; if (spillInterval->needBothAcc(builder)) { assert(accID % 2 == 0 && "accID must be even-aligned in this case"); freeAccs[accID+1] = true; } } // pre-assigned intervals (e.g., mach, addc) must use acc0 (and acc1 depending on inst type/size) // we have to spill active intervals that occupy acc0/acc1. // the pre-assigned interavl is also pushed to active list void handlePreAssignedInterval(AccInterval* interval) { if (!freeAccs[interval->assignedAcc]) { spillInterval(interval->assignedAcc); } freeAccs[interval->assignedAcc] = false; if (interval->needBothAcc(builder)) { assert(interval->assignedAcc == 0 && "Total 2 acc support right now"); if (!freeAccs[interval->assignedAcc + 1]) // && activeIntervals.size() { spillInterval(interval->assignedAcc + 1); } freeAccs[interval->assignedAcc + 1] = false; } activeIntervals.push_back(interval); } // pick a free acc for this interval // returns true if a free acc is found, false otherwise bool assignAcc(AccInterval* interval) { if (interval->isPreAssigned) { handlePreAssignedInterval(interval); return true; } int step = interval->needBothAcc(builder) ? 2 : 1; for (int i = 0, end = interval->mustBeAcc0 ? 1 : (int)freeAccs.size(); i < end; i += step) { if (freeAccs[i] && (!interval->needBothAcc(builder) || freeAccs[i+1])) { interval->assignedAcc = i; freeAccs[i] = false; if (interval->needBothAcc(builder)) { freeAccs[i+1] = false; } activeIntervals.push_back(interval); return true; } } return false; } }; void HWConformity::multiAccSubstitution(G4_BB* bb) { int numGeneralAcc = builder.getNumACC(); std::vector<AccInterval*> intervals; //build intervals for potential acc candidates as well as pre-existing acc uses from mac/mach/addc/etc for (auto instIter = bb->begin(), instEnd = bb->end(); instIter != instEnd; ++instIter) { G4_INST* inst = *instIter; if (inst->defAcc()) { // we should only have single def/use acc at this point, so any use would kill the def auto iter = instIter; auto useIter = std::find_if(++iter, instEnd, [](G4_INST* inst) { return inst->useAcc(); }); int lastUseId = useIter == instEnd ? bb->back()->getLocalId() : (*useIter)->getLocalId(); AccInterval *newInterval = new AccInterval(inst, lastUseId, true); intervals.push_back(newInterval); } else { int lastUseId = 0; bool mustBeAcc0 = false; int bundleBCTimes = 0; int bankBCTimes = 0; if (isAccCandidate(inst, kernel, lastUseId, mustBeAcc0)) { // this is a potential candidate for acc substitution AccInterval *newInterval = new AccInterval(inst, lastUseId); newInterval->mustBeAcc0 = mustBeAcc0; newInterval->bankConflictTimes = bankBCTimes; newInterval->bundleConflictTimes = bundleBCTimes; intervals.push_back(newInterval); } } } //modified linear scan to assign free accs to intervals AccAssignment accAssign(numGeneralAcc, builder); for (auto interval : intervals) { // expire intervals accAssign.expireIntervals(interval); // assign interval bool foundFreeAcc = accAssign.assignAcc(interval); //Spill if (!foundFreeAcc && accAssign.activeIntervals.size() != 0) { // check if we should spill one of the active intervals auto spillCostCmp = [interval](AccInterval* intv1, AccInterval* intv2) { if (!interval->mustBeAcc0) { return intv1->getSpillCost() < intv2->getSpillCost(); } // different compr function if interval must use acc0 if (intv1->assignedAcc == 0 && intv2->assignedAcc == 0) { return intv1->getSpillCost() < intv2->getSpillCost(); } else if (intv1->assignedAcc == 0) { return true; } return false; }; auto spillIter = std::min_element(accAssign.activeIntervals.begin(), accAssign.activeIntervals.end(), spillCostCmp); auto spillCandidate = *spillIter; if (interval->getSpillCost() > spillCandidate->getSpillCost() && !spillCandidate->isPreAssigned && !(interval->mustBeAcc0 && spillCandidate->assignedAcc != 0)) { bool tmpAssignValue[2]; tmpAssignValue[0] = accAssign.freeAccs[spillCandidate->assignedAcc]; accAssign.freeAccs[spillCandidate->assignedAcc] = true; if (spillCandidate->needBothAcc(builder)) { tmpAssignValue[1] = accAssign.freeAccs[spillCandidate->assignedAcc + 1]; accAssign.freeAccs[spillCandidate->assignedAcc + 1] = true; } if (accAssign.assignAcc(interval)) { spillCandidate->assignedAcc = -1; accAssign.activeIntervals.erase(spillIter); } else { accAssign.freeAccs[spillCandidate->assignedAcc] = tmpAssignValue[0]; if (spillCandidate->needBothAcc(builder)) { accAssign.freeAccs[spillCandidate->assignedAcc + 1] = tmpAssignValue[1]; } } } } } for (auto interval : intervals) { if (!interval->isPreAssigned && interval->assignedAcc != -1) { G4_INST* inst = interval->inst; replaceDstWithAcc(inst, interval->assignedAcc, builder); numAccSubDef++; numAccSubUse += (int)inst->use_size(); #if 0 std::cout << "Acc sub def inst: \n"; inst->emit(std::cout); std::cout << "[" << inst->getLocalId() << "]\n"; std::cout << "Uses:\n"; for (auto I = inst->use_begin(), E = inst->use_end(); I != E; ++I) { auto&& use = *I; std::cout << "\t"; use.first->emit(std::cout); std::cout << "[" << use.first->getLocalId() << "]\n"; } #endif } } for (int i = 0, end = (int)intervals.size(); i < end; ++i) { delete intervals[i]; } } // substitute local operands with acc when possible void HWConformity::accSubstitution(G4_BB* bb) { bb->resetLocalId(); if (builder.doMultiAccSub()) { multiAccSubstitution(bb); return; } for (auto instIter = bb->begin(), instEnd = bb->end(); instIter != instEnd; ++instIter) { bool canDoAccSub = true; G4_INST* inst = *instIter; if (inst->defAcc()) { // skip ahead till its single use // we should only have single def/use acc at this point, so any use would // kill the def auto iter = instIter; auto useIter = std::find_if(++iter, instEnd, [](G4_INST* inst) { return inst->useAcc(); }); if (useIter == instEnd) { return; } instIter = --useIter; // start at the use inst next time continue; } int lastUseId = 0; bool mustBeAcc0 = false; //ignored if (!isAccCandidate(inst, kernel, lastUseId, mustBeAcc0)) { continue; } // don't attempt acc sub if def and last use are too far apart // this is a crude way to avoid a long running life range from blocking // other acc sub opportunities const int accWindow = 25; if (lastUseId == 0 || lastUseId - inst->getLocalId() > accWindow) { continue; } // check for intervening acc usage between inst and its last use auto subIter = instIter; ++subIter; for (int instId = inst->getLocalId() + 1; instId != lastUseId; ++subIter, ++instId) { G4_INST* anInst = *subIter; if (anInst->useAcc() || anInst->mayExpandToAccMacro()) { canDoAccSub = false; break; } } if (!canDoAccSub) { continue; } else { replaceDstWithAcc(inst, 0, builder); // advance iter to the last use of the acc instIter = subIter; --instIter; numAccSubDef++; numAccSubUse += (int)inst->use_size(); #if 0 std::cout << "Acc sub def inst: \n"; inst->emit(std::cout); std::cout << "[" << inst->getLocalId() << "]\n"; std::cout << "Uses:\n"; for (auto&& use : inst->useInstList) { std::cout << "\t"; use.first->emit(std::cout); std::cout << "[" << use.first->getLocalId() << "]\n"; } #endif } } } // find the location for hoisting the inst pointed to by start // boundary is the upper limit for hoisting // if there is any ACC def/use between start and end, return false; // otherwise, return true. bool HWConformity::findHoistLocation( INST_LIST_ITER start, INST_LIST_ITER &end, uint16_t &movDist, G4_INST *boundary ) { bool canMov = true; G4_INST *inst = *start; end = start; end--; movDist = 0; if ((*end) != boundary) { // check if src and dst of MAD are re-defined in between and // if dst is used in between while ((*end) != boundary) { G4_INST *curInst = *end; if (curInst->hasACCOpnd() || curInst->mayExpandToAccMacro()) { canMov = false; break; } if (inst->isRAWdep(curInst) || inst->isWAWdep(curInst) || inst->isWARdep(curInst)) { break; } movDist++; --end; } // check if acc is possibly updated between the new location and boundary if (canMov && ((*end) != boundary)) { INST_LIST_ITER in_between_iter = end; ++in_between_iter; for (; (*in_between_iter) != boundary; --in_between_iter) { G4_INST *curInst = *in_between_iter; if (curInst->hasACCOpnd() || curInst->mayExpandToAccMacro()) { canMov = false; break; } } } } return canMov; } // for mac code gen we use W as acc type for int since it has enough precision for int G4_Type HWConformity::getAccType( G4_Type ty ) { if( ty == Type_D ) { return Type_W; } else if( ty == Type_UD ) { return Type_UW; } else { return ty; } } // convert MAD in madList to MAC instructions // iter is either the next pseudo-mad that does not belong to this list, or the last inst in the BB // return true if the mad list is converted to mac bool HWConformity::convertMAD2MAC( INST_LIST_ITER iter, std::vector<G4_INST*> &madList, G4_BB *bb ) { if( madList.size() == 1 ) { // there is only one inst in list, it is not a MAD return false; } // find the iterator of the last mad in list G4_INST *lastMad = madList.back(); INST_LIST_ITER movTarget, lastMadIter = iter; while ((*lastMadIter) != lastMad) { lastMadIter--; } movTarget = lastMadIter; bool changeType = false; bool dwDst = IS_TYPE_INT(lastMad->getDst()->getType()); bool twoGRFDst = lastMad->hasNULLDst() ? false : ((lastMad->getDst()->getRightBound() - lastMad->getDst()->getLeftBound() + 1) > GENX_GRF_REG_SIZ ); G4_Type newType = lastMad->getDst()->getType(); // check if we can convert the type of MAC dst from DW to W, // such that we can avoid instruction splitting and improve code quality if (dwDst && lastMad->hasNULLDst()) { // is this possible? changeType = true; lastMad->getDst()->setType( IS_SIGNED_INT( lastMad->getDst()->getType() ) ? Type_W : Type_UW ); } else if( dwDst && twoGRFDst && lastMad->hasOneUse() && !kernel.fg.globalOpndHT.isOpndGlobal(lastMad->getDst()) ) { // last mad has single use, see if we can replace the def-use pair with acc G4_INST *useInst = lastMad->use_front().first; if( useInst->getDst() && ( IS_BTYPE( useInst->getDst()->getType() ) || IS_WTYPE( useInst->getDst()->getType() ) ) ) { // check the use of last MAD dst INST_LIST_ITER useIter = lastMadIter; useIter++; while( (*useIter) != useInst ) { useIter++; } uint16_t movDist, hs; if( lastMad->canUseACCOpt( false, true, hs, true, true, true ) && hs == 1 && findHoistLocation( useIter, movTarget, movDist, lastMad ) && (*movTarget) == lastMad ) { changeType = true; if( movDist > 0 ) { movTarget++; bb->insert( movTarget, useInst ); bb->erase( useIter ); } uint32_t dstStrideSize = G4_Type_Table[useInst->getDst()->getType()].byteSize * useInst->getDst()->getHorzStride(); uint32_t useTypeSize = G4_Type_Table[Type_UW].byteSize; // insert a temp mov if( dstStrideSize > useTypeSize ) { movTarget--; insertMovAfter( movTarget, (uint16_t)( useTypeSize / G4_Type_Table[useInst->getDst()->getType()].byteSize ), bb ); } newType = getAccType( newType ); // change src of useInst to ACC Gen4_Operand_Number srcNum = lastMad->use_front().second; ASSERT_USER(useInst->getSrc((uint32_t)srcNum - 1)->isSrcRegRegion(), "Unexpected src to be changed!"); G4_SrcRegRegion *accSrcOpnd = builder.createSrcRegRegion( useInst->getSrc( (uint32_t)srcNum - 1 )->asSrcRegRegion()->getModifier(), Direct, builder.phyregpool.getAcc0Reg(), 0, 0, builder.getRegionStride1(), newType ); useInst->setSrc( accSrcOpnd, (uint32_t)srcNum - 1 ); // change dst of the last MAD G4_DstRegRegion *accDstOpnd = builder.createDstRegRegion( Direct, builder.phyregpool.getAcc0Reg(), 0, 0, 1, newType); lastMad->setDest( accDstOpnd ); } } } // if we can do type demotion or dst fits in 1GRF, we do not have to worry about inst splitting. if( !twoGRFDst || changeType ) { // generate MAC directly auto madIter = madList.end(); madIter--; G4_INST *curInst = (*madIter); G4_Type accType = getAccType(curInst->getSrc(2)->getType()); uint32_t accTypeSize = getTypeSize(accType); // mac dst region has to match that of acc, which is always GRF-aligned // we also cannot have acc dst hstride > 4 if (!builder.isOpndAligned(curInst->getDst(), GENX_GRF_REG_SIZ) || (curInst->getDst()->getExecTypeSize() / accTypeSize) > 4) { // ToDo: store the iter in madInst? auto instIter = std::find(bb->begin(), bb->end(), curInst); auto newDst = insertMovAfter(instIter, curInst->getDst(), curInst->getDst()->getType(), bb, GRFALIGN); curInst->setDest(newDst); } uint32_t dstByteStride = curInst->getDst()->getExecTypeSize(); uint16_t stride = (uint16_t) (dstByteStride > accTypeSize ? dstByteStride / accTypeSize : 1); RegionDesc* region = builder.createRegionDesc(stride, 1, 0); G4_SrcRegRegion *accSrcOpnd = builder.createSrcRegRegion( Mod_src_undef, Direct, builder.phyregpool.getAcc0Reg(), 0, 0, region, accType); curInst->setImplAccSrc(accSrcOpnd); curInst->setSrc(nullptr, 2); curInst->setOpcode( G4_mac ); curInst->fixMACSrc2DefUse(); do { // change all intermediate macs to use acc dst and src madIter--; curInst = (*madIter); bool changeSrc = curInst->opcode() == G4_pseudo_mad; addACCOpnd(curInst, changeSrc, stride, accType); } while( madIter != madList.begin() ); return true; } // just split them into mul/add // assumption: all pseudo_mads from lastMadIter back to the first inst should be on madList auto madIter = lastMadIter; for (G4_INST* inst = *madIter; inst != madList.front(); inst = *(--madIter)) { if (inst->opcode() == G4_pseudo_mad) { convertMAD2MulAdd(madIter, bb); } } return false; } void HWConformity::convertComprInstSrcRegion( G4_INST *inst ) { for( int k = 0; k < 2; k++ ) { G4_Operand *src = inst->getSrc( k ); if (!src || src->isImm() || (inst->isMath() && k == 1 && src->isNullReg())) { continue; } if (!src->isSrcRegRegion()) { continue; } int w = src->asSrcRegRegion()->getRegion()->width; int hs = src->asSrcRegRegion()->getRegion()->horzStride; int vs = src->asSrcRegRegion()->getRegion()->vertStride; if( w == 1 && hs == 0 && vs == 0 ) { continue; } if( inst->getExecSize() < w ) { RegionDesc *rd = builder.createRegionDesc( (uint16_t) (vs/2), (uint16_t) (w/2), (uint16_t) (hs/2) ); src->asSrcRegRegion()->setRegion( rd ); } } } // replace src/dst with ACC void HWConformity::addACCOpnd(G4_INST *curInst, bool needACCSrc, int dstStride, G4_Type accTy) { if (needACCSrc) { // change src2 to implicit ACC src. RegionDesc* region = nullptr; switch (dstStride) { case 1: region = builder.getRegionStride1(); break; case 2: region = builder.getRegionStride2(); break; case 4: region = builder.getRegionStride4(); break; default: MUST_BE_TRUE(false, "unexpected stride value"); break; } G4_SrcRegRegion *accSrcOpnd = builder.createSrcRegRegion( Mod_src_undef, Direct, builder.phyregpool.getAcc0Reg(), 0, 0, region, accTy); curInst->setImplAccSrc( accSrcOpnd ); curInst->setSrc( NULL, 2 ); curInst->setOpcode( G4_mac ); curInst->fixMACSrc2DefUse(); } // change dst for all in between MAD G4_DstRegRegion *accDstOpnd = builder.createDstRegRegion( Direct, builder.phyregpool.getAcc0Reg(), 0, 0, (unsigned short)dstStride, accTy); curInst->setDest(accDstOpnd); } // convert a psuedo mad inst into mul/add // return the iterator pointing to add void HWConformity::convertMAD2MulAdd( INST_LIST_ITER iter, G4_BB *bb ) { G4_INST *inst = *iter; assert(inst->opcode() == G4_pseudo_mad && "expect pseudo-mad"); G4_DstRegRegion *addOpDst = inst->getDst(); G4_Operand *addOpnd2 = inst->getSrc(2); G4_Type mulOpDstType = addOpDst->getType(); G4_Type mulOpExecType = inst->getExecType(); // pick the widest type of mad's src and dst as the intermediate type if (G4_Type_Table[mulOpDstType].byteSize > G4_Type_Table[mulOpExecType].byteSize) { mulOpExecType = mulOpDstType; } mulOpDstType = mulOpExecType; G4_SubReg_Align subAlign = Get_G4_SubRegAlign_From_Type( mulOpDstType ); // Reuse the MAD op for MUL. inst->setOpcode(G4_mul); inst->setSrc(nullptr, 2); G4_Declare* mulDefDcl = builder.createTempVar(inst->getExecSize(), mulOpDstType, subAlign); G4_DstRegRegion* mulOpDst = builder.Create_Dst_Opnd_From_Dcl(mulDefDcl, 1); inst->setDest(mulOpDst); // Follow with an ADD. INST_LIST_ITER tIter = iter; tIter++; auto addOpnd1 = builder.Create_Src_Opnd_From_Dcl(mulDefDcl, builder.getRegionStride1()); G4_INST* addOp = builder.createInternalInst( inst->getPredicate(), G4_add, inst->getCondMod(), inst->getSaturate(), inst->getExecSize(), addOpDst, addOpnd1, addOpnd2, nullptr, inst->getOption(), inst->getLineNo(), inst->getCISAOff(), inst->getSrcFilename() ); bb->insert( tIter, addOp ); // predicate/condmod/saturate, if they exist, are propagated to the add instruction inst->setSaturate( false ); inst->setPredicate( NULL ); inst->setCondMod(nullptr); { inst->transferDef( addOp, Opnd_src2, Opnd_src1 ); if( addOp->getPredicate() ) { inst->transferDef( addOp, Opnd_pred, Opnd_pred ); } inst->transferUse( addOp ); inst->addDefUse(addOp, Opnd_src0); } } // See if we can convert the pseudo_sada2 instruction into an actual Gen sada2 // This can be done if the following conditions are met: // -- We can find the definition of the pseudo sada2 instruction's source 2 in // the same basic block, and that // -- it may be replaced by an acc (i.e., the src2 is its only use, the dst and // the src have identical regions, and there are no intervening instructions // that update acc) // // We additionally attempt to schedule up the sada2 instruction to be as close // as possible to the src2 defining instruction (subject to the constraints of // def-use chains for def, src0 and src1), so that more opportunites may be // exposed for later sada2 instructions void HWConformity::fixSADA2Inst(G4_BB* bb) { INST_LIST_ITER i = bb->begin(); while (i != bb->end()) { G4_INST *inst = *i; if( inst->opcode() != G4_pseudo_sada2 ) { ++i; continue; } G4_Operand *src2 = inst->getSrc(2); bool canDoSada2 = true; G4_INST* src2Dst = NULL; int emask = inst->getMaskOption(); if (bb->isInSimdFlow() && emask != InstOpt_WriteEnable && inst->getMaskOffset() != 0) { canDoSada2 = false; } G4_DstRegRegion *dst = inst->getDst(); if( canDoSada2 ) { if( src2->isSrcRegRegion() && src2->asSrcRegRegion()->getRegAccess() == Direct ) { // check Src2 if( kernel.fg.globalOpndHT.isOpndGlobal(src2 ) ) { // no sada2 if operand is global canDoSada2 = false; } else if( src2->asSrcRegRegion()->getModifier() != Mod_src_undef ) { // no sada2 if src2 has a modifier canDoSada2 = false; } else { for (auto defIter = inst->def_begin(), end = inst->def_end(); defIter != end; ++defIter) { if((*defIter).second == Opnd_src2 ) { if( src2Dst != NULL ) { // no sada2 if src2 has >1 definition canDoSada2 = false; break; } src2Dst = (*defIter).first; } } if( !src2Dst ) { canDoSada2 = false; } else { if( !src2Dst->hasOneUse() ) { // no sad2 if def has more than one use canDoSada2 = false; } else { G4_DstRegRegion *src2DstOpnd = src2Dst->getDst(); G4_Type src2DstType = src2DstOpnd->getType(); if( src2DstOpnd->getRegAccess() != Direct || (src2DstType != Type_W && src2DstType != Type_UW) ) { // no sada2 if def's dst is indirect, or it type is not W or UW canDoSada2 = false; } else if( src2DstOpnd->compareOperand( src2 ) != Rel_eq ) { // no sada2 if src2Dst and src2 are not equal canDoSada2 = false; } } } } } else { canDoSada2 = false; } } // The new location of the sada2 after the conversion INST_LIST_ITER newSada2Iter = i; --newSada2Iter; if( canDoSada2 ) { // try to schedule up the sada2 to be as close to the src2-defining instruction // as possible to expose more optmizaition opportunities for(; *newSada2Iter != src2Dst; --newSada2Iter ) { if( inst->isRAWdep( *newSada2Iter ) || inst->isWAWdep( *newSada2Iter ) || inst->isWARdep( *newSada2Iter ) ) { break; } } // make sure there are no instructions between the sada2's new location // and the src2-defining instruction that updates acc for (auto iter = newSada2Iter; *iter != src2Dst; --iter) { G4_INST* aInst = *iter; if (aInst->hasACCOpnd()) { canDoSada2 = false; break; } } } if( canDoSada2 ) { // We have verified all conditions and can convert this instruction to sada2. // replace the destination for src2Dst to be acc0. // The actual acc0 offset will be fixed in a later pass G4_DstRegRegion *accDstOpnd = builder.createDstRegRegion( Direct, builder.phyregpool.getAcc0Reg(), 0, 0, 1, src2->getType()); src2Dst->setDest( accDstOpnd ); if (src2Dst->getExecSize() == 1) { // This can happen for the first sada2 instruction if src2 is scalar // expand its execution size so that acc is fully defined src2Dst->setExecSize(inst->getExecSize()); } // create an implicit acc parameter for sada2 inst->setOpcode( G4_sada2 ); inst->setSrc( NULL, 2 ); G4_SrcRegRegion *accSrcOpnd = builder.createSrcRegRegion( Mod_src_undef, Direct, builder.phyregpool.getAcc0Reg(), 0, 0, builder.getRegionStride1(), src2->getType()); inst->setImplAccSrc( accSrcOpnd ); ++newSada2Iter; bb->insert( newSada2Iter, inst ); i = bb->erase(i); // maintain def-use for (auto tmpIter = src2Dst->use_begin(), end = src2Dst->use_end(); tmpIter != end; ++tmpIter) { if( (*tmpIter).first == inst && (*tmpIter).second == Opnd_src2 ) { (*tmpIter).second = Opnd_implAccSrc; break; } } for (auto tmpIter = inst->def_begin(), end = inst->def_end(); tmpIter != end; ++tmpIter) { if( (*tmpIter).first == src2Dst && (*tmpIter).second == Opnd_src2 ) { (*tmpIter).second = Opnd_implAccSrc; break; } } } else { // pseudo_sada2 (N) dst src0 src1 src2 // becomes // sad2 (n) tmp<1>:w src0 src1 // add (n) dst tmp<n;n,1>:w src2 inst->setOpcode( G4_sad2 ); inst->setSrc( NULL, 2 ); G4_SubReg_Align sad2TmpSubAlign = Get_G4_SubRegAlign_From_Type( dst->getType() ); if( inst->getExecSize() * G4_Type_Table[dst->getType()].byteSize > GENX_GRF_REG_SIZ ) { // align to GRF sad2TmpSubAlign = GRFALIGN; } // create a new temp variable as sad2's destination G4_Declare* sad2Tmp = builder.createTempVar( inst->getExecSize(), dst->getType(), sad2TmpSubAlign); G4_DstRegRegion* sad2Dst = builder.Create_Dst_Opnd_From_Dcl(sad2Tmp, 1); inst->setDest( sad2Dst ); uint16_t srcVertStride, srcWidth, srcHorzStride; srcWidth = inst->getExecSize() > 8 ? 8 : inst->getExecSize(); srcHorzStride = 1; srcVertStride = srcWidth; // opnd 0 for add is the new temp we've just created RegionDesc *rd = builder.createRegionDesc( srcVertStride, srcWidth, srcHorzStride ); G4_Operand* addSrc0Opnd = builder.createSrcRegRegion(Mod_src_undef, Direct, sad2Dst->getBase(), 0, 0, rd, sad2Dst->getType() ); // opnd 1 is src2 of the pseudo_sada2 // dst is the same as the pseudo_sada2 G4_INST* addInst = builder.createInternalInst( inst->getPredicate(), G4_add, inst->getCondMod(), inst->getSaturate(), inst->getExecSize(), dst, addSrc0Opnd, src2, NULL, inst->getOption(), inst->getLineNo(), inst->getCISAOff(), inst->getSrcFilename() ); INST_LIST_ITER addLoc = i; ++addLoc; bb->insert( addLoc, addInst ); // FIXME: redundant? inst->addDefUse(addInst, Opnd_src0); // The sad2 op should not have the SAT attribute set, // as this is intended only for the final result of the // SADA2 (and thus the add op will keep the SAT attribute). inst->setSaturate( false ); inst->setPredicate( NULL ); { inst->transferDef( addInst, Opnd_src2, Opnd_src1 ); if( addInst->getPredicate() ) { inst->transferDef( addInst, Opnd_pred, Opnd_pred ); } inst->transferUse( addInst ); inst->addDefUse(addInst, Opnd_src0); } ++i; } } } void HWConformity::fixSendInst(G4_BB* bb) { for (INST_LIST_ITER i = bb->begin(), end = bb->end(); i != end; i++) { G4_INST *inst = *i; if (!inst->isSend()) { continue; } if (inst->getExecSize() < 8) { // A64 messages require a minimum msg len of two for address (src0), which is inconsistent // with our input IR as it allows <2 GRF address variables (e.g., simd1 A64 scatter r/w). // To avoid this causing overlap between send dst/src0/src1 (it is known to cause HW hang), // we have to ensure they are all 2GRF-aligned G4_Declare* src0Dcl = inst->getSrc(0)->getTopDcl(); // ToDo: check if dst/src1 may also exhibit such size mismatch bool sizeMismatch = inst->getMsgDesc()->MessageLength() == 2 && (src0Dcl && src0Dcl->getRootDeclare()->getByteSize() < 2u * GENX_GRF_REG_SIZ); auto doEvenAlign = [](G4_Declare* dcl) { if (dcl) { dcl = dcl->getRootDeclare(); // variables >= 2 GRF don't need even alignment since they can't possibly overlap if (dcl->getByteSize() < 2u * GENX_GRF_REG_SIZ) { dcl->setEvenAlign(); } } }; if (sizeMismatch) { doEvenAlign(inst->getSrc(0)->getTopDcl()); if (inst->isSplitSend()) { doEvenAlign(inst->getSrc(1)->getTopDcl()); } if (VISA_WA_CHECK(builder.getPWaTable(), WaDisableSendSrcDstOverlap)) { doEvenAlign(inst->getDst()->getTopDcl()); } } } uint16_t offset = 0; if (!builder.isOpndAligned(inst->getDst(), offset, GENX_GRF_REG_SIZ)) { inst->setDest(insertMovAfter(i, inst->getDst(), inst->getDst()->getType(), bb, GRFALIGN)); } G4_Operand *src0 = inst->getSrc(0); G4_Declare *src0TopDcl = src0->getTopDcl(); // if src0 and src1 are hard-wired GRF, check that // they satisfy EOT and preemption restrictions auto needsTempSrc = [this](G4_INST* inst, G4_Declare* dcl) { return dcl->getRegVar() && dcl->getRegVar()->getPhyReg() && ((inst->isEOT() && builder.hasEOTGRFBinding() && dcl->getRegVar()->getPhyReg()->asGreg()->getRegNum() < 112) || (builder.getOption(vISA_enablePreemption) && dcl->getRegVar()->getPhyReg()->asGreg()->getRegNum() < 2)); }; if (needsTempSrc(inst, src0TopDcl)) { uint16_t rows = inst->getMsgDesc()->MessageLength(); G4_Type type = src0->getType(); G4_Declare* dcl = builder.createTempVar(rows * 8, type, GRFALIGN); MUST_BE_TRUE(G4_Type_Table[type].byteSize == 4, "Invalid src0 opnd type for send."); RegionDesc* region = builder.getRegionStride1(); G4_VarBase *base = src0->asSrcRegRegion()->getBase(); short baseOff = src0->asSrcRegRegion()->getRegOff(); short baseSubOff = src0->asSrcRegRegion()->getSubRegOff(); for (uint16_t idx = 0; idx != rows; ++idx) { G4_SrcRegRegion *src = builder.createSrcRegRegion(Mod_src_undef, Direct, base, baseOff + idx, baseSubOff + 0, region, type); G4_DstRegRegion* dst = builder.createDstRegRegion(Direct, dcl->getRegVar(), idx, 0, 1, type); G4_INST* newInst = builder.createMov(8, dst, src, InstOpt_WriteEnable, false); bb->insert(i, newInst); inst->transferDef(newInst, Opnd_src0, Opnd_src0); newInst->addDefUse(inst, Opnd_src0); } G4_Operand *newSrc = builder.Create_Src_Opnd_From_Dcl(dcl, builder.getRegionStride1()); inst->setSrc(newSrc, 0); } if (inst->isSplitSend() && !inst->getSrc(1)->isNullReg()) { // src1 may be null because some messages (e.g., CPS) require split send if (!builder.isOpndAligned(inst->getSrc(1), GENX_GRF_REG_SIZ)) { inst->setSrc(insertMovBefore(i, 1, inst->getSrc(1)->getType(), bb, GRFALIGN), 1); } G4_Operand *src1 = inst->getSrc(1); G4_Declare *src1TopDcl = src1->getTopDcl(); if (needsTempSrc(inst, src1TopDcl)) { uint16_t rows = inst->getMsgDesc()->extMessageLength(); G4_Type type = src1->getType(); G4_Declare* dcl = builder.createTempVar(rows * 8, type, GRFALIGN); MUST_BE_TRUE(G4_Type_Table[type].byteSize == 4, "Invalid src1 opnd type for send."); RegionDesc* region = builder.getRegionStride1(); G4_VarBase *base = src1->asSrcRegRegion()->getBase(); short baseOff = src1->asSrcRegRegion()->getRegOff(); short baseSubOff = src1->asSrcRegRegion()->getSubRegOff(); for (uint16_t idx = 0; idx != rows; ++idx) { G4_SrcRegRegion *src = builder.createSrcRegRegion(Mod_src_undef, Direct, base, baseOff + idx, baseSubOff + 0, region, type); G4_DstRegRegion* dst = builder.createDstRegRegion(Direct, dcl->getRegVar(), idx, 0, 1, type); G4_INST* newInst = builder.createMov(8, dst, src, InstOpt_WriteEnable, false); bb->insert(i, newInst); inst->transferDef(newInst, Opnd_src1, Opnd_src1); newInst->addDefUse(inst, Opnd_src1); } G4_Operand *newSrc = builder.Create_Src_Opnd_From_Dcl(dcl, region); inst->setSrc(newSrc, 1); } } if (builder.getOption(vISA_enablePreemption)) { G4_DstRegRegion *dst = inst->getDst(); if (!dst->isNullReg()) { G4_Declare *dstTopDcl = dst->getTopDcl(); if (dstTopDcl != NULL && dstTopDcl->getRegVar() && dstTopDcl->getRegVar()->getPhyReg()) { MUST_BE_TRUE((dstTopDcl->getRegVar()->getPhyReg()->asGreg()->getRegNum() > 2), "Unexpected preg used for send destination."); } } } if (VISA_WA_CHECK(builder.getPWaTable(), WaDisableSendSrcDstOverlap)) { // create copy if dst and src0/src1 overlap due to being the same variable bool src0Overlap = inst->getDst()->compareOperand(inst->getSrc(0)) != Rel_disjoint; bool src1Overlap = inst->isSplitSend() && inst->getDst()->compareOperand(inst->getSrc(1)) != Rel_disjoint; if (src0Overlap || src1Overlap) { int dstSize = inst->getMsgDesc()->ResponseLength(); int src0Size = src0Overlap ? inst->getMsgDesc()->MessageLength() : 0; int src1Size = src1Overlap ? inst->getMsgDesc()->extMessageLength() : 0; if (dstSize > src0Size + src1Size) { //copy src0/src1 if (src0Overlap) { G4_Declare* copyDst = builder.createTempVar(src0Size * 8, Type_UD, Any); copyRegs(copyDst, 0, inst->getSrc(0)->getBase()->asRegVar()->getDeclare(), inst->getSrc(0)->asSrcRegRegion()->getRegOff() * 32, src0Size, bb, i); inst->setSrc(builder.Create_Src_Opnd_From_Dcl(copyDst, builder.getRegionStride1()), 0); } if (src1Overlap) { G4_Declare* copyDst = builder.createTempVar(src1Size * 8, Type_UD, Any); copyRegs(copyDst, 0, inst->getSrc(1)->getBase()->asRegVar()->getDeclare(), inst->getSrc(1)->asSrcRegRegion()->getRegOff() * 32, src1Size, bb, i); inst->setSrc(builder.Create_Src_Opnd_From_Dcl(copyDst, builder.getRegionStride1()), 1); } } else { // copy dst auto copyIter = i; ++copyIter; G4_Declare* copySrc = builder.createTempVar(dstSize * 8, Type_UD, Any); copyRegs(inst->getDst()->getBase()->asRegVar()->getDeclare(), inst->getDst()->getRegOff() * 32, copySrc, 0, dstSize, bb, copyIter); inst->setDest(builder.Create_Dst_Opnd_From_Dcl(copySrc, 1)); } } } } } // // Fix sel and csel instructions: // -- set their cond mod to null as they don't modify it. They will be hard-coded to f0.0 in Gen asm void HWConformity::fixSelCsel(INST_LIST_ITER it, G4_BB* bb) { G4_INST* inst = *it; if (inst->opcode() == G4_sel || inst->opcode() == G4_csel) { G4_CondMod *condMod = inst->getCondMod(); if (condMod) { condMod->setBase(nullptr); } } } void HWConformity::conformBB(G4_BB* bb) { INST_LIST_ITER i = bb->begin(), iEnd = bb->end(); INST_LIST_ITER next_iter = i; for ( ; i != iEnd; i = next_iter ) { // by default we skip the newly inserted instructions as we assume they are already HW conformed // if a check may produce new instructions that violate HW rules, it must adjust the next_iter // to point to them ++next_iter; G4_INST *inst = *i; G4_opcode opcode = inst->opcode(); if (opcode == G4_nop || opcode == G4_label) { continue; } // do this early since otherwise the moves inserted by other passes may still // inherit bad regions from the original inst fixSrcRegion(inst); bool changed = fixMov(i, bb); if (changed) { next_iter = i; next_iter++; } fixOpndType(i, bb); fixSelCsel(i, bb); if (inst->getExecSize() > builder.getNativeExecSize()) { if (inst->opcode() == G4_math && inst->getDst()->getType() == Type_HF && inst->getSrc(0)->getType() == Type_HF && (!inst->getSrc(1) || inst->getSrc(1)->getType() == Type_HF)) { // split pure HF math to simd8 evenlySplitInst(i, bb); } } fix3SrcInst(i, bb); G4_Operand *dst = inst->getDst(); #ifdef _DEBUG verifyG4Kernel(kernel, Optimizer::PI_HWConformityChk, false); #endif if (inst->isMath()) { if( fixMathInst( i, bb ) ) { // check the newly added insts later next_iter = i; next_iter++; } } inst = *i; #ifdef _DEBUG verifyG4Kernel(kernel, Optimizer::PI_HWConformityChk, false); #endif if( inst->opcode() == G4_mul ) { if(fixMULInst( i, bb ) ) { // inserted mach and mov // check the newly added insts later ( MUL, MACH, MOV ) next_iter = i; next_iter++; } } #ifdef _DEBUG verifyG4Kernel(kernel, Optimizer::PI_HWConformityChk, false); #endif if( inst->opcode() == G4_mulh ) { fixMULHInst( i, bb ); // inserted mul before // check the newly added MUL inst i--; next_iter = i; continue; } #ifdef _DEBUG verifyG4Kernel(kernel, Optimizer::PI_HWConformityChk, false); #endif // HW check #6: indirect operand spilling fixIndirectOpnd( i, bb ); #ifdef _DEBUG verifyG4Kernel(kernel, Optimizer::PI_HWConformityChk, false); #endif // HW check #8: unsigned dst with execution type F /* If the execution type is F and the destination type if either UD, UW * or UB and the detination is not saturated, then we need to add an * intermediate type conversion to D. */ inst = *i; opcode = inst->opcode(); if (opcode == G4_cmp || opcode == G4_cmpn) { dst = inst->getDst(); int dst_elsize = 0; bool null_dst = !dst || inst->hasNULLDst(); if (!null_dst) { dst_elsize = dst->isPredicate() ? G4_Type_Table[Type_UW].byteSize : G4_Type_Table[dst->getType()].byteSize; } int extypesize; G4_Type extype = inst->getOpExecType( extypesize ); fixCompareInst( i, bb, extype, dst_elsize ); } dst = inst->getDst(); #ifdef _DEBUG verifyG4Kernel(kernel, Optimizer::PI_HWConformityChk, false); #endif if (fixAcc(i, bb)) { next_iter = i; next_iter++; } #ifdef _DEBUG verifyG4Kernel(kernel, Optimizer::PI_HWConformityChk, false); #endif { dst = inst->getDst(); G4_Type extype = inst->getExecType2(); int extypesize = G4_Type_Table[extype].byteSize; int dst_elsize = 0; if (dst) { dst_elsize = G4_Type_Table[dst->getType()].byteSize; } if (dst && inst->getExecSize() == 1 && dst_elsize < extypesize && !IS_VTYPE(extype) && !inst->isMixedMode() && !inst->isSend()) { fixDstHstride( i, extypesize ); } } #ifdef _DEBUG verifyG4Kernel(kernel, Optimizer::PI_HWConformityChk, false); #endif bool planeDeleted = fixPlaneInst(i, bb); if (planeDeleted) { continue; } fixLine(i, bb); fixRotate(i, bb); if (!builder.hasVxHFloat64b()) { fixVxHFloat64b(i, bb); } // CHV/BXT specific checks for 64b datatypes fix64bInst( i, bb); #ifdef _DEBUG verifyG4Kernel(kernel, Optimizer::PI_HWConformityChk, false); #endif fixImm64( i, bb ); // fixed immediates for DF4 in fixImm64() // FIXME: may be better to call fixDstAlign instead if (getGenxPlatform() == GENX_BDW) { fixPackedHFConversions(i, bb); } } } // // SIMD16 addc/subb are illegal on GEN, since they write to acc and there are only 8 acc // channels for D/UD type. In vISA IR we should get something like // addc (16) V0 V2 V3 // mov (16) V1 acc0<8;8,1>:ud // which needs to be translated to // addc (8) V0(0) V2(0) V3(0) {Q1} // mov (8) V1(0) acc0<8;8,1>:ud {Q1} // addc (8) V0(1) V2(1) V3(1) {Q2} // mov (8) V1(1) acc0<8;8,1>:ud {Q2} // // We do this first thing in HW conformity to avoid REXES from splitting addc/subb incorrectly // We also count on previous opt to preserve the inst pair by not inserting any acc using inst in between; // it should hopefully be the case since we generally don't optimize instructions with acc src/dst // // If exec size of addc is < 8, we also have to make sure both the addc's dst and the carry move's dst are // GRF-aligned, since acc's channel is dependent on the dst's subreg offset. In other words, we fix // addc (1) r1.0 ... // mov (1) r1.1 acc0.0<0;1,0> // into // addc (1) r1.0 ... // mov (1) r2.0 acc0.0<0;1,0> // mov (1) r1.1 r2.0 // // bool HWConformity::fixAddcSubb(G4_BB* bb) { bool changed = false; for (auto iter = bb->begin(), iterEnd = bb->end(); iter != iterEnd; ++iter) { G4_INST* inst = *iter; if ((inst->opcode() == G4_addc || inst->opcode() == G4_subb) && inst->getExecSize() != 8) { // find the matching carry move G4_INST* carryMov = NULL; auto movIter = iter; for (++movIter; movIter != iterEnd; ++movIter) { G4_INST* inst2 = *movIter; if (inst2->opcode() == G4_mov && inst2->getExecSize() == inst->getExecSize() && inst2->getSrc(0)->isAccReg() && inst2->getSrc(0)->getType() == Type_UD) { carryMov = inst2; break; } else if (inst2->useAcc()) { break; } } if (carryMov == NULL) { // can't find the move using acc, skip this addc/subb assert(false && "expect a carry move instruction"); continue; } if (inst->getExecSize() > builder.getNativeExecSize()) { evenlySplitInst(iter, bb); evenlySplitInst(movIter, bb); // movIter now points to the second half of move, and we want to move the first move to be // before the second half of the addc/subb, which is pointed by iter --movIter; G4_INST* mov1 = *movIter; bb->erase(movIter); bb->insert(iter, mov1); changed = true; } else { // we will need to GRF-align addc's dst as well as the move dst, // so that the acc will have the correct offset // note that insertMovAfter will align the tmp since addc/subb has implicit acc use if (!builder.isOpndAligned(inst->getDst(), 32)) { inst->setDest( insertMovAfter(iter, inst->getDst(), inst->getDst()->getType(), bb)); changed = true; } if (!builder.isOpndAligned(carryMov->getDst(), 32)) { carryMov->setDest( insertMovAfter(movIter, carryMov->getDst(), carryMov->getDst()->getType(), bb)); changed = true; } } } } return changed; } void HWConformity::chkHWConformity() { fixDataLayout(); for (auto bb : kernel.fg) { fixIntToHFMove(bb); #ifdef _DEBUG verifyG4Kernel(kernel, Optimizer::PI_HWConformityChk, false); #endif fixAddcSubb(bb); #ifdef _DEBUG verifyG4Kernel(kernel, Optimizer::PI_HWConformityChk, false); #endif fixMADInst( bb ); #ifdef _DEBUG verifyG4Kernel(kernel, Optimizer::PI_HWConformityChk, false); #endif // fix source operand first to avoid redundant MOVs if this fix is done after // reducing execution size. // used by 3d. Mainly to fix sel with two imm sources fixOpndTypeAlign( bb ); #ifdef _DEBUG verifyG4Kernel(kernel, Optimizer::PI_HWConformityChk, false); #endif if (builder.getOption(vISA_accSubstitution) && !builder.getOption(vISA_doAccSubAfterSchedule)) { accSubstitution(bb); } #ifdef _DEBUG verifyG4Kernel(kernel, Optimizer::PI_HWConformityChk, false); #endif fixInstExecSize( bb ); #ifdef _DEBUG verifyG4Kernel(kernel, Optimizer::PI_HWConformityChk, false); #endif fixMixedHFInst( bb ); #ifdef _DEBUG verifyG4Kernel(kernel, Optimizer::PI_HWConformityChk, false); #endif fixSADA2Inst( bb ); #ifdef _DEBUG verifyG4Kernel(kernel, Optimizer::PI_HWConformityChk, false); #endif fixSendInst( bb ); #ifdef _DEBUG verifyG4Kernel(kernel, Optimizer::PI_HWConformityChk, false); #endif conformBB(bb); #ifdef _DEBUG verifyG4Kernel(kernel, Optimizer::PI_HWConformityChk, false); #endif } } bool HWConformity::hasBadRegion( G4_INST *inst ) { if( inst->getImplAccDst() || inst->getImplAccSrc() ) return false; bool badRegion = false; for( unsigned int srcNum = 0, n_srcs = G4_Inst_Table[inst->opcode()].n_srcs; srcNum < n_srcs; srcNum++ ) { if( !(inst->getSrc(srcNum)->isSrcRegRegion()) ) { continue; } RegionDesc *rd = inst->getSrc(srcNum)->asSrcRegRegion()->getRegion(); if( rd->isRegionWH() ) { badRegion = true; break; } if( rd->horzStride == GENX_MAX_H_STRIDE && rd->width > 1 ) { badRegion = true; break; } G4_SrcRegRegion *expandSrcRegion = inst->getSrc(srcNum)->asSrcRegRegion(); if( expandSrcRegion->getRegAccess() != Direct ) { RegionDesc* origRegion = expandSrcRegion->getRegion(); short secondSubRegOffDiff = 0, secondAddrImmedDiff = 0; if( origRegion->width == 1 ) { secondSubRegOffDiff = origRegion->vertStride; } else { secondSubRegOffDiff = origRegion->horzStride; } secondAddrImmedDiff = (short) (secondSubRegOffDiff * G4_Type_Table[expandSrcRegion->getType()].byteSize); if( (expandSrcRegion->getAddrImm() + secondAddrImmedDiff) > G4_MAX_ADDR_IMM ) { badRegion = true; break; } } } return badRegion; } bool HWConformity::canSplitInst( G4_INST *inst, G4_INST *use_op ) { if( ( inst->getPredicate() && inst->getExecSize() < 16 ) || hasBadRegion( inst ) ) return false; G4_CondMod *condMod = inst->getCondMod(); if (condMod) { return false; } for (int i = 0; i < inst->getNumSrc(); i++) { G4_Operand *src = inst->getSrc(i); if (src->isAccReg()) { // don't split inst with explicit acc return false; } } return true; } bool HWConformity::canSplitByteDst( G4_opcode op ) { switch( op ) { case G4_mac: case G4_mach: case G4_cmp: case G4_mad: case G4_sad2: case G4_sada2: case G4_line: case G4_send: case G4_sendc: return false; default: return true; } } // split one instruction into 2 if its dstination is packed byte and execution type is W. // for example: // add <16> V1(0,0)<1>:b V1(0,0)<16;16,1>:w V2(0,0)<16;16,1>:w // ==> // add <8> V1(0,0)<2>:b V1(0,0)<16;8,2>:w V2(0,0)<16;8,2>:w // add <8> V1(0,1)<2>:b V1(0,1)<16;8,2>:w V2(0,1)<16;8,2>:w // if predicate is used for instruction, the definition of this predicate is tracked and the // corresponding instruction is checked to see if it can do the same split. bool HWConformity::splitInstListForByteDst( INST_LIST_ITER it, G4_BB *bb, uint16_t extypesize ) { G4_INST *inst = *it; G4_opcode inst_op = inst->opcode(); G4_DstRegRegion *dst = inst->getDst(); // check if we can split the inst if( !canSplitByteDst( inst_op ) || inst->getExecSize() == 1 || ( bb->isInSimdFlow() && !inst->isWriteEnableInst() ) || dst->getByteOffset() % extypesize != 0 || dst->getHorzStride() != 1 || extypesize != G4_Type_Table[Type_W].byteSize) { return false; } if (inst->getPredicate() || inst->getCondMod()) { return false; } // recursively the inst that defines its predicate can be split INST_LIST expandOpList; bool canSplit = canSplitInst( inst, NULL ); if( canSplit ) { expandOpList.push_back( inst ); } G4_INST *currInst = inst; while( canSplit && currInst->getPredicate() ) { // look for predicate def inst uint16_t defNum = 0; G4_INST *defInst = NULL; // FIXME: should be currInst->defInstList.begin()? for (auto def_iter = inst->def_begin(), end = inst->def_end(); def_iter != end; def_iter++) { if( (*def_iter).second == Opnd_pred ) { defNum++; defInst = (*def_iter).first; } } if( defNum != 1 || !defInst->getCondMod() ) { canSplit = false; break; } if( canSplit ) { if( bb->isInSimdFlow() && !defInst->isWriteEnableInst() ) { canSplit = false; } else { canSplit = canSplitInst( defInst, currInst ); } } // check if def inst can be split if( !canSplit ) { break; } else { expandOpList.push_back( defInst ); currInst = defInst; } } // split inst into two INST_LIST_ITER new_iter = it; new_iter++; if( canSplit ) { while( !expandOpList.empty() ) { G4_INST *expand_op = expandOpList.front(); expandOpList.pop_front(); // find location of expand_op in instruction list do { new_iter--; if( (*new_iter) == expand_op ) { break; } }while( new_iter != bb->begin() ); MUST_BE_TRUE( new_iter != bb->end(), "Cannot find predicate definition function in BB." ); new_iter++; G4_INST *secondHalfOp = splitInstWithByteDst( expand_op ); MUST_BE_TRUE( secondHalfOp, "Error in spliting instruction." ); bb->insert( new_iter, secondHalfOp ); } } return canSplit; } G4_INST* HWConformity::splitInstWithByteDst( G4_INST *expand_op ) { unsigned char newExecSize = expand_op->getExecSize()/2; if( expand_op->getPredicate() ) { expand_op->getPredicate()->splitPred(); } if( expand_op->getCondMod() ) { expand_op->getCondMod()->splitCondMod(); } G4_INST *expand_sec_half_op = builder.createInternalInst( builder.duplicateOperand( expand_op->getPredicate() ), expand_op->opcode(), builder.duplicateOperand( expand_op->getCondMod() ), expand_op->getSaturate(), newExecSize, NULL, NULL, NULL, NULL, expand_op->getOption(), expand_op->getLineNo(), expand_op->getCISAOff(), expand_op->getSrcFilename() ); MUST_BE_TRUE( expand_sec_half_op != NULL, ERROR_MEM_ALLOC ); expand_op->setExecSize( newExecSize ); if( expand_op->getDst() && !expand_op->hasNULLDst() ) { G4_DstRegRegion *old_dst = expand_op->getDst(); short secondSubRegOff = old_dst->getSubRegOff() + 1; G4_DstRegRegion *newDstOpnd = builder.createDstRegRegion( old_dst->getRegAccess(), old_dst->getBase(), old_dst->getRegOff(), old_dst->getSubRegOff(), old_dst->getHorzStride() * 2, old_dst->getType() ); if( old_dst->getRegAccess() != Direct ) { newDstOpnd->setImmAddrOff(old_dst->getAddrImm() ); secondSubRegOff -= 1; } expand_op->setDest( newDstOpnd ); G4_DstRegRegion *secondDstOpnd = builder.createDstRegRegion( old_dst->getRegAccess(), old_dst->getBase(), old_dst->getRegOff(), secondSubRegOff, old_dst->getHorzStride() * 2, old_dst->getType()); if( old_dst->getRegAccess() != Direct ) { secondDstOpnd->setImmAddrOff( old_dst->getAddrImm() + 1 ); } expand_sec_half_op->setDest( secondDstOpnd ); } else { expand_sec_half_op->setDest( expand_op->getDst() ); } for( int k = 0, n_srcs = G4_Inst_Table[expand_op->opcode()].n_srcs; k < n_srcs; k++ ) { G4_Operand *expand_src = expand_op->getSrc(k); if (!expand_src) continue; if ((expand_op->isMath() && k == 1 && expand_src->isNullReg()) || expand_src->isImm()) { expand_sec_half_op->setSrc(expand_src, k); } else if (expand_src->isSrcRegRegion()) { G4_SrcRegRegion *expandSrcRegion = expand_src->asSrcRegRegion(); if (expandSrcRegion->isScalar()) { expand_sec_half_op->setSrc(builder.duplicateOperand(expand_src), k); } else { short secondSubRegOffDiff = 0, secondAddrImmedDiff = 0; RegionDesc* origRegion = expandSrcRegion->getRegion(); RegionDesc* newRegion = NULL; if( origRegion->width == 1 ) { newRegion = builder.createRegionDesc( origRegion->vertStride * 2, origRegion->width, origRegion->horzStride ); secondSubRegOffDiff = origRegion->vertStride; } else { unsigned short newWD = origRegion->width/2; secondSubRegOffDiff = origRegion->horzStride; newRegion = builder.createRegionDesc( (newWD == 1 && newExecSize == 1) ? 0 : origRegion->vertStride, newWD, (newWD== 1) ? 0 : origRegion->horzStride * 2 ); } secondAddrImmedDiff = (short) (secondSubRegOffDiff * G4_Type_Table[expand_src->getType()].byteSize); expandSrcRegion->setRegion( newRegion ); bool directSrc = ( expandSrcRegion->getRegAccess() == Direct ); if( secondAddrImmedDiff >= GENX_GRF_REG_SIZ ) { secondSubRegOffDiff = (short) (( secondAddrImmedDiff - GENX_GRF_REG_SIZ ) / G4_Type_Table[expand_src->getType()].byteSize); } G4_SrcRegRegion *secondSrcOpnd = builder.createSrcRegRegion( expandSrcRegion->getModifier(), expandSrcRegion->getRegAccess(), expandSrcRegion->getBase(), expandSrcRegion->getRegOff() + ( ( directSrc && secondAddrImmedDiff >= GENX_GRF_REG_SIZ ) ? 1 : 0 ), expandSrcRegion->getSubRegOff() + ( directSrc ? secondSubRegOffDiff : 0 ), newRegion, expandSrcRegion->getType()); if (expandSrcRegion->getRegAccess() != Direct) { secondSrcOpnd->setImmAddrOff( expandSrcRegion->getAddrImm() + secondAddrImmedDiff ); } expand_sec_half_op->setSrc( secondSrcOpnd, k ); } } } expand_sec_half_op->setLineNo(expand_op->getLineNo()); if (expand_op->getPredicate() || expand_op->getCondMod()) { if (expand_op->getMaskOffset() == 0) { expand_sec_half_op->setMaskOption(InstOpt_M8); } else if(expand_op->getMaskOffset() == 16) { expand_sec_half_op->setMaskOption(InstOpt_M24); } else if(!( expand_op->opcode() == G4_sel && !(expand_op->getPredicate()) && expand_op->getCondMod())) { expand_sec_half_op->setMaskOption( newExecSize > 8 ? InstOpt_M16 : InstOpt_M8 ); } } return expand_sec_half_op; } // Fix up src regions in instructions: // In the component uncompressed instruction uop, // if exec size(uop) == width(src(uop)) && hstride(src(uop)) != 0 // vstride(src(uop)) = width(src(uop)) * hstride(src(uop)) // In the compressed instruction op, // if exec size(op) == width(src(op)) == vstride(src(op)) && // hstride(src(op)) == 1 // width(src(op)) = vstride(src(op)) = 8 // e.g. // mul (32) r60.0<1>:uw r76.0<32;16,1>:ub r78.0<0;1,0>:ub // => // mul (32) r60.0<1>:uw r76.0<16;16,1>:ub r78.0<0;1,0>:ub // add (16) r60.0<1>:d r76.0<16;16,1>:d r78.0<0;1,0>:d // => // add (16) r60.0<1>:d r76.0<8;8,1>:d r78.0<0;1,0>:d // in addition, fix the source region to follow the region restriction: // 1. ExecSize must be greater than or equal to Width. -- no check for this one // 2. If ExecSize = Width and HorzStride ? 0, VertStride must be set to Width * HorzStride. // 3. If ExecSize = Width and HorzStride = 0, there is no restriction on VertStride. // 4. If Width = 1, HorzStride must be 0 regardless of the values of ExecSize and VertStride. // 5. If ExecSize = Width = 1, both VertStride and HorzStride must be 0. This defines a scalar. // 6. If VertStride = HorzStride = 0, Width must be 1 regardless of the value of ExecSize. // 7. Dst.HorzStride must not be 0. -- this needs not to be checked. // 8. VertStride must be used to cross GRF register boundaries. This rule implies that // elements within a 'Width' cannot cross GRF boundaries. void HWConformity::fixSrcRegion( G4_INST *inst ) { bool comprInst = isCompressedInst( inst ); for (int i = 0; i < G4_MAX_SRCS; i++) { if (inst->getSrc(i) && inst->getSrc(i)->isSrcRegRegion() && !inst->getSrc(i)->isNullReg()) { G4_SrcRegRegion *src = inst->getSrc(i)->asSrcRegRegion(); RegionDesc* srcRegion = src->getRegion(); if( srcRegion->isRegionWH() || srcRegion->isRegionV() || srcRegion->isRegionSW() ) continue; uint16_t vs = srcRegion->vertStride, wd = srcRegion->width, hs = srcRegion->horzStride; uint8_t exSize = inst->getExecSize(); MUST_BE_TRUE( inst->isSend() || exSize >= wd, " Bad source region: Width is greater than execution size." ); if ( comprInst ) { if (G4_Type_Table[inst->getSrc(i)->getType()].byteSize > G4_WSIZE && wd == exSize && vs == wd && hs == 1) { vs = wd = exSize / 2; } } if( wd == exSize && hs != 0 && vs != wd * hs ) { vs = wd * hs; } if( wd == 1 ) { hs = 0; if( 1 == exSize ) vs = 0; } if( vs == 0 && hs == 0 ) { wd = 1; } if( hs == 0 && ((G4_Type_Table[inst->getSrc(i)->getType()].byteSize == G4_WSIZE && exSize == 32 && vs == 32 && wd == 32) || (G4_Type_Table[inst->getSrc(i)->getType()].byteSize == G4_DSIZE && exSize == 16 && vs == 16 && wd == 16)) ) { vs = 0; wd = 1; } // check cross GRF (rule 2H) // TODO! for the following two cases, split the instruction: // source region is like<8;4,1> // source region is like<2;4,1> if( src->getRegAccess() == Direct && src->crossGRF() && hs != 0) { // TODO: this is a temp fix if( (getGenxPlatform() == GENX_BDW || getGenxPlatform() == GENX_CHV) && vs < wd * hs ) continue; // check number of elements in first GRF. uint16_t execTypeSize = hs * src->getElemSize(); uint16_t sizeInFirstGRF = GENX_GRF_REG_SIZ - src->getLeftBound() % GENX_GRF_REG_SIZ; uint16_t vertSize = vs * G4_Type_Table[src->getType()].byteSize; uint16_t numEle = ( sizeInFirstGRF + execTypeSize - 1 ) / execTypeSize; uint16_t rowSize = wd * execTypeSize; if( sizeInFirstGRF <= vertSize ) { if( numEle >= wd ) { numEle = wd; } } else if( vs > wd ) { numEle = sizeInFirstGRF/vertSize * wd + (( sizeInFirstGRF%vertSize > rowSize ) ? wd : ( sizeInFirstGRF%vertSize + execTypeSize - 1 ) / execTypeSize ); } // wd is used to cross GRF, change to <vs;1,0> if( numEle < wd || ( wd >= vs && numEle % wd != 0 ) ) { wd = 1; if( hs == 0 ) { vs = 1; } else { vs = hs; } hs = 0; } } if( vs != srcRegion->vertStride || wd != srcRegion->width || hs != srcRegion->horzStride ) { G4_SrcRegRegion *origSrc = inst->getSrc(i)->asSrcRegRegion(); origSrc->setRegion( builder.createRegionDesc( vs, wd, hs ) ); } } } if( inst->getDst() && !inst->hasNULLDst() ) { MUST_BE_TRUE( inst->getDst()->getHorzStride() != 0, "Bad source region: Width is greater than execution size." ); } } // //single entry point for HW conformity checks // void HWConformityChk(IR_Builder& builder, G4_Kernel& kernel, Mem_Manager& mem ) { HWConformity conformity( builder, kernel, mem ); conformity.chkHWConformity(); } bool HWConformity::markPackedByteReference(G4_Kernel& kernel, G4_Operand* opnd, G4_INST* inst) { G4_Declare *dcl = NULL, *topdcl = NULL; bool foundOptCandidate = false; if ((opnd->isSrcRegRegion() || opnd->isDstRegRegion())) { if (opnd->getBase() && opnd->getBase()->isRegVar()) { dcl = opnd->getBase()->asRegVar()->getDeclare(); topdcl = dcl->getRootDeclare(); } } if (topdcl != NULL && topdcl->getRegFile() == G4_GRF && !(topdcl->getAddressed())) { if (topdcl->doNotWiden() || inst->mayExceedTwoGRF()) { //send has no regioning so it is certainly illegal to change data layout setAccessPattern(topdcl, ACCESS_PATTERN_INVALID); return false; } if (opnd->isDstRegRegion() && // check if the opnd has pre-assigned physical regsiter !(opnd->asDstRegRegion()->getBase()->asRegVar()->isPhyRegAssigned()) && // check if the opnd is global !(kernel.fg.globalOpndHT.isOpndGlobal(opnd)) && // check if the opnd is used as packed byte G4_Type_Table[opnd->getType()].byteSize == 1 && dcl->getElemSize() == 1 && opnd->asDstRegRegion()->getHorzStride() == 1 && // check if the instruction is a raw mov !inst->isRawMov() && // check if the instruction execution type is word // (This should be the most common case that can benefit // from this optimization. It could be extended to other // cases like D execution type). G4_Type_Table[inst->getExecType()].byteSize == 2 ) { unsigned int leftBound = opnd->asDstRegRegion()->getLeftBound(); unsigned int rightBound = opnd->asDstRegRegion()->getRightBound(); if (((rightBound*2/G4_GRF_REG_NBYTES - leftBound*2/G4_GRF_REG_NBYTES) > 1) || (getGenxPlatform() == GENX_BDW && (rightBound*2/G4_GRF_REG_NBYTES != leftBound*2/G4_GRF_REG_NBYTES))) { setAccessPattern(topdcl, ACCESS_PATTERN_INVALID); } else if (getAccessPattern(topdcl) == ACCESS_PATTERN_UNDEF) { setAccessPattern(topdcl, ACCESS_PATTERN_PACKED_BYTE); foundOptCandidate = true; } } else if (opnd->isSrcRegRegion() && // check if the opnd has pre-assigned physical regsiter !(opnd->asSrcRegRegion()->getBase()->asRegVar()->isPhyRegAssigned()) && // check if the opnd is global !(kernel.fg.globalOpndHT.isOpndGlobal(opnd)) && // check if the opnd is used as packed byte G4_Type_Table[opnd->getType()].byteSize == 1 && dcl->getElemSize() == 1 && opnd->asSrcRegRegion()->getRegion()->isContiguous(inst->getExecSize())) { unsigned int leftBound = opnd->asSrcRegRegion()->getLeftBound(); unsigned int rightBound = opnd->asSrcRegRegion()->getRightBound(); if (((rightBound*2/G4_GRF_REG_NBYTES - leftBound*2/G4_GRF_REG_NBYTES) > 1) || (getGenxPlatform() == GENX_BDW && (rightBound*2/G4_GRF_REG_NBYTES != leftBound*2/G4_GRF_REG_NBYTES))) { setAccessPattern(topdcl, ACCESS_PATTERN_INVALID); } } else { setAccessPattern(topdcl, ACCESS_PATTERN_INVALID); } } return foundOptCandidate; } G4_Operand* HWConformity::fixPackedByteReference(IR_Builder& builder, G4_Operand* opnd) { G4_Operand* newOpnd = NULL; G4_Declare* topdcl = NULL; if (opnd->isDstRegRegion() || opnd->isSrcRegRegion()) { topdcl = GetTopDclFromRegRegion(opnd); } if (topdcl != NULL && getAccessPattern(topdcl) == ACCESS_PATTERN_PACKED_BYTE) { if (opnd->isDstRegRegion()) { short dst_regoff = opnd->asDstRegRegion()->getRegOff(); short dst_subregoff = opnd->asDstRegRegion()->getSubRegOff(); short off = (dst_regoff * G4_GRF_REG_NBYTES + dst_subregoff) * 2; dst_regoff = off / G4_GRF_REG_NBYTES; dst_subregoff = off % G4_GRF_REG_NBYTES; G4_DstRegRegion* newDstOpnd = builder.createDstRegRegion( Direct, opnd->getBase()->asRegVar(), dst_regoff, dst_subregoff, 2, opnd->getType()); newOpnd = newDstOpnd; } else if (opnd->isSrcRegRegion()) { short src_regoff = opnd->asSrcRegRegion()->getRegOff(); short src_subregoff = opnd->asSrcRegRegion()->getSubRegOff(); short off = (src_regoff * G4_GRF_REG_NBYTES + src_subregoff) * 2; src_regoff = off / G4_GRF_REG_NBYTES; src_subregoff = off % G4_GRF_REG_NBYTES; RegionDesc *rd = builder.getRegionStride2(); G4_SrcRegRegion* newSrcOpnd = builder.createSrcRegRegion(opnd->asSrcRegRegion()->getModifier(), Direct, opnd->getBase()->asRegVar(), src_regoff, src_subregoff, rd, opnd->getType()); newOpnd = newSrcOpnd; } } return newOpnd; } void HWConformity::fixDataLayout( ) { bool changeDataLayout = false; for (auto &bb : kernel.fg) { for (auto &inst : *bb) { if (G4_Inst_Table[inst->opcode()].n_dst == 1) { G4_Operand* dst = inst->getDst(); if (dst) { bool foundOptCandidate = markPackedByteReference(kernel, dst, inst); if (changeDataLayout == false && foundOptCandidate) { changeDataLayout = true; } } } for (int i = 0; i < G4_Inst_Table[inst->opcode()].n_srcs; i++) { G4_Operand* src = inst->getSrc(i); if (src) { markPackedByteReference(kernel, src, inst); } } } } if (changeDataLayout) { for (auto &dcl : kernel.Declares) { G4_Declare* topdcl = dcl->getRootDeclare(); if (getAccessPattern(topdcl) == ACCESS_PATTERN_PACKED_BYTE) { dcl->setTotalElems(dcl->getTotalElems() * 2); if (dcl != topdcl) { G4_Declare* aliasDcl = dcl->getAliasDeclare(); unsigned int aliasOffset = dcl->getAliasOffset(); dcl->setAliasDeclare(aliasDcl, aliasOffset * 2); } } } for (auto &bb : kernel.fg) { for (auto &inst : *bb) { if (G4_Inst_Table[inst->opcode()].n_dst == 1) { G4_Operand* dst = inst->getDst(); G4_Operand* newDst = NULL; if (dst) { newDst = fixPackedByteReference(builder, dst); if (newDst) { inst->setDest(newDst->asDstRegRegion()); } } } for (int i = 0; i < inst->getNumSrc(); i++) { G4_Operand* src = inst->getSrc(i); G4_Operand* newSrc = NULL; if (src) { newSrc = fixPackedByteReference(builder, src); if (newSrc) { inst->setSrc(newSrc, i); } } } } } } } // maintain def-use chain for current inst and the MOV inst generated for its dst void HWConformity::maintainDU4TempMov( G4_INST *inst, G4_INST *newInst ) { if (newInst->getPredicate()) { inst->transferDef(newInst, Opnd_pred, Opnd_pred); } inst->transferUse(newInst); inst->addDefUse(newInst, Opnd_src0); } static void expandPlaneMacro(IR_Builder& builder, INST_LIST_ITER it, G4_BB* bb, bool secondHalf) { G4_INST* inst = *it; G4_DstRegRegion* dst = inst->getDst(); G4_SrcRegRegion* src0 = inst->getSrc(0)->asSrcRegRegion(); G4_SrcRegRegion* src1 = inst->getSrc(1)->asSrcRegRegion(); G4_SrcRegRegion* srcP = builder.createSrcRegRegion(src0->getModifier(), Direct, src0->getBase(), src0->getRegOff(), src0->getSubRegOff(), builder.getRegionScalar(), src0->getType()); G4_SrcRegRegion* srcQ = builder.createSrcRegRegion(src0->getModifier(), Direct, src0->getBase(), src0->getRegOff(), src0->getSubRegOff() + 1, builder.getRegionScalar(), src0->getType()); G4_SrcRegRegion* srcR = builder.createSrcRegRegion(src0->getModifier(), Direct, src0->getBase(), src0->getRegOff(), src0->getSubRegOff() + 3, builder.getRegionScalar(), src0->getType()); G4_SrcRegRegion* u = builder.duplicateOperand(src1); u->setRegOff(u->getRegOff() + (secondHalf ? 2 : 0)); G4_SrcRegRegion* v = builder.duplicateOperand(src1); v->setRegOff(v->getRegOff() + (secondHalf ? 3 : 1)); uint32_t options = inst->getOption(); if (inst->getExecSize() == 16) { options &= ~InstOpt_QuarterMasks; int maskOffset = inst->getMaskOffset() + (secondHalf ? 8 : 0); switch (maskOffset) { case 0: options |= InstOpt_M0; break; case 8: options |= InstOpt_M8; break; case 16: options |= InstOpt_M16; break; case 24: options |= InstOpt_M24; break; default: MUST_BE_TRUE(false, "unexpected offset value"); } } G4_Declare* tmpVal = builder.hasNFType() ? nullptr : builder.createTempVar(8, Type_F, Any); G4_DstRegRegion* accDst = builder.hasNFType() ? builder.createDstRegRegion(Direct, builder.phyregpool.getAcc0Reg(), 0, 0, 1, Type_NF) : builder.Create_Dst_Opnd_From_Dcl(tmpVal, 1); G4_INST* madInst = builder.createInternalInst(nullptr, G4_mad, nullptr, false, 8, accDst, srcR, u, srcP, options | InstOpt_WriteEnable); bb->insert(it, madInst); G4_Predicate* pred = inst->getPredicate() ? builder.duplicateOperand(inst->getPredicate()) : nullptr; G4_CondMod* condMod = inst->getCondMod() ? builder.duplicateOperand(inst->getCondMod()) : nullptr; G4_SrcRegRegion* accSrc = builder.hasNFType() ? builder.createSrcRegRegion(Mod_src_undef, Direct, builder.phyregpool.getAcc0Reg(), 0, 0, builder.getRegionStride1(), Type_NF) : builder.Create_Src_Opnd_From_Dcl(tmpVal, builder.getRegionStride1()); G4_DstRegRegion* newDst = builder.createDstRegRegion(Direct, dst->getBase(), dst->getRegOff() + (secondHalf ? 1 : 0), dst->getSubRegOff(), dst->getHorzStride(), dst->getType()); G4_INST* secondMadInst = builder.createInternalInst(pred, G4_mad, condMod, inst->getSaturate(), 8, newDst, accSrc, v, srcQ, options); bb->insert(it, secondMadInst); } // Replace plane with a macro sequence: // pln dest:f src0:f src1:f // --> // mad acc0:nf src0.3:f src1:f src0.0:f // mad dest:f acc0:nf src1+1:f src0.1:f // simd16 pln also needs to be split as the macro is simd8 only void HWConformity::expandPlaneInst(INST_LIST_ITER it, G4_BB* bb) { G4_INST* inst = *it; MUST_BE_TRUE(inst->opcode() == G4_pln, "expect a plane inst"); MUST_BE_TRUE(inst->getSrc(0)->isSrcRegRegion(), "src0 must be source reg region"); MUST_BE_TRUE(inst->getExecSize() == 8 || inst->getExecSize() == 16, " only size 8 and 16 are supported"); G4_DstRegRegion* dst = inst->getDst(); if (dst->getRegAccess() == IndirGRF || dst->getHorzStride() > 1) { inst->setDest(insertMovAfter(it, dst, dst->getType(), bb)); } G4_SrcRegRegion* src0 = inst->getSrc(0)->asSrcRegRegion(); if (src0->getRegAccess() == IndirGRF) { // insert move to make src0 direct inst->setSrc(insertMovBefore(it, 0, src0->getType(), bb), 0); } G4_SrcRegRegion* src1 = inst->getSrc(1)->asSrcRegRegion(); if (src1->getRegAccess() == IndirGRF) { // insert move to make src1 direct inst->setSrc(insertMovBefore(it, 1, src1->getType(), bb), 1); } expandPlaneMacro(builder, it, bb, false); if (inst->getExecSize() == 16) { expandPlaneMacro(builder, it, bb, true); } it = bb->erase(it); } // plane does not support pln with non-packed dst. // also fix up plane sources, which don't support modifiers // returns true if the original plane is deleted bool HWConformity::fixPlaneInst(INST_LIST_ITER it, G4_BB* bb) { G4_INST* inst = *it; if (inst->opcode() == G4_pln) { if (!builder.doPlane()) { expandPlaneInst(it, bb); return true; } G4_DstRegRegion* dst = inst->getDst(); if (dst->getHorzStride() != 1) { G4_DstRegRegion *newDst = insertMovAfter(it, dst, dst->getType(), bb); inst->setDest(newDst); } G4_Operand* src0 = inst->getSrc(0); G4_Operand* src1 = inst->getSrc(1); // Source modifiers are not supported for pln instruction if (src0 && ((src0->isSrcRegRegion() && src0->asSrcRegRegion()->getModifier() != Mod_src_undef) || !builder.isOpndAligned(src0, 16))) { // src0 needs a temp G4_Declare* tmpDcl = builder.createTempVar(4, Type_F, GRFALIGN); // Before: // pln (16) dst, (mod)src0, src1 // // After: // mov (4) tmp(0,0):f (mod)src0(r)<4;4,1>:f // pln (16) dst, tmp(0,0)<0;1,0>, src1 G4_DstRegRegion* dstRgn = builder.createDstRegRegion( Direct, tmpDcl->getRegVar(), 0, 0, 1, Type_F); RegionDesc* rd = builder.createRegionDesc(4, 4, 1); G4_SrcRegRegion* srcRgn = builder.createSrcRegRegion( src0->asSrcRegRegion()->getModifier(), Direct, src0->asSrcRegRegion()->getBase(), src0->asSrcRegRegion()->getRegOff(), src0->asSrcRegRegion()->getSubRegOff(), rd, Type_F); G4_INST* newInst = builder.createMov(4, dstRgn, srcRgn, InstOpt_NoOpt, false); bb->insert(it, newInst); rd = builder.getRegionScalar(); G4_SrcRegRegion* newSrcRgn = builder.createSrcRegRegion( Mod_src_undef, Direct, tmpDcl->getRegVar(), 0, 0, rd, Type_F); inst->setSrc(newSrcRgn, 0); inst->transferDef(newInst, Opnd_src0, Opnd_src0); newInst->addDefUse(inst, Opnd_src0); } if (src1 && src1->isSrcRegRegion() && src1->asSrcRegRegion()->getModifier() != Mod_src_undef) { // src1 needs a temp // For pln instruction src2 is implied from src1 and exec_size // When exec_size = 8, src2 is 1 GRF after src1 with size = 1 GRF // When exec_size = 16, src2 is 2 GRFs after src1 with size = 2 GRFs unsigned short numGRFsToCopy = inst->getExecSize() == 8 ? 2 : 4; G4_Declare* tmpDcl = builder.createTempVar((unsigned short)(G4_GRF_REG_NBYTES / G4_Type_Table[Type_F].byteSize * numGRFsToCopy), Type_F, Any); // Before: // pln (16) dst, src0, (mod)src1 // // After: // mov (16) tmp(0,0):f (mod)src1(r)<8;8,1>:f // mov (16) tmp(2,0):f (mod)src1(r+2)<8;8,1>:f <-- only if exec_size = 16 // pln (16) dst, src0, tmp(0,0) for (int i = 0; i < numGRFsToCopy; i += 2) { G4_DstRegRegion* dstRgn = builder.createDstRegRegion( Direct, tmpDcl->getRegVar(), (short)i, 0, 1, Type_F); RegionDesc* rd = builder.createRegionDesc(8, 8, 1); G4_SrcRegRegion* srcRgn = builder.createSrcRegRegion( src1->asSrcRegRegion()->getModifier(), Direct, src1->asSrcRegRegion()->getBase(), src1->asSrcRegRegion()->getRegOff() + i, 0, rd, Type_F); G4_INST* newInst = builder.createMov(16, dstRgn, srcRgn, InstOpt_NoOpt, false); bb->insert(it, newInst); if (i == 0) { G4_SrcRegRegion* newSrcRgn = builder.createSrcRegRegion( Mod_src_undef, Direct, tmpDcl->getRegVar(), 0, 0, rd, Type_F); inst->setSrc(newSrcRgn, 1); inst->transferDef(newInst, Opnd_src1, Opnd_src0); } newInst->addDefUse(inst, Opnd_src1); } } } return false; } void HWConformity::fixImm64 ( INST_LIST_ITER i, G4_BB* bb ) { G4_INST *inst = *i; for( int j = 0, n_srcs = G4_Inst_Table[inst->opcode()].n_srcs; j < n_srcs; j++ ) { G4_Operand *src = inst->getSrc(j); if( !src || !(src->isImm() ) || G4_Type_Table[src->getType()].byteSize != 8 ) { continue; } // a 64bit immediate is supported ONLY for a MOV operation bool needsSplit = false; if( VISA_WA_CHECK(builder.getPWaTable(), WaDisallow64BitImmMov) ) { needsSplit = true; } if (needsSplit) { char* immPtr = NULL; double dfValue = 0.0f; int64_t qValue = 0; if (IS_DFTYPE(src->getType())) { dfValue = src->asImm()->getDouble(); immPtr = (char*) &dfValue; } else { qValue = src->asImm()->getInt(); immPtr = (char*) &qValue; } unsigned int lowValue = *((unsigned int*)(immPtr)); unsigned int highValue = *((unsigned int*)(immPtr+4)); G4_Imm *lowImm = builder.createImm( (int64_t)lowValue, Type_UD); G4_Imm *highImm = builder.createImm( (int64_t)highValue, Type_UD); G4_Declare *defDcl = NULL; defDcl = builder.createTempVar(1, src->getType(), Eight_Word); G4_Declare* dcl = builder.createTempVar( 2, Type_UD, Eight_Word ); dcl->setAliasDeclare(defDcl, 0); G4_DstRegRegion *dstRegion = builder.Create_Dst_Opnd_From_Dcl(dcl, 1); G4_INST* lowMovInst = builder.createMov(1, dstRegion, lowImm, InstOpt_WriteEnable, false); bb->insert(i, lowMovInst); G4_DstRegRegion *dstRegionNext = builder.Create_Dst_Opnd_From_Dcl(dcl, 1); G4_INST *highMovInst = builder.createMov(1, dstRegionNext, highImm, InstOpt_WriteEnable, false); dstRegionNext->setSubRegOff(1); bb->insert(i, highMovInst); inst->transferDef(lowMovInst, Gen4_Operand_Number(j + 1), Opnd_src0); lowMovInst->addDefUse(inst, Gen4_Operand_Number(j + 1)); inst->transferDef(highMovInst, Gen4_Operand_Number(j + 1), Opnd_src0); highMovInst->addDefUse(inst, Gen4_Operand_Number(j + 1)); unsigned short vs = 0, hs = 0, wd = 1; // gen7_5: always 0;1,0 G4_SrcRegRegion *new_src = builder.Create_Src_Opnd_From_Dcl(defDcl, builder.createRegionDesc(vs, wd, hs)); inst->setSrc( new_src, j ); } else { if ( inst->opcode() != G4_mov ) { inst->setSrc(insertMovBefore(i, j, src->getType(), bb), j); } } } } // Check if the source of def_inst is redefined before inst G4_INST* HWConformity::checkSrcDefInst( G4_INST *inst, G4_INST *def_inst, uint32_t srcNum ) { G4_INST* valid_inst = def_inst; if( def_inst != NULL ) { MUST_BE_TRUE( def_inst->opcode() == G4_mov, "def inst must be a mov instruction" ); G4_INST* def_inst1 = NULL; for (auto def_it1 = inst->def_begin(), end = inst->def_end(); def_it1 != end; def_it1++ ) { if((*def_it1).second == srcNum + 1 ) { def_inst1 = (*def_it1).first; } } if( def_inst1 != NULL ) { G4_INST* def_inst2 = NULL; for (auto def_it2 = def_inst->def_begin(), end2 = def_inst->def_end(); def_it2 != end2; def_it2++ ) { if((*def_it2).second == Opnd_src0 ) { def_inst2 = (*def_it2).first; } } if ( def_inst1 != def_inst2 ) { valid_inst = NULL; } } } return valid_inst; } /* Helper function for fixMixedHFInst It assumes dst is not null and is of type DstRegRegion. This check must be done before this method is called. */ void HWConformity::helperGenerateTempDst( G4_BB* bb, INST_LIST_ITER instIter, G4_INST *inst, uint8_t hStride, G4_Type tempDstType, G4_SubReg_Align subAlign) { G4_DstRegRegion *dst = inst->getDst(); uint8_t execSize = inst->getExecSize(); uint8_t dstSize = execSize * G4_Type_Table[tempDstType].byteSize; //create a new temp with horizontal stride of 1 (packed) //create a move to dst. uint32_t numElt = execSize == 1 ? 1 : execSize * hStride; if (numElt > 1 && isLowPrecisionFloatTy(tempDstType) && hStride == 1 && subAlign < Eight_Word) subAlign = Eight_Word; subAlign = getDclAlignment( dstSize, inst, execSize == 1); G4_Declare* dcl = builder.createTempVar( numElt, tempDstType, subAlign ); G4_DstRegRegion *dstRegion = builder.Create_Dst_Opnd_From_Dcl(dcl, hStride); inst->setDest(dstRegion); RegionDesc* region = execSize == 1 ? builder.getRegionScalar() : builder.createRegionDesc(execSize*hStride, execSize, hStride); G4_SrcRegRegion *srcRegion = builder.Create_Src_Opnd_From_Dcl(dcl, region); //creating a mov from temp dst to final destination using original options of fixed instruction G4_INST* movInst = builder.createMov(execSize, dst, srcRegion, inst->getMaskOption(), false); ++instIter; //inserting mov after fixed instruction bb->insert( instIter, movInst ); /* Need to remove dst from uses list of mulh, and add them to movInst useList add movInst to uselist of mulh. Add mulh to def instruction list of movInst */ inst->transferUse(movInst); inst->addDefUse(movInst, Opnd_src0); } /* Not Implemented rules: 3: (Does this mean align1 doesn't support replication?) In Align16 mode, replicate is supported and is coissueable. 4: (handled in reduce execution size) No simd16 in mixed mode when destination is packed f16 for both Align1 and Align16. mad(8) r3.xyzw:hf r4.xyzw:f r6.xyzw:hf r7.xyzw:hf add(8) r20.0<1>:hf r3<8;8,1>:f r6.0<8;8,1>:hf {Q1} 5: (we are not producing this type of code) No accumulator read access for align16 mixed float 6: (we do not generate code like this) [DevCHV, DevSKL+]: When source is float from accumulator register and destination is half float with a stride of 1, the source must register aligned. i.e., source must have offset zero. 7: (doesn't seem like it is applicable to our code) In Align16, vertical stride can never be zero for f16 8.a: (handled by another check) Math operations for mixed mode, - In Align16, only packed format is supported 11. (handled in reduce execution size) [DevCHV, DevSKL, DevBXT]: No simd16 in mixed mode when destination is f32. Instruction Execution size must be no more than 8. */ void HWConformity::fixMixedHFInst(G4_BB* bb) { for (auto instIter = bb->begin(); instIter != bb->end(); ++instIter) { G4_INST *inst = *instIter; if (inst->mayExceedTwoGRF()) { continue; } if (inst->isMath() && builder.getOption(vISA_DisableHFMath)) { auto src0 = inst->getSrc(0); auto src1 = inst->getSrc(1); auto dst = inst->getDst(); if (src0 && src0->getType() == Type_HF) { inst->setSrc(insertMovBefore(instIter, 0, Type_F, bb), 0); } if (src1 && src1->getType() == Type_HF) { inst->setSrc(insertMovBefore(instIter, 1, Type_F, bb), 1); } if (dst && dst->getType() == Type_HF) { inst->setDest(insertMovAfter(instIter, dst, inst->getExecType2(), bb)); } continue; } if (VISA_WA_CHECK(builder.getPWaTable(), WaSrc1ImmHfNotAllowed)) { G4_Operand *tSrc1 = inst->getSrc(1); if (tSrc1 && tSrc1->isImm() && tSrc1->getType() == Type_HF) { inst->setSrc(insertMovBefore(instIter, 1, Type_HF, bb), 1); } } // The execution size must be no more than 8 when half-floats are used in source or destination operand. // ToDO: move this to fixmathinst if (inst->getExecSize() > builder.getNativeExecSize()) { if (inst->opcode() == G4_math && inst->getDst()->getType() == Type_HF && inst->getSrc(0)->getType() == Type_HF && (!inst->getSrc(1) || inst->getSrc(1)->getType() == Type_HF)) { evenlySplitInst(instIter, bb); } } G4_DstRegRegion *dst = inst->getDst(); if (INST_FLOAT_SRC_ONLY(inst->opcode()) && dst && !dst->isNullReg() && isLowPrecisionFloatTy(dst->getType())) { helperGenerateTempDst(bb, instIter, inst, 1, Type_F); } if (!inst->isMixedMode()) continue; if (inst->getDst() && !inst->getDst()->isNullReg()) dst = inst->getDst(); if ((VISA_WA_CHECK(builder.getPWaTable(), WaMixModeSelInstDstNotPacked) || VISA_WA_CHECK(builder.getPWaTable(), WaFloatMixedModeSelNotAllowedWithPackedDestination)) && inst->opcode() == G4_sel && dst && (VISA_WA_CHECK(builder.getPWaTable(), WaMixModeSelInstDstNotPacked) || dst->getHorzStride() == 1) && dst->getType() == Type_HF) { helperGenerateTempDst(bb, instIter, inst, 1, Type_F); } if (!inst->isMixedMode()) continue; if (getGenxPlatform() >= GENX_CHV) { // no SIMD16 mix mode instruction if (inst->getExecSize() > builder.getNativeExecSize() && inst->isMixedMode()) { evenlySplitInst(instIter, bb, false); //instruction was split, and new instruction inserted before //going back to previous instruction to double check it still confirms. --instIter; inst = *instIter; } } /* 12: [DevCHV, DevSKL]: Indirect Addressing on source is not supported when source and destination data types are mixed float. */ if (getGenxPlatform() == GENX_CHV || getGenxPlatform() == GENX_SKL) { for (uint8_t i = 0; i < inst->getNumSrc(); ++i) { G4_Operand* src = inst->getSrc(i); if (src == nullptr || !src->isSrcRegRegion() || !src->asSrcRegRegion()->isIndirect()) { continue; } inst->setSrc(insertMovBefore(instIter, i, src->getType(), bb), i); } } if (inst->getDst()->getBase()->isRegVar() && inst->getDst()->getType() == Type_HF && inst->getDst()->getHorzStride() == 1) { inst->getDst()->getBase()->asRegVar()->getDeclare()->setSubRegAlign(Eight_Word); } } } // Fix for packed half types on BDW. // Conversions from F to packed HF are not supported on this platform, // only unpacked HF is supported on destination. // When we encounter an instruction with HF type on destination with <1> stride // and float on source, add an additional mov that handles unpacking. void HWConformity::fixPackedHFConversions(INST_LIST_ITER it, G4_BB* bb) { G4_INST *inst = *it; G4_DstRegRegion* dst = inst->getDst(); if (dst && dst->getType() == Type_HF && dst->getHorzStride() == 1 && getTypeSize(inst->getExecType()) > 2) { helperGenerateTempDst(bb, it, inst, 2, Type_HF); } } void HWConformity::fixSrc2(INST_LIST_ITER it, G4_BB* bb, bool swapSrc0and2) { G4_INST* inst = *it; int srcPos = swapSrc0and2 ? 0 : 2; // unfortunate side effect of vISA mad and Gen mad having difference src order assert(inst->getNumSrc() == 3 && "expect 3-src inst"); if (builder.noSrc2Regioning()) { auto src = inst->getSrc(srcPos); // we have to make sure src2 and dst are aligned // Promote src2's type to f if mix mode is supported. // e.g., // mad (4) r10.0<1>:f src0 src1 r12.0<1>:hf --> f // mad (4) r10.0<2>:hf src0 src1 r12.0<1>:hf --> f // mad (4) r10.0<1>:hf src0 src1 r12.0<2>:hf --> hf // mad (4) r10.0<2>:hf src0 src1 r12.1<2>:hf --> f // ditto for 3-src inst with int types G4_Type srcTy = src->getType(); unsigned short dstEltSz = inst->getDst()->getExecTypeSize(); if (dstEltSz >= 4) { if (IS_SIGNED_INT(srcTy)) { srcTy = Type_D; } else if (IS_UNSIGNED_INT(srcTy)) { srcTy = Type_UD; } else if (builder.hasMixMode() && builder.getMixModeType() == srcTy) { // we can change operand type to F to save one move srcTy = Type_F; } } inst->setSrc(insertMovBefore(it, srcPos, srcTy, bb, GRFALIGN), srcPos); // Check if dst stride aligns with src2. if (dstEltSz != G4_Type_Table[srcTy].byteSize) { inst->setDest(insertMovAfter(it, inst->getDst(), inst->getDst()->getType(), bb, GRFALIGN)); } } } void HWConformity::fixVxHFloat64b(INST_LIST_ITER it, G4_BB* bb) { // at this point VxH region should only be on src0 G4_INST* inst = *it; G4_SrcRegRegion* src0 = inst->getSrc(0) && inst->getSrc(0)->isSrcRegRegion() ? inst->getSrc(0)->asSrcRegRegion() : nullptr; if (src0 && src0->getRegAccess() == IndirGRF && src0->getRegion()->isRegionWH()) { auto type = src0->getType(); if (type == Type_HF || type == Type_F) { auto intType = type == Type_HF ? Type_UW : Type_UD; if (inst->isRawMov()) { // directly change the dst/src type to int inst->getDst()->setType(intType); src0->setType(intType); } else { // generate a copy move using int type // FIXME: code is a bit hacky, may want to change insertMovBefore // so that we could specify the move type auto origType = src0->getType(); auto origMod = src0->getModifier(); src0->setType(intType); src0->setModifier(Mod_src_undef); auto newSrc = insertMovBefore(it, 0, intType, bb); newSrc->asSrcRegRegion()->setType(origType); newSrc->asSrcRegRegion()->setModifier(origMod); inst->setSrc(newSrc, 0); } } else if (getTypeSize(type) == 8) { int numDwords = inst->getExecSize() * 2; G4_Declare* tmpSrc = builder.createTempVar(numDwords / 2, src0->getType(), Any); RegionDesc* newRegion = builder.getRegionStride1(); copyDwordsIndirect(tmpSrc, src0, numDwords, bb, it); G4_SrcRegRegion* tmpSrcOpnd = builder.createSrcRegRegion(src0->getModifier(), Direct, tmpSrc->getRegVar(), 0, 0, newRegion, tmpSrc->getElemType()); inst->setSrc(tmpSrcOpnd, 0); } } } bool HWConformity::fixIntToHFMove(G4_BB* bb) { // int to HF move requires dst to have stride 2, which would result in // an illegal SIMD32 inst. So we split in this case // we put it in a separate pass so that the split instructions may be legalized later bool changed = false; for (auto I = bb->begin(), E = bb->end(); I != E; ++I) { auto inst = *I; if (inst->opcode() == G4_mov && inst->getDst()->getType() == Type_HF && IS_INT(inst->getSrc(0)->getType())) { if (inst->getExecSize() * 2 * 2 > getGRFSize() * 2) { evenlySplitInst(I, bb); changed = true; } } } return changed; }
268,914
87,583
// ========================================================================== // Munin Scroll Pane // // Copyright (C) 2011 Matthew Chaplain, All Rights Reserved. // // Permission to reproduce, distribute, perform, display, and to prepare // derivitive works from this file under the following conditions: // // 1. Any copy, reproduction or derivitive work of any part of this file // contains this copyright notice and licence in its entirety. // // 2. The rights granted to you under this license automatically terminate // should you attempt to assert any patent claims against the licensor // or contributors, which in any way restrict the ability of any party // from using this software or portions thereof in any form under the // terms of this license. // // Disclaimer: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY // KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS // OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR // OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // ========================================================================== #include "munin/scroll_pane.hpp" #include "munin/basic_frame.hpp" #include "munin/container.hpp" #include "munin/horizontal_scroll_bar.hpp" #include "munin/filled_box.hpp" #include "munin/framed_component.hpp" #include "munin/grid_layout.hpp" #include "munin/unicode_glyphs.hpp" #include "munin/vertical_scroll_bar.hpp" #include "munin/viewport.hpp" #include "terminalpp/element.hpp" #include <algorithm> namespace munin { namespace { class scroll_frame : public basic_frame { public : // ====================================================================== // CONSTRUCTOR // ====================================================================== scroll_frame( std::shared_ptr<horizontal_scroll_bar> const &hscroll_bar, std::shared_ptr<vertical_scroll_bar> const &vscroll_bar, bool top_border) : basic_frame( top_border ? make_fill(single_lined_rounded_top_left_corner) : std::shared_ptr<filled_box>(), top_border ? make_fill(single_lined_horizontal_beam) : std::shared_ptr<filled_box>(), top_border ? make_fill(single_lined_rounded_top_right_corner) : std::shared_ptr<filled_box>(), make_fill(single_lined_vertical_beam), vscroll_bar, make_fill(single_lined_rounded_bottom_left_corner), hscroll_bar, make_fill(single_lined_rounded_bottom_right_corner)) { } // ====================================================================== // DESTRUCTOR // ====================================================================== ~scroll_frame() { } }; } // ========================================================================== // SCROLL_PANE::IMPLEMENTATION STRUCTURE // ========================================================================== struct scroll_pane::impl { // ====================================================================== // CONSTRUCTOR // ====================================================================== impl(scroll_pane &self) : self_(self) { } scroll_pane &self_; std::shared_ptr<component> underlying_component_; std::shared_ptr<viewport> viewport_; std::shared_ptr<horizontal_scroll_bar> horizontal_scroll_bar_; std::shared_ptr<vertical_scroll_bar> vertical_scroll_bar_; std::shared_ptr<scroll_frame> scroll_frame_; // ====================================================================== // ON_PAGE_LEFT // ====================================================================== void on_page_left() { terminalpp::point new_origin; auto origin = viewport_->get_origin(); new_origin = origin; // TODO: Tab a page, not a line. if (new_origin.x != 0) { --new_origin.x; } viewport_->set_origin(new_origin); calculate_scrollbars(); } // ====================================================================== // ON_PAGE_RIGHT // ====================================================================== void on_page_right() { terminalpp::point new_origin; auto origin = viewport_->get_origin(); auto size = self_.get_size(); auto underlying_component_size = underlying_component_->get_size(); // Find out how far over to the right the maximum origin should be. // If the underlying component has a width smaller than this, then // the max is 0, because we can't scroll to the right. Otherwise, // it is the width of the underlying component - the width of the // viewport. auto max_right = (underlying_component_size.width < size.width ? 0 : underlying_component_size.width - size.width); // Same for the bottom, with height. auto max_bottom = (underlying_component_size.height < size.height ? 0 : underlying_component_size.height - size.height); // Now, move the origin over to the right by one page, up to the // maximum to the right. // new_origin.x = (min)(origin.x + size.width, max_right); new_origin.x = (std::min)(origin.x + 1, max_right); new_origin.y = (std::min)(origin.y, max_bottom); viewport_->set_origin(new_origin); calculate_scrollbars(); } // ====================================================================== // ON_PAGE_UP // ====================================================================== void on_page_up() { auto origin = viewport_->get_origin(); auto size = viewport_->get_size(); // If we would tab over the top of the viewport, then move to the // top instead. if (size.height >= origin.y) { origin.y = 0; } // Otherwise, move up by a page. else { origin.y -= size.height; } viewport_->set_origin(origin); } // ====================================================================== // ON_PAGE_DOWN // ====================================================================== void on_page_down() { terminalpp::point new_origin; auto origin = viewport_->get_origin(); auto size = viewport_->get_size(); auto underlying_component_size = underlying_component_->get_size(); // Find out how far over to the right the maximum origin should be. // If the underlying component has a width smaller than this, then // the max is 0, because we can't scroll to the right. Otherwise, // it is the width of the underlying component - the width of the // viewport. auto max_right = (underlying_component_size.width < size.width ? 0 : underlying_component_size.width - size.width); // Same for the bottom, with height. auto max_bottom = (underlying_component_size.height < size.height ? 0 : underlying_component_size.height - size.height); // Now, move the origin over to the right by one page, up to the // maximum to the right. new_origin.x = (std::min)(origin.x, max_right); new_origin.y = (std::min)(origin.y + size.height, max_bottom); viewport_->set_origin(new_origin); } // ====================================================================== // CALCULATE_HORIZONTAL_SCROLLBAR // ====================================================================== boost::optional<odin::u8> calculate_horizontal_scrollbar() { auto origin = viewport_->get_origin(); auto size = viewport_->get_size(); auto underlying_component_size = underlying_component_->get_size(); odin::u8 slider_position = 0; if (underlying_component_size.width <= size.width) { return {}; } if (origin.x != 0) { auto max_right = underlying_component_size.width - size.width; if (origin.x == max_right) { slider_position = 100; } else { slider_position = odin::u8((origin.x * 100) / max_right); if (slider_position == 0) { slider_position = 1; } if (slider_position == 100) { slider_position = 99; } } } return slider_position; } // ====================================================================== // CALCULATE_VERTICAL_SCROLLBAR // ====================================================================== boost::optional<odin::u8> calculate_vertical_scrollbar() { auto origin = viewport_->get_origin(); auto size = viewport_->get_size(); auto underlying_component_size = underlying_component_->get_size(); odin::u8 slider_position = 0; if (underlying_component_size.height <= size.height) { return {}; } if (origin.y != 0) { auto max_bottom = underlying_component_size.height - size.height; if (origin.y == max_bottom) { slider_position = 100; } else { slider_position = odin::u8((origin.y * 100) / max_bottom); if (slider_position == 0) { slider_position = 1; } if (slider_position == 100) { slider_position = 99; } } } return slider_position; } // ====================================================================== // CALCULATE_SCROLLBARS // ====================================================================== void calculate_scrollbars() { // Fix the scrollbars to be at the correct percentages. auto horizontal_slider_position = calculate_horizontal_scrollbar(); auto vertical_slider_position = calculate_vertical_scrollbar(); horizontal_scroll_bar_->set_slider_position(horizontal_slider_position); vertical_scroll_bar_->set_slider_position(vertical_slider_position); } }; // ========================================================================== // CONSTRUCTOR // ========================================================================== scroll_pane::scroll_pane( std::shared_ptr<component> const &underlying_component , bool top_border) { pimpl_ = std::make_shared<impl>(std::ref(*this)); pimpl_->underlying_component_ = underlying_component; pimpl_->viewport_ = make_viewport(pimpl_->underlying_component_); pimpl_->viewport_->on_size_changed.connect( [this]{pimpl_->calculate_scrollbars();}); pimpl_->viewport_->on_subcomponent_size_changed.connect( [this]{pimpl_->calculate_scrollbars();}); pimpl_->viewport_->on_origin_changed.connect( [this]{pimpl_->calculate_scrollbars();}); pimpl_->horizontal_scroll_bar_ = make_horizontal_scroll_bar(); pimpl_->horizontal_scroll_bar_->on_page_left.connect( [this]{pimpl_->on_page_left();}); pimpl_->horizontal_scroll_bar_->on_page_right.connect( [this]{pimpl_->on_page_right();}); pimpl_->vertical_scroll_bar_ = make_vertical_scroll_bar(); pimpl_->vertical_scroll_bar_->on_page_up.connect( [this]{pimpl_->on_page_up();}); pimpl_->vertical_scroll_bar_->on_page_down.connect( [this]{pimpl_->on_page_down();}); pimpl_->scroll_frame_ = std::make_shared<scroll_frame>( pimpl_->horizontal_scroll_bar_ , pimpl_->vertical_scroll_bar_ , top_border); auto content = get_container(); content->set_layout(make_grid_layout(1, 1)); content->add_component(make_framed_component( pimpl_->scroll_frame_ , pimpl_->viewport_)); } // ========================================================================== // DESTRUCTOR // ========================================================================== scroll_pane::~scroll_pane() { } // ========================================================================== // MAKE_SCROLL_PANE // ========================================================================== std::shared_ptr<component> make_scroll_pane( std::shared_ptr<component> const &underlying_component, bool top_border) { return std::make_shared<scroll_pane>(underlying_component, top_border); } }
13,683
3,822
/** * \file * \copyright * Copyright (c) 2012-2019, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #include "Output.h" #include <cassert> #include <fstream> #include <vector> #include <logog/include/logog.hpp> #include "Applications/InSituLib/Adaptor.h" #include "BaseLib/FileTools.h" #include "BaseLib/RunTime.h" #include "ProcessLib/Process.h" namespace { //! Converts a vtkXMLWriter's data mode string to an int. See /// Output::_output_file_data_mode. int convertVtkDataMode(std::string const& data_mode) { if (data_mode == "Ascii") { return 0; } if (data_mode == "Binary") { return 1; } if (data_mode == "Appended") { return 2; } OGS_FATAL( "Unsupported vtk output file data mode '%s'. Expected Ascii, " "Binary, or Appended.", data_mode.c_str()); } std::string constructFileName(std::string const& prefix, int const process_id, int const timestep, double const t) { return prefix + "_pcs_" + std::to_string(process_id) + "_ts_" + std::to_string(timestep) + "_t_" + std::to_string(t); } } // namespace namespace ProcessLib { bool Output::shallDoOutput(int timestep, double const t) { int each_steps = 1; for (auto const& pair : _repeats_each_steps) { each_steps = pair.each_steps; if (timestep > pair.repeat * each_steps) { timestep -= pair.repeat * each_steps; } else { break; } } bool make_output = timestep % each_steps == 0; if (_fixed_output_times.empty()) { return make_output; } const double specific_time = _fixed_output_times.back(); const double zero_threshold = std::numeric_limits<double>::min(); if (std::fabs(specific_time - t) < zero_threshold) { _fixed_output_times.pop_back(); make_output = true; } return make_output; } Output::Output(std::string output_directory, std::string output_file_prefix, bool const compress_output, std::string const& data_mode, bool const output_nonlinear_iteration_results, std::vector<PairRepeatEachSteps> repeats_each_steps, std::vector<double>&& fixed_output_times, ProcessOutput&& process_output, std::vector<std::string>&& mesh_names_for_output, std::vector<std::unique_ptr<MeshLib::Mesh>> const& meshes) : _output_directory(std::move(output_directory)), _output_file_prefix(std::move(output_file_prefix)), _output_file_compression(compress_output), _output_file_data_mode(convertVtkDataMode(data_mode)), _output_nonlinear_iteration_results(output_nonlinear_iteration_results), _repeats_each_steps(std::move(repeats_each_steps)), _fixed_output_times(std::move(fixed_output_times)), _process_output(std::move(process_output)), _mesh_names_for_output(mesh_names_for_output), _meshes(meshes) { } void Output::addProcess(ProcessLib::Process const& process, const int process_id) { auto const filename = BaseLib::joinPaths( _output_directory, _output_file_prefix + "_pcs_" + std::to_string(process_id) + ".pvd"); _process_to_process_data.emplace(std::piecewise_construct, std::forward_as_tuple(&process), std::forward_as_tuple(filename)); } // TODO return a reference. Output::ProcessData* Output::findProcessData(Process const& process, const int process_id) { auto range = _process_to_process_data.equal_range(&process); int counter = 0; ProcessData* process_data = nullptr; for (auto spd_it = range.first; spd_it != range.second; ++spd_it) { if (counter == process_id) { process_data = &spd_it->second; break; } counter++; } if (process_data == nullptr) { OGS_FATAL( "The given process is not contained in the output" " configuration. Aborting."); } return process_data; } struct Output::OutputFile { OutputFile(std::string const& directory, std::string const& prefix, int const process_id, int const timestep, double const t, int const data_mode_, bool const compression_) : name(constructFileName(prefix, process_id, timestep, t) + ".vtu"), path(BaseLib::joinPaths(directory, name)), data_mode(data_mode_), compression(compression_) { } std::string const name; std::string const path; //! Chooses vtk's data mode for output following the enumeration given /// in the vtkXMLWriter: {Ascii, Binary, Appended}. See vtkXMLWriter /// documentation /// http://www.vtk.org/doc/nightly/html/classvtkXMLWriter.html int const data_mode; //! Enables or disables zlib-compression of the output files. bool const compression; }; void Output::outputBulkMesh(OutputFile const& output_file, ProcessData* const process_data, MeshLib::Mesh const& mesh, double const t) const { DBUG("output to %s", output_file.path.c_str()); process_data->pvd_file.addVTUFile(output_file.name, t); makeOutput(output_file.path, mesh, output_file.compression, output_file.data_mode); } void Output::doOutputAlways(Process const& process, const int process_id, const int timestep, const double t, std::vector<GlobalVector*> const& x) { BaseLib::RunTime time_output; time_output.start(); std::vector<NumLib::LocalToGlobalIndexMap const*> dof_tables; dof_tables.reserve(x.size()); for (std::size_t i = 0; i < x.size(); ++i) { dof_tables.push_back(&process.getDOFTable(i)); } bool output_secondary_variable = true; // Need to add variables of process to vtu even no output takes place. processOutputData(t, x, process_id, process.getMesh(), dof_tables, process.getProcessVariables(process_id), process.getSecondaryVariables(), output_secondary_variable, process.getIntegrationPointWriter(), _process_output); // For the staggered scheme for the coupling, only the last process, which // gives the latest solution within a coupling loop, is allowed to make // output. if (!(process_id == static_cast<int>(_process_to_process_data.size()) - 1 || process.isMonolithicSchemeUsed())) { return; } auto output_bulk_mesh = [&]() { outputBulkMesh( OutputFile(_output_directory, _output_file_prefix, process_id, timestep, t, _output_file_data_mode, _output_file_compression), findProcessData(process, process_id), process.getMesh(), t); }; // Write the bulk mesh only if there are no other meshes specified for // output, otherwise only the specified meshes are written. if (_mesh_names_for_output.empty()) { output_bulk_mesh(); } for (auto const& mesh_output_name : _mesh_names_for_output) { if (process.getMesh().getName() == mesh_output_name) { output_bulk_mesh(); continue; } auto& mesh = *BaseLib::findElementOrError( begin(_meshes), end(_meshes), [&mesh_output_name](auto const& m) { return m->getName() == mesh_output_name; }, "Need mesh '" + mesh_output_name + "' for the output."); std::vector<MeshLib::Node*> const& nodes = mesh.getNodes(); DBUG( "Found %d nodes for output at mesh '%s'.", nodes.size(), mesh.getName().c_str()); MeshLib::MeshSubset mesh_subset(mesh, nodes); std::vector<std::unique_ptr<NumLib::LocalToGlobalIndexMap>> mesh_dof_tables; mesh_dof_tables.reserve(x.size()); for (std::size_t i = 0; i < x.size(); ++i) { mesh_dof_tables.push_back( process.getDOFTable(i).deriveBoundaryConstrainedMap( std::move(mesh_subset))); } std::vector<NumLib::LocalToGlobalIndexMap const*> mesh_dof_table_pointers; mesh_dof_table_pointers.reserve(mesh_dof_tables.size()); transform(cbegin(mesh_dof_tables), cend(mesh_dof_tables), back_inserter(mesh_dof_table_pointers), [](std::unique_ptr<NumLib::LocalToGlobalIndexMap> const& p) { return p.get(); }); output_secondary_variable = false; processOutputData(t, x, process_id, mesh, mesh_dof_table_pointers, process.getProcessVariables(process_id), process.getSecondaryVariables(), output_secondary_variable, process.getIntegrationPointWriter(), _process_output); // TODO (TomFischer): add pvd support here. This can be done if the // output is mesh related instead of process related. This would also // allow for merging bulk mesh output and arbitrary mesh output. OutputFile const output_file{_output_directory, mesh.getName(), process_id, timestep, t, _output_file_data_mode, _output_file_compression}; DBUG("output to %s", output_file.path.c_str()); makeOutput(output_file.path, mesh, output_file.compression, output_file.data_mode); } INFO("[time] Output of timestep %d took %g s.", timestep, time_output.elapsed()); } void Output::doOutput(Process const& process, const int process_id, const int timestep, const double t, std::vector<GlobalVector*> const& x) { if (shallDoOutput(timestep, t)) { doOutputAlways(process, process_id, timestep, t, x); } #ifdef USE_INSITU // Note: last time step may be output twice: here and in // doOutputLastTimestep() which throws a warning. InSituLib::CoProcess(process.getMesh(), t, timestep, false); #endif } void Output::doOutputLastTimestep(Process const& process, const int process_id, const int timestep, const double t, std::vector<GlobalVector*> const& x) { if (!shallDoOutput(timestep, t)) { doOutputAlways(process, process_id, timestep, t, x); } #ifdef USE_INSITU InSituLib::CoProcess(process.getMesh(), t, timestep, true); #endif } void Output::doOutputNonlinearIteration(Process const& process, const int process_id, const int timestep, const double t, std::vector<GlobalVector*> const& x, const int iteration) { if (!_output_nonlinear_iteration_results) { return; } BaseLib::RunTime time_output; time_output.start(); std::vector<NumLib::LocalToGlobalIndexMap const*> dof_tables; for (std::size_t i = 0; i < x.size(); ++i) { dof_tables.push_back(&process.getDOFTable(i)); } bool const output_secondary_variable = true; processOutputData(t, x, process_id, process.getMesh(), dof_tables, process.getProcessVariables(process_id), process.getSecondaryVariables(), output_secondary_variable, process.getIntegrationPointWriter(), _process_output); // For the staggered scheme for the coupling, only the last process, which // gives the latest solution within a coupling loop, is allowed to make // output. if (!(process_id == static_cast<int>(_process_to_process_data.size()) - 1 || process.isMonolithicSchemeUsed())) { return; } // Only check whether a process data is available for output. findProcessData(process, process_id); std::string const output_file_name = constructFileName(_output_file_prefix, process_id, timestep, t) + "_nliter_" + std::to_string(iteration) + ".vtu"; std::string const output_file_path = BaseLib::joinPaths(_output_directory, output_file_name); DBUG("output iteration results to %s", output_file_path.c_str()); INFO("[time] Output took %g s.", time_output.elapsed()); makeOutput(output_file_path, process.getMesh(), _output_file_compression, _output_file_data_mode); } } // namespace ProcessLib
13,417
3,973
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2008-2011 Bruno Lalande, Paris, France. // Copyright (c) 2008-2011 Barend Gehrels, Amsterdam, the Netherlands. // Copyright (c) 2009-2011 Mateusz Loskot, London, UK. // Parts of Boost.Geometry are redesigned from Geodan's Geographic Library // (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_GEOMETRY_CORE_ACCESS_HPP #define BOOST_GEOMETRY_CORE_ACCESS_HPP #include <cstddef> #include <boost/mpl/assert.hpp> #include <boost/type_traits/remove_const.hpp> #include <boost/concept_check.hpp> #include <boost/geometry/core/coordinate_type.hpp> #include <boost/geometry/core/point_type.hpp> #include <boost/geometry/core/tag.hpp> namespace boost { namespace geometry { /// Index of minimum corner of the box. int const min_corner = 0; /// Index of maximum corner of the box. int const max_corner = 1; namespace traits { /*! \brief Traits class which gives access (get,set) to points. \ingroup traits \par Geometries: /// @li point \par Specializations should provide, per Dimension /// @li static inline T get(G const&) /// @li static inline void set(G&, T const&) \tparam Geometry geometry-type \tparam Dimension dimension to access */ template <typename Geometry, std::size_t Dimension, typename Enable = void> struct access { BOOST_MPL_ASSERT_MSG ( false, NOT_IMPLEMENTED_FOR_THIS_POINT_TYPE, (types<Geometry>) ); }; /*! \brief Traits class defining "get" and "set" to get and set point coordinate values \tparam Geometry geometry (box, segment) \tparam Index index (min_corner/max_corner for box, 0/1 for segment) \tparam Dimension dimension \par Geometries: - box - segment \par Specializations should provide: - static inline T get(G const&) - static inline void set(G&, T const&) \ingroup traits */ template <typename Geometry, std::size_t Index, std::size_t Dimension> struct indexed_access {}; } // namespace traits #ifndef DOXYGEN_NO_DISPATCH namespace core_dispatch { template < typename Tag, typename Geometry, typename CoordinateType, std::size_t Dimension > struct access { //static inline T get(G const&) {} //static inline void set(G& g, T const& value) {} }; template < typename Tag, typename Geometry, typename CoordinateType, std::size_t Index, std::size_t Dimension > struct indexed_access { //static inline T get(G const&) {} //static inline void set(G& g, T const& value) {} }; template <typename Point, typename CoordinateType, std::size_t Dimension> struct access<point_tag, Point, CoordinateType, Dimension> { static inline CoordinateType get(Point const& point) { return traits::access<Point, Dimension>::get(point); } static inline void set(Point& p, CoordinateType const& value) { traits::access<Point, Dimension>::set(p, value); } }; template < typename Box, typename CoordinateType, std::size_t Index, std::size_t Dimension > struct indexed_access<box_tag, Box, CoordinateType, Index, Dimension> { static inline CoordinateType get(Box const& box) { return traits::indexed_access<Box, Index, Dimension>::get(box); } static inline void set(Box& b, CoordinateType const& value) { traits::indexed_access<Box, Index, Dimension>::set(b, value); } }; template < typename Segment, typename CoordinateType, std::size_t Index, std::size_t Dimension > struct indexed_access<segment_tag, Segment, CoordinateType, Index, Dimension> { static inline CoordinateType get(Segment const& segment) { return traits::indexed_access<Segment, Index, Dimension>::get(segment); } static inline void set(Segment& segment, CoordinateType const& value) { traits::indexed_access<Segment, Index, Dimension>::set(segment, value); } }; } // namespace core_dispatch #endif // DOXYGEN_NO_DISPATCH #ifndef DOXYGEN_NO_DETAIL namespace detail { // Two dummy tags to distinguish get/set variants below. // They don't have to be specified by the user. The functions are distinguished // by template signature also, but for e.g. GCC this is not enough. So give them // a different signature. struct signature_getset_dimension {}; struct signature_getset_index_dimension {}; } // namespace detail #endif // DOXYGEN_NO_DETAIL /*! \brief Get coordinate value of a geometry (usually a point) \details \details_get_set \ingroup get \tparam Dimension \tparam_dimension_required \tparam Geometry \tparam_geometry (usually a Point Concept) \param geometry \param_geometry (usually a point) \param dummy \qbk_skip \return The coordinate value of specified dimension of specified geometry \qbk{[include reference/core/get_point.qbk]} */ template <std::size_t Dimension, typename Geometry> inline typename coordinate_type<Geometry>::type get(Geometry const& geometry , detail::signature_getset_dimension* dummy = 0 ) { boost::ignore_unused_variable_warning(dummy); typedef typename boost::remove_const<Geometry>::type ncg_type; typedef core_dispatch::access < typename tag<Geometry>::type, ncg_type, typename coordinate_type<ncg_type>::type, Dimension > coord_access_type; return coord_access_type::get(geometry); } /*! \brief Set coordinate value of a geometry (usually a point) \details \details_get_set \tparam Dimension \tparam_dimension_required \tparam Geometry \tparam_geometry (usually a Point Concept) \param geometry geometry to assign coordinate to \param geometry \param_geometry (usually a point) \param value The coordinate value to set \param dummy \qbk_skip \ingroup set \qbk{[include reference/core/set_point.qbk]} */ template <std::size_t Dimension, typename Geometry> inline void set(Geometry& geometry , typename coordinate_type<Geometry>::type const& value , detail::signature_getset_dimension* dummy = 0 ) { boost::ignore_unused_variable_warning(dummy); typedef typename boost::remove_const<Geometry>::type ncg_type; typedef core_dispatch::access < typename tag<Geometry>::type, ncg_type, typename coordinate_type<ncg_type>::type, Dimension > coord_access_type; coord_access_type::set(geometry, value); } /*! \brief get coordinate value of a Box or Segment \details \details_get_set \tparam Index \tparam_index_required \tparam Dimension \tparam_dimension_required \tparam Geometry \tparam_box_or_segment \param geometry \param_geometry \param dummy \qbk_skip \return coordinate value \ingroup get \qbk{distinguish,with index} \qbk{[include reference/core/get_box.qbk]} */ template <std::size_t Index, std::size_t Dimension, typename Geometry> inline typename coordinate_type<Geometry>::type get(Geometry const& geometry , detail::signature_getset_index_dimension* dummy = 0 ) { boost::ignore_unused_variable_warning(dummy); typedef typename boost::remove_const<Geometry>::type ncg_type; typedef core_dispatch::indexed_access < typename tag<Geometry>::type, ncg_type, typename coordinate_type<ncg_type>::type, Index, Dimension > coord_access_type; return coord_access_type::get(geometry); } /*! \brief set coordinate value of a Box / Segment \details \details_get_set \tparam Index \tparam_index_required \tparam Dimension \tparam_dimension_required \tparam Geometry \tparam_box_or_segment \param geometry geometry to assign coordinate to \param geometry \param_geometry \param value The coordinate value to set \param dummy \qbk_skip \ingroup set \qbk{distinguish,with index} \qbk{[include reference/core/set_box.qbk]} */ template <std::size_t Index, std::size_t Dimension, typename Geometry> inline void set(Geometry& geometry , typename coordinate_type<Geometry>::type const& value , detail::signature_getset_index_dimension* dummy = 0 ) { boost::ignore_unused_variable_warning(dummy); typedef typename boost::remove_const<Geometry>::type ncg_type; typedef core_dispatch::indexed_access < typename tag<Geometry>::type, ncg_type, typename coordinate_type<ncg_type>::type, Index, Dimension > coord_access_type; coord_access_type::set(geometry, value); } }} // namespace boost::geometry #endif // BOOST_GEOMETRY_CORE_ACCESS_HPP
8,753
2,832
#include "Mapper001.h" Mapper001::Mapper001(int mapperNumber, int prgChunks, int chrChunks, std::vector<uint8_t>& prg, std::vector<uint8_t>& chr) : Mapper(mapperNumber, prgChunks, chrChunks, prg, chr) { sramSize = 0x2000; sram.resize(sramSize); Reset(); } Mapper001::Mapper001(Savestate& state, std::vector<uint8_t>& prg, std::vector<uint8_t>& chr) : Mapper(state, prg, chr) { sramSize = 0x2000; sram.resize(sramSize); shift = state.Pop<uint8_t>(); chrLo = state.Pop<uint8_t>(); chrHi = state.Pop<uint8_t>(); prgLo = state.Pop<uint8_t>(); ctrl = state.Pop<decltype(ctrl)>(); } Savestate Mapper001::SaveState() const { Savestate state = Mapper::SaveState(); state.Push<uint8_t>(shift); state.Push<uint8_t>(chrLo); state.Push<uint8_t>(chrHi); state.Push<uint8_t>(prgLo); state.Push<decltype(ctrl)>(ctrl); return state; } void Mapper001::Reset() { shift = 0b10000; ctrl.prgBankMode = 3; } MirrorMode Mapper001::GetMirrorMode() const { switch (ctrl.mirror) { case 0: return MirrorMode::OneScreenLo; case 1: return MirrorMode::OneScreenHi; case 2: return MirrorMode::Vertical; case 3: return MirrorMode::Horizontal; default: return MirrorMode::Hardwired; } } bool Mapper001::MapCpuRead(uint16_t& addr, uint8_t& data, bool readonly) { uint32_t newAddr; if (addr >= 0x6000 && addr < 0x8000) { data = sram[addr - 0x6000]; return true; } else if (addr >= 0x8000) { uint8_t bank = prgLo & 0x0F; switch (ctrl.prgBankMode) { case 0: case 1: newAddr = 0x8000 + ((bank & 0b1111'1110) * 0x4000) + (addr & 0x7FFF); break; case 2: if (addr < 0xC000) newAddr = 0x8000 + (addr & 0x3FFF); else newAddr = 0x8000 + (bank * 0x4000) + (addr & 0x3FFF); break; case 3: if (addr >= 0xC000) newAddr = 0x8000 + ((prgChunks - 1) * 0x4000) + (addr & 0x3FFF); else newAddr = 0x8000 + (bank * 0x4000) + (addr & 0x3FFF); break; } } else newAddr = addr; return Mapper::MapCpuRead(newAddr, data); } bool Mapper001::MapCpuWrite(uint16_t& addr, uint8_t data) { if (addr >= 0x6000 && addr < 0x8000) { sram[addr - 0x6000] = data; return true; } else if (addr >= 0x8000) { if (data & 0x80) { Reset(); } else { bool filled = shift & 1; shift = (shift >> 1) | ((data & 1) << 4); shift &= 0b11111; if (filled) { switch ((addr - 0x8000) / 0x2000) { case 0: ctrl.reg = shift; break; case 1: chrLo = shift; break; case 2: chrHi = shift; break; case 3: prgLo = shift; break; } shift = 0b10000; } } } return false; } bool Mapper001::MapPpuAddr(uint16_t& addr, uint32_t& newAddr) const { newAddr = addr; if (addr < 0x2000) { if (ctrl.chrBankMode == 0) { newAddr = ((chrLo & 0b1111'1110) * 0x1000) + (addr & 0x1FFF); } else { if (addr < 0x1000) newAddr = (chrLo * 0x1000) + (addr & 0x0FFF); else newAddr = (chrHi * 0x1000) + (addr & 0x0FFF); } return true; } return false; } bool Mapper001::MapPpuRead(uint16_t& addr, uint8_t& data, bool readonly) { uint32_t newAddr; if (MapPpuAddr(addr, newAddr)) { if (newAddr < chr.size()) data = chr[newAddr]; return true; } return false; } bool Mapper001::MapPpuWrite(uint16_t& addr, uint8_t data) { uint32_t newAddr; if (MapPpuAddr(addr, newAddr)) { if (newAddr < chr.size()) chr[newAddr] = data; return true; } return false; }
3,382
1,805
//============================================================================== // Copyright 2003 & onward LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 & onward LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef NT2_TOOLBOX_LINALG_FUNCTIONS_COV_HPP_INCLUDED #define NT2_TOOLBOX_LINALG_FUNCTIONS_COV_HPP_INCLUDED #include <nt2/include/functor.hpp> #include <nt2/include/functions/sqr_abs.hpp> #include <boost/simd/toolbox/constant/constants/zero.hpp> namespace nt2 { namespace tag { /*! * \brief Define the tag expm_ of functor expm * in namespace nt2::tag for toolbox algebra **/ struct cov_ : tag::formal_ { typedef tag::formal_ parent; }; } /** * @brief compute covariance matrix expression * * If x is a vector, cov(x) returns the variance * For matrices, where each row is an observation, and each column a variable, * cov(x) is the covariance matrix. diag(cov(x)) is a vector of * variances for each column, and sqrt(diag(cov(x))) is a vector * of standard deviations. * cov(x,y), where x and y are matrices with the same number of elements, * is equivalent to cov(horzcat(x(_) y(_))). * * cov(x) or cov(x,y) normalizes by (n-1) if n>1, where n is the number of * observations. this makes cov(x) the best unbiased estimate of the * covariance matrix if the observations are from a normal distribution. * for n=1, cov normalizes by n. * * cov(x,1) or cov(x,y,1) normalizes by n and produces the second * moment matrix of the observations about their mean. cov(x,y,0) is * the same as cov(x,y) and cov(x,0) is the same as cov(x). * * the mean is removed from each column before calculating the * result. * **/ NT2_FUNCTION_IMPLEMENTATION(nt2::tag::cov_ , cov, 1) NT2_FUNCTION_IMPLEMENTATION(nt2::tag::cov_ , cov, 2) NT2_FUNCTION_IMPLEMENTATION(nt2::tag::cov_ , cov, 3) } #endif
2,238
785
#include <iostream> #include <numeric> #include <fstream> #include <sstream> #include <vector> using namespace std; class Rational { public: Rational() { numerator = 0; denominator = 1; } Rational(int numerator, int denominator) { if (denominator == 0) { throw invalid_argument("Invalid argument: denominator = 0"); } if (numerator == 0) { this->numerator = 0; this->denominator = 1; } else if (denominator < 0) { this->numerator = numerator * -1; this->denominator = denominator * -1; } else { this->numerator = numerator; this->denominator = denominator; } int tmp_gcd = gcd(this->numerator, this->denominator); this->numerator /= tmp_gcd; this->denominator /= tmp_gcd; } int Numerator() const { return numerator; } int Denominator() const { return denominator; } private: int numerator; int denominator; }; bool operator==(const Rational& num1, const Rational& num2) { return num1.Numerator() == num2.Numerator() && num1.Denominator() == num2.Denominator(); } Rational operator+(const Rational& num1, const Rational& num2) { int new_numerator = num1.Numerator() * num2.Denominator() + num2.Numerator() * num1.Denominator(); int new_denominator = num1.Denominator() * num2.Denominator(); return Rational(new_numerator, new_denominator); } Rational operator-(const Rational& num1, const Rational& num2) { int new_numerator = num1.Numerator() * num2.Denominator() - num2.Numerator() * num1.Denominator(); int new_denominator = num1.Denominator() * num2.Denominator(); return Rational(new_numerator, new_denominator); } Rational operator*(const Rational& num1, const Rational& num2) { int new_numerator = num1.Numerator() * num2.Numerator(); int new_denominator = num1.Denominator() * num2.Denominator(); return Rational(new_numerator, new_denominator); } Rational operator/(const Rational& num1, const Rational& num2) { if (num2.Numerator() == 0) { throw domain_error("Dived by 0"); } int new_numerator = num1.Numerator() * num2.Denominator(); int new_denominator = num1.Denominator() * num2.Numerator(); return Rational(new_numerator, new_denominator); } ostream& operator<<(ostream& stream, const Rational& number) { stream << number.Numerator() << "/" << number.Denominator(); return stream; } bool operator<(const Rational& lhs, const Rational& rhs) { return lhs.Numerator() * rhs.Denominator() < rhs.Numerator() * lhs.Denominator(); } istream& operator>>(istream& stream, Rational& number) { if (stream.tellg() == -1) return stream; int new_numerator = 0; int new_denominator = 1; char new_delim; stream >> new_numerator >> new_delim >> new_denominator; if (new_delim == '/') { number = Rational(new_numerator, new_denominator); } return stream; } int main() { try { Rational r(1, 0); cout << "Doesn't throw in case of zero denominator" << endl; return 1; } catch (invalid_argument&) { } try { auto r1 = Rational(1, 2); auto r2 = Rational(0, 1); auto x = r1 / r2; cout << "Doesn't throw in case of division by zero" << endl; return 2; } catch (domain_error&) { } cout << "OK" << endl; return 0; }
3,548
1,226
// Generated by the gRPC C++ plugin. // If you make any local change, they will be lost. // source: google/devtools/cloudtrace/v1/trace.proto #include "google/devtools/cloudtrace/v1/trace.pb.h" #include "google/devtools/cloudtrace/v1/trace.grpc.pb.h" #include <grpcpp/impl/codegen/async_stream.h> #include <grpcpp/impl/codegen/async_unary_call.h> #include <grpcpp/impl/codegen/channel_interface.h> #include <grpcpp/impl/codegen/client_unary_call.h> #include <grpcpp/impl/codegen/method_handler_impl.h> #include <grpcpp/impl/codegen/rpc_service_method.h> #include <grpcpp/impl/codegen/service_type.h> #include <grpcpp/impl/codegen/sync_stream.h> namespace google { namespace devtools { namespace cloudtrace { namespace v1 { static const char* TraceService_method_names[] = { "/google.devtools.cloudtrace.v1.TraceService/ListTraces", "/google.devtools.cloudtrace.v1.TraceService/GetTrace", "/google.devtools.cloudtrace.v1.TraceService/PatchTraces", }; std::unique_ptr< TraceService::Stub> TraceService::NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options) { (void)options; std::unique_ptr< TraceService::Stub> stub(new TraceService::Stub(channel)); return stub; } TraceService::Stub::Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel) : channel_(channel), rpcmethod_ListTraces_(TraceService_method_names[0], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_GetTrace_(TraceService_method_names[1], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_PatchTraces_(TraceService_method_names[2], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) {} ::grpc::Status TraceService::Stub::ListTraces(::grpc::ClientContext* context, const ::google::devtools::cloudtrace::v1::ListTracesRequest& request, ::google::devtools::cloudtrace::v1::ListTracesResponse* response) { return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_ListTraces_, context, request, response); } ::grpc::ClientAsyncResponseReader< ::google::devtools::cloudtrace::v1::ListTracesResponse>* TraceService::Stub::AsyncListTracesRaw(::grpc::ClientContext* context, const ::google::devtools::cloudtrace::v1::ListTracesRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderFactory< ::google::devtools::cloudtrace::v1::ListTracesResponse>::Create(channel_.get(), cq, rpcmethod_ListTraces_, context, request, true); } ::grpc::ClientAsyncResponseReader< ::google::devtools::cloudtrace::v1::ListTracesResponse>* TraceService::Stub::PrepareAsyncListTracesRaw(::grpc::ClientContext* context, const ::google::devtools::cloudtrace::v1::ListTracesRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderFactory< ::google::devtools::cloudtrace::v1::ListTracesResponse>::Create(channel_.get(), cq, rpcmethod_ListTraces_, context, request, false); } ::grpc::Status TraceService::Stub::GetTrace(::grpc::ClientContext* context, const ::google::devtools::cloudtrace::v1::GetTraceRequest& request, ::google::devtools::cloudtrace::v1::Trace* response) { return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_GetTrace_, context, request, response); } ::grpc::ClientAsyncResponseReader< ::google::devtools::cloudtrace::v1::Trace>* TraceService::Stub::AsyncGetTraceRaw(::grpc::ClientContext* context, const ::google::devtools::cloudtrace::v1::GetTraceRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderFactory< ::google::devtools::cloudtrace::v1::Trace>::Create(channel_.get(), cq, rpcmethod_GetTrace_, context, request, true); } ::grpc::ClientAsyncResponseReader< ::google::devtools::cloudtrace::v1::Trace>* TraceService::Stub::PrepareAsyncGetTraceRaw(::grpc::ClientContext* context, const ::google::devtools::cloudtrace::v1::GetTraceRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderFactory< ::google::devtools::cloudtrace::v1::Trace>::Create(channel_.get(), cq, rpcmethod_GetTrace_, context, request, false); } ::grpc::Status TraceService::Stub::PatchTraces(::grpc::ClientContext* context, const ::google::devtools::cloudtrace::v1::PatchTracesRequest& request, ::google::protobuf::Empty* response) { return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_PatchTraces_, context, request, response); } ::grpc::ClientAsyncResponseReader< ::google::protobuf::Empty>* TraceService::Stub::AsyncPatchTracesRaw(::grpc::ClientContext* context, const ::google::devtools::cloudtrace::v1::PatchTracesRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderFactory< ::google::protobuf::Empty>::Create(channel_.get(), cq, rpcmethod_PatchTraces_, context, request, true); } ::grpc::ClientAsyncResponseReader< ::google::protobuf::Empty>* TraceService::Stub::PrepareAsyncPatchTracesRaw(::grpc::ClientContext* context, const ::google::devtools::cloudtrace::v1::PatchTracesRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderFactory< ::google::protobuf::Empty>::Create(channel_.get(), cq, rpcmethod_PatchTraces_, context, request, false); } TraceService::Service::Service() { AddMethod(new ::grpc::internal::RpcServiceMethod( TraceService_method_names[0], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< TraceService::Service, ::google::devtools::cloudtrace::v1::ListTracesRequest, ::google::devtools::cloudtrace::v1::ListTracesResponse>( std::mem_fn(&TraceService::Service::ListTraces), this))); AddMethod(new ::grpc::internal::RpcServiceMethod( TraceService_method_names[1], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< TraceService::Service, ::google::devtools::cloudtrace::v1::GetTraceRequest, ::google::devtools::cloudtrace::v1::Trace>( std::mem_fn(&TraceService::Service::GetTrace), this))); AddMethod(new ::grpc::internal::RpcServiceMethod( TraceService_method_names[2], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< TraceService::Service, ::google::devtools::cloudtrace::v1::PatchTracesRequest, ::google::protobuf::Empty>( std::mem_fn(&TraceService::Service::PatchTraces), this))); } TraceService::Service::~Service() { } ::grpc::Status TraceService::Service::ListTraces(::grpc::ServerContext* context, const ::google::devtools::cloudtrace::v1::ListTracesRequest* request, ::google::devtools::cloudtrace::v1::ListTracesResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status TraceService::Service::GetTrace(::grpc::ServerContext* context, const ::google::devtools::cloudtrace::v1::GetTraceRequest* request, ::google::devtools::cloudtrace::v1::Trace* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status TraceService::Service::PatchTraces(::grpc::ServerContext* context, const ::google::devtools::cloudtrace::v1::PatchTracesRequest* request, ::google::protobuf::Empty* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } } // namespace google } // namespace devtools } // namespace cloudtrace } // namespace v1
7,476
2,419
/**************************************************************************** * * Copyright (C) 2012, 2013 PX4 Development Team. All rights reserved. * Author: Randy Mackay <rmackay9@yahoo.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file oreoled.cpp * * Driver for oreoled ESCs found in solo, connected via I2C. * */ #include <px4_config.h> #include <drivers/device/i2c.h> #include <drivers/drv_hrt.h> #include <sys/types.h> #include <stdint.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <ctype.h> #include <sys/stat.h> #include <nuttx/arch.h> #include <nuttx/wqueue.h> #include <nuttx/clock.h> #include <systemlib/perf_counter.h> #include <systemlib/err.h> #include <systemlib/systemlib.h> #include <board_config.h> #include <drivers/drv_oreoled.h> #include <drivers/device/ringbuffer.h> #define OREOLED_NUM_LEDS 4 ///< maximum number of LEDs the oreo led driver can support #define OREOLED_BASE_I2C_ADDR 0x68 ///< base i2c address (7-bit) #define OPEOLED_I2C_RETRYCOUNT 2 ///< i2c retry count #define OREOLED_TIMEOUT_USEC 2000000U ///< timeout looking for oreoleds 2 seconds after startup #define OREOLED_GENERALCALL_US 4000000U ///< general call sent every 4 seconds #define OREOLED_GENERALCALL_CMD 0x00 ///< general call command sent at regular intervals #define OREOLED_STARTUP_INTERVAL_US (1000000U / 10U) ///< time in microseconds, measure at 10hz #define OREOLED_UPDATE_INTERVAL_US (1000000U / 50U) ///< time in microseconds, measure at 10hz #define OREOLED_CMD_QUEUE_SIZE 10 ///< up to 10 messages can be queued up to send to the LEDs class OREOLED : public device::I2C { public: OREOLED(int bus, int i2c_addr, bool autoupdate, bool alwaysupdate); virtual ~OREOLED(); virtual int init(); virtual int probe(); virtual int info(); virtual int ioctl(struct file *filp, int cmd, unsigned long arg); /* send general call on I2C bus to syncronise all LEDs */ int send_general_call(); /* send cmd to an LEDs (used for testing only) */ int send_cmd(oreoled_cmd_t sb); /* returns true once the driver finished bootloading and ready for commands */ bool is_ready(); private: /** * Start periodic updates to the LEDs */ void start(); /** * Stop periodic updates to the LEDs */ void stop(); /** * static function that is called by worker queue */ static void cycle_trampoline(void *arg); /** * update the colours displayed by the LEDs */ void cycle(); int bootloader_app_reset(int led_num); int bootloader_app_ping(int led_num); uint16_t bootloader_inapp_checksum(int led_num); int bootloader_ping(int led_num); uint8_t bootloader_version(int led_num); uint16_t bootloader_app_version(int led_num); uint16_t bootloader_app_checksum(int led_num); int bootloader_set_colour(int led_num, uint8_t red, uint8_t green); int bootloader_flash(int led_num); int bootloader_boot(int led_num); uint16_t bootloader_fw_checksum(void); int bootloader_coerce_healthy(void); /* internal variables */ work_s _work; ///< work queue for scheduling reads bool _healthy[OREOLED_NUM_LEDS]; ///< health of each LED bool _in_boot[OREOLED_NUM_LEDS]; ///< true for each LED that is in bootloader mode uint8_t _num_healthy; ///< number of healthy LEDs ringbuffer::RingBuffer *_cmd_queue; ///< buffer of commands to send to LEDs uint8_t _num_inboot; ///< number of LEDs in bootloader uint64_t _last_gencall; uint64_t _start_time; ///< system time we first attempt to communicate with battery bool _autoupdate; ///< true if the driver should update all LEDs bool _alwaysupdate; ///< true if the driver should update all LEDs bool _is_bootloading; ///< true if a bootloading operation is in progress bool _is_ready; ///< set to true once the driver has completly initialised uint16_t _fw_checksum; ///< the current 16bit XOR checksum of the built in oreoled firmware binary /* performance checking */ perf_counter_t _call_perf; perf_counter_t _gcall_perf; perf_counter_t _probe_perf; perf_counter_t _comms_errors; perf_counter_t _reply_errors; }; /* for now, we only support one OREOLED */ namespace { OREOLED *g_oreoled = nullptr; } void oreoled_usage(); extern "C" __EXPORT int oreoled_main(int argc, char *argv[]); /* constructor */ OREOLED::OREOLED(int bus, int i2c_addr, bool autoupdate, bool alwaysupdate) : I2C("oreoled", OREOLED0_DEVICE_PATH, bus, i2c_addr, 100000), _work{}, _num_healthy(0), _num_inboot(0), _cmd_queue(nullptr), _last_gencall(0), _autoupdate(autoupdate), _alwaysupdate(alwaysupdate), _is_bootloading(false), _is_ready(false), _fw_checksum(0x0000), _call_perf(perf_alloc(PC_ELAPSED, "oreoled_call")), _gcall_perf(perf_alloc(PC_ELAPSED, "oreoled_gcall")), _probe_perf(perf_alloc(PC_ELAPSED, "oreoled_probe")), _comms_errors(perf_alloc(PC_COUNT, "oreoled_comms_errors")), _reply_errors(perf_alloc(PC_COUNT, "oreoled_reply_errors")) { /* initialise to unhealthy */ memset(_healthy, 0, sizeof(_healthy)); /* initialise to in application */ memset(_in_boot, 0, sizeof(_in_boot)); /* capture startup time */ _start_time = hrt_absolute_time(); } /* destructor */ OREOLED::~OREOLED() { /* make sure we are truly inactive */ stop(); /* clear command queue */ if (_cmd_queue != nullptr) { delete _cmd_queue; } /* free perf counters */ perf_free(_call_perf); perf_free(_gcall_perf); perf_free(_probe_perf); perf_free(_comms_errors); perf_free(_reply_errors); } int OREOLED::init() { int ret; /* initialise I2C bus */ ret = I2C::init(); if (ret != OK) { return ret; } /* allocate command queue */ _cmd_queue = new ringbuffer::RingBuffer(OREOLED_CMD_QUEUE_SIZE, sizeof(oreoled_cmd_t)); if (_cmd_queue == nullptr) { return ENOTTY; } else { /* start work queue */ start(); } return OK; } int OREOLED::probe() { /* set retry count */ _retries = OPEOLED_I2C_RETRYCOUNT; /* always return true */ return OK; } int OREOLED::info() { /* print health info on each LED */ for (uint8_t i = 0; i < OREOLED_NUM_LEDS; i++) { if (!_healthy[i]) { DEVICE_LOG("oreo %u: BAD", (unsigned)i); } else { DEVICE_LOG("oreo %u: OK", (unsigned)i); } } /* display perf info */ perf_print_counter(_call_perf); perf_print_counter(_gcall_perf); perf_print_counter(_probe_perf); perf_print_counter(_comms_errors); perf_print_counter(_reply_errors); return OK; } void OREOLED::start() { /* schedule a cycle to start things */ work_queue(HPWORK, &_work, (worker_t)&OREOLED::cycle_trampoline, this, 1); } void OREOLED::stop() { work_cancel(HPWORK, &_work); } void OREOLED::cycle_trampoline(void *arg) { OREOLED *dev = (OREOLED *)arg; /* check global oreoled and cycle */ if (g_oreoled != nullptr) { dev->cycle(); } } void OREOLED::cycle() { /* check time since startup */ uint64_t now = hrt_absolute_time(); bool startup_timeout = (now - _start_time > OREOLED_TIMEOUT_USEC); /* prepare the response buffer */ uint8_t reply[OREOLED_CMD_READ_LENGTH_MAX]; /* during startup period keep searching for unhealthy LEDs */ if (!startup_timeout && _num_healthy < OREOLED_NUM_LEDS) { /* prepare command to turn off LED */ /* add two bytes of pre-amble to for higher signal to noise ratio */ uint8_t msg[] = {0xAA, 0x55, OREOLED_PATTERN_OFF, 0x00}; /* attempt to contact each unhealthy LED */ for (uint8_t i = 0; i < OREOLED_NUM_LEDS; i++) { if (!_healthy[i]) { perf_begin(_probe_perf); /* set I2C address */ set_address(OREOLED_BASE_I2C_ADDR + i); /* Calculate XOR CRC and append to the i2c write data */ msg[sizeof(msg) - 1] = OREOLED_BASE_I2C_ADDR + i; for (uint8_t j = 0; j < sizeof(msg) - 1; j++) { msg[sizeof(msg) - 1] ^= msg[j]; } /* send I2C command */ if (transfer(msg, sizeof(msg), reply, 3) == OK) { if (reply[1] == OREOLED_BASE_I2C_ADDR + i && reply[2] == msg[sizeof(msg) - 1]) { DEVICE_LOG("oreoled %u ok - in bootloader", (unsigned)i); _healthy[i] = true; _num_healthy++; /* If slaves are in application record that so we can reset if we need to bootload */ /* This additional check is required for LED firmwares below v1.3 and can be deprecated once all LEDs in the wild have firmware >= v1.3 */ if (bootloader_ping(i) == OK) { _in_boot[i] = true; _num_inboot++; } /* Check for a reply with a checksum offset of 1, which indicates a response from firmwares >= 1.3 */ } else if (reply[1] == OREOLED_BASE_I2C_ADDR + i && reply[2] == msg[sizeof(msg) - 1] + 1) { DEVICE_LOG("oreoled %u ok - in application", (unsigned)i); _healthy[i] = true; _num_healthy++; } else { DEVICE_LOG("oreo reply errors: %u", (unsigned)_reply_errors); perf_count(_reply_errors); } } else { perf_count(_comms_errors); } perf_end(_probe_perf); } } /* schedule another attempt in 0.1 sec */ work_queue(HPWORK, &_work, (worker_t)&OREOLED::cycle_trampoline, this, USEC2TICK(OREOLED_STARTUP_INTERVAL_US)); return; } else if (_alwaysupdate) { /* reset each healthy LED */ for (uint8_t i = 0; i < OREOLED_NUM_LEDS; i++) { if (_healthy[i] && !_in_boot[i]) { /* reset the LED if it's not in the bootloader */ /* (this happens during a pixhawk OTA update, since the LEDs stay powered) */ bootloader_app_reset(i); } } /* attempt to update each healthy LED */ for (uint8_t i = 0; i < OREOLED_NUM_LEDS; i++) { if (_healthy[i] && _in_boot[i]) { /* flash the new firmware */ bootloader_flash(i); } } /* boot each healthy LED */ for (uint8_t i = 0; i < OREOLED_NUM_LEDS; i++) { if (_healthy[i] && _in_boot[i]) { /* boot the application */ bootloader_boot(i); } } /* coerce LEDs with startup issues to be healthy again */ bootloader_coerce_healthy(); /* mandatory updating has finished */ _alwaysupdate = false; /* schedule a fresh cycle call when the measurement is done */ work_queue(HPWORK, &_work, (worker_t)&OREOLED::cycle_trampoline, this, USEC2TICK(OREOLED_UPDATE_INTERVAL_US)); return; } else if (_autoupdate) { /* check booted oreoleds to see if the app can report it's checksum (release versions >= v1.2) */ for (uint8_t i = 0; i < OREOLED_NUM_LEDS; i++) { if (_healthy[i] && !_in_boot[i]) { /* put any out of date oreoleds into bootloader mode */ /* being in bootloader mode signals to be code below that the will likey need updating */ if (bootloader_inapp_checksum(i) != bootloader_fw_checksum()) { bootloader_app_reset(i); } } } /* reset all healthy oreoleds if the number of outdated oreoled's is > 0 */ /* this is done for consistency, so if only one oreoled is updating, all LEDs show the same behaviour */ /* otherwise a single oreoled could appear broken or failed. */ if (_num_inboot > 0) { for (uint8_t i = 0; i < OREOLED_NUM_LEDS; i++) { if (_healthy[i] && !_in_boot[i]) { /* reset the LED if it's not in the bootloader */ /* (this happens during a pixhawk OTA update, since the LEDs stay powered) */ bootloader_app_reset(i); } } /* update each outdated and healthy LED in bootloader mode */ for (uint8_t i = 0; i < OREOLED_NUM_LEDS; i++) { if (_healthy[i] && _in_boot[i]) { /* only flash LEDs with an old version of the applictioon */ if (bootloader_app_checksum(i) != bootloader_fw_checksum()) { /* flash the new firmware */ bootloader_flash(i); } } } /* boot each healthy LED */ for (uint8_t i = 0; i < OREOLED_NUM_LEDS; i++) { if (_healthy[i] && _in_boot[i]) { /* boot the application */ bootloader_boot(i); } } /* coerce LEDs with startup issues to be healthy again */ bootloader_coerce_healthy(); } /* auto updating has finished */ _autoupdate = false; /* schedule a fresh cycle call when the measurement is done */ work_queue(HPWORK, &_work, (worker_t)&OREOLED::cycle_trampoline, this, USEC2TICK(OREOLED_UPDATE_INTERVAL_US)); return; } else if (_num_inboot > 0) { /* boot any LEDs which are in still in bootloader mode */ for (uint8_t i = 0; i < OREOLED_NUM_LEDS; i++) { if (_in_boot[i]) { bootloader_boot(i); } } /* coerce LEDs with startup issues to be healthy again */ bootloader_coerce_healthy(); /* ensure we don't get stuck in a loop */ _num_inboot = 0; /* schedule a fresh cycle call when the measurement is done */ work_queue(HPWORK, &_work, (worker_t)&OREOLED::cycle_trampoline, this, USEC2TICK(OREOLED_UPDATE_INTERVAL_US)); return; } else if (!_is_ready) { /* indicate a ready state since startup has finished */ _is_ready = true; } /* get next command from queue */ oreoled_cmd_t next_cmd; while (_cmd_queue->get(&next_cmd, sizeof(oreoled_cmd_t))) { /* send valid messages to healthy LEDs */ if ((next_cmd.led_num < OREOLED_NUM_LEDS) && _healthy[next_cmd.led_num] && (next_cmd.num_bytes <= OREOLED_CMD_LENGTH_MAX)) { /* start performance timer */ perf_begin(_call_perf); /* set I2C address */ set_address(OREOLED_BASE_I2C_ADDR + next_cmd.led_num); /* Calculate XOR CRC and append to the i2c write data */ uint8_t next_cmd_xor = OREOLED_BASE_I2C_ADDR + next_cmd.led_num; for (uint8_t i = 0; i < next_cmd.num_bytes; i++) { next_cmd_xor ^= next_cmd.buff[i]; } next_cmd.buff[next_cmd.num_bytes++] = next_cmd_xor; /* send I2C command with a retry limit */ for (uint8_t retry = OEROLED_COMMAND_RETRIES; retry > 0; retry--) { if (transfer(next_cmd.buff, next_cmd.num_bytes, reply, 3) == OK) { if (reply[1] == (OREOLED_BASE_I2C_ADDR + next_cmd.led_num) && reply[2] == next_cmd_xor) { /* slave returned a valid response */ break; } else { perf_count(_reply_errors); } } else { perf_count(_comms_errors); } } perf_end(_call_perf); } } /* send general call every 4 seconds, if we aren't bootloading*/ if (!_is_bootloading && ((now - _last_gencall) > OREOLED_GENERALCALL_US)) { perf_begin(_gcall_perf); send_general_call(); perf_end(_gcall_perf); } /* schedule a fresh cycle call when the command is sent */ work_queue(HPWORK, &_work, (worker_t)&OREOLED::cycle_trampoline, this, USEC2TICK(OREOLED_UPDATE_INTERVAL_US)); } int OREOLED::bootloader_app_reset(int led_num) { _is_bootloading = true; oreoled_cmd_t boot_cmd; boot_cmd.led_num = led_num; int ret = -1; /* Set the current address */ set_address(OREOLED_BASE_I2C_ADDR + boot_cmd.led_num); /* send a reset */ boot_cmd.buff[0] = OREOLED_PATTERN_PARAMUPDATE; boot_cmd.buff[1] = OREOLED_PARAM_RESET; boot_cmd.buff[2] = OEROLED_RESET_NONCE; boot_cmd.buff[3] = OREOLED_BASE_I2C_ADDR + boot_cmd.led_num; boot_cmd.num_bytes = 4; for (uint8_t j = 0; j < boot_cmd.num_bytes - 1; j++) { boot_cmd.buff[boot_cmd.num_bytes - 1] ^= boot_cmd.buff[j]; } uint8_t reply[OREOLED_CMD_READ_LENGTH_MAX]; /* send I2C command with a retry limit */ for (uint8_t retry = OEROLED_COMMAND_RETRIES; retry > 0; retry--) { if (transfer(boot_cmd.buff, boot_cmd.num_bytes, reply, 3) == OK) { if (reply[1] == (OREOLED_BASE_I2C_ADDR + boot_cmd.led_num) && reply[2] == boot_cmd.buff[boot_cmd.num_bytes - 1]) { /* slave returned a valid response */ ret = OK; /* set this LED as being in boot mode now */ _in_boot[led_num] = true; _num_inboot++; break; } } } /* Allow time for the LED to reboot */ usleep(OREOLED_BOOT_FLASH_WAITMS * 1000 * 10); usleep(OREOLED_BOOT_FLASH_WAITMS * 1000 * 10); usleep(OREOLED_BOOT_FLASH_WAITMS * 1000 * 10); usleep(OREOLED_BOOT_FLASH_WAITMS * 1000 * 10); _is_bootloading = false; return ret; } int OREOLED::bootloader_app_ping(int led_num) { oreoled_cmd_t boot_cmd; boot_cmd.led_num = led_num; int ret = -1; /* Set the current address */ set_address(OREOLED_BASE_I2C_ADDR + boot_cmd.led_num); /* send a pattern off command */ boot_cmd.buff[0] = 0xAA; boot_cmd.buff[1] = 0x55; boot_cmd.buff[2] = OREOLED_PATTERN_OFF; boot_cmd.buff[3] = OREOLED_BASE_I2C_ADDR + boot_cmd.led_num; boot_cmd.num_bytes = 4; for (uint8_t j = 0; j < boot_cmd.num_bytes - 1; j++) { boot_cmd.buff[boot_cmd.num_bytes - 1] ^= boot_cmd.buff[j]; } uint8_t reply[OREOLED_CMD_READ_LENGTH_MAX]; /* send I2C command with a retry limit */ for (uint8_t retry = OEROLED_COMMAND_RETRIES; retry > 0; retry--) { if (transfer(boot_cmd.buff, boot_cmd.num_bytes, reply, 3) == OK) { if (reply[1] == (OREOLED_BASE_I2C_ADDR + boot_cmd.led_num) && reply[2] == boot_cmd.buff[boot_cmd.num_bytes - 1]) { /* slave returned a valid response */ ret = OK; break; } } } return ret; } uint16_t OREOLED::bootloader_inapp_checksum(int led_num) { _is_bootloading = true; oreoled_cmd_t boot_cmd; boot_cmd.led_num = led_num; uint16_t ret = 0x0000; /* Set the current address */ set_address(OREOLED_BASE_I2C_ADDR + boot_cmd.led_num); boot_cmd.buff[0] = OREOLED_PATTERN_PARAMUPDATE; boot_cmd.buff[1] = OREOLED_PARAM_APP_CHECKSUM; boot_cmd.buff[2] = OREOLED_BASE_I2C_ADDR + boot_cmd.led_num; boot_cmd.num_bytes = 3; for (uint8_t j = 0; j < boot_cmd.num_bytes - 1; j++) { boot_cmd.buff[boot_cmd.num_bytes - 1] ^= boot_cmd.buff[j]; } uint8_t reply[OREOLED_CMD_READ_LENGTH_MAX]; for (uint8_t retry = OEROLED_COMMAND_RETRIES; retry > 0; retry--) { /* Send the I2C Write+Read */ memset(reply, 0, sizeof(reply)); transfer(boot_cmd.buff, boot_cmd.num_bytes, reply, 6); /* Check the response */ if (reply[1] == OREOLED_BASE_I2C_ADDR + boot_cmd.led_num && reply[2] == OREOLED_PARAM_APP_CHECKSUM && reply[5] == boot_cmd.buff[boot_cmd.num_bytes - 1]) { warnx("bl app checksum OK from LED %i", boot_cmd.led_num); warnx("bl app checksum msb: 0x%x", reply[3]); warnx("bl app checksum lsb: 0x%x", reply[4]); ret = ((reply[3] << 8) | reply[4]); break; } else { warnx("bl app checksum FAIL from LED %i", boot_cmd.led_num); warnx("bl app checksum response ADDR: 0x%x", reply[1]); warnx("bl app checksum response CMD: 0x%x", reply[2]); warnx("bl app checksum response VER H: 0x%x", reply[3]); warnx("bl app checksum response VER L: 0x%x", reply[4]); warnx("bl app checksum response XOR: 0x%x", reply[5]); if (retry > 1) { warnx("bl app checksum retrying LED %i", boot_cmd.led_num); } else { warnx("bl app checksum failed on LED %i", boot_cmd.led_num); break; } } } _is_bootloading = false; return ret; } int OREOLED::bootloader_ping(int led_num) { _is_bootloading = true; oreoled_cmd_t boot_cmd; boot_cmd.led_num = led_num; int ret = -1; /* Set the current address */ set_address(OREOLED_BASE_I2C_ADDR + boot_cmd.led_num); boot_cmd.buff[0] = OREOLED_BOOT_CMD_PING; boot_cmd.buff[1] = OREOLED_BASE_I2C_ADDR + boot_cmd.led_num; boot_cmd.num_bytes = 2; for (uint8_t j = 0; j < boot_cmd.num_bytes - 1; j++) { boot_cmd.buff[boot_cmd.num_bytes - 1] ^= boot_cmd.buff[j]; } uint8_t reply[OREOLED_CMD_READ_LENGTH_MAX]; for (uint8_t retry = OEROLED_BOOT_COMMAND_RETRIES; retry > 0; retry--) { /* Send the I2C Write+Read */ memset(reply, 0, sizeof(reply)); transfer(boot_cmd.buff, boot_cmd.num_bytes, reply, 5); /* Check the response */ if (reply[1] == OREOLED_BASE_I2C_ADDR + boot_cmd.led_num && reply[2] == OREOLED_BOOT_CMD_PING && reply[3] == OREOLED_BOOT_CMD_PING_NONCE && reply[4] == boot_cmd.buff[boot_cmd.num_bytes - 1]) { warnx("bl ping OK from LED %i", boot_cmd.led_num); ret = OK; break; } else { warnx("bl ping FAIL from LED %i", boot_cmd.led_num); warnx("bl ping response ADDR: 0x%x", reply[1]); warnx("bl ping response CMD: 0x%x", reply[2]); warnx("bl ping response NONCE: 0x%x", reply[3]); warnx("bl ping response XOR: 0x%x", reply[4]); if (retry > 1) { warnx("bl ping retrying LED %i", boot_cmd.led_num); } else { warnx("bl ping failed on LED %i", boot_cmd.led_num); break; } } } _is_bootloading = false; return ret; } uint8_t OREOLED::bootloader_version(int led_num) { _is_bootloading = true; oreoled_cmd_t boot_cmd; boot_cmd.led_num = led_num; uint8_t ret = 0x00; /* Set the current address */ set_address(OREOLED_BASE_I2C_ADDR + boot_cmd.led_num); boot_cmd.buff[0] = OREOLED_BOOT_CMD_BL_VER; boot_cmd.buff[1] = OREOLED_BASE_I2C_ADDR + boot_cmd.led_num; boot_cmd.num_bytes = 2; for (uint8_t k = 0; k < boot_cmd.num_bytes - 1; k++) { boot_cmd.buff[boot_cmd.num_bytes - 1] ^= boot_cmd.buff[k]; } uint8_t reply[OREOLED_CMD_READ_LENGTH_MAX]; for (uint8_t retry = OEROLED_BOOT_COMMAND_RETRIES; retry > 0; retry--) { /* Send the I2C Write+Read */ memset(reply, 0, sizeof(reply)); transfer(boot_cmd.buff, boot_cmd.num_bytes, reply, 5); /* Check the response */ if (reply[1] == OREOLED_BASE_I2C_ADDR + boot_cmd.led_num && reply[2] == OREOLED_BOOT_CMD_BL_VER && reply[3] == OREOLED_BOOT_SUPPORTED_VER && reply[4] == boot_cmd.buff[boot_cmd.num_bytes - 1]) { warnx("bl ver from LED %i = %i", boot_cmd.led_num, reply[3]); ret = reply[3]; break; } else { warnx("bl ver response ADDR: 0x%x", reply[1]); warnx("bl ver response CMD: 0x%x", reply[2]); warnx("bl ver response VER: 0x%x", reply[3]); warnx("bl ver response XOR: 0x%x", reply[4]); if (retry > 1) { warnx("bl ver retrying LED %i", boot_cmd.led_num); } else { warnx("bl ver failed on LED %i", boot_cmd.led_num); break; } } } _is_bootloading = false; return ret; } uint16_t OREOLED::bootloader_app_version(int led_num) { _is_bootloading = true; oreoled_cmd_t boot_cmd; boot_cmd.led_num = led_num; uint16_t ret = 0x0000; /* Set the current address */ set_address(OREOLED_BASE_I2C_ADDR + boot_cmd.led_num); boot_cmd.buff[0] = OREOLED_BOOT_CMD_APP_VER; boot_cmd.buff[1] = OREOLED_BASE_I2C_ADDR + boot_cmd.led_num; boot_cmd.num_bytes = 2; for (uint8_t j = 0; j < boot_cmd.num_bytes - 1; j++) { boot_cmd.buff[boot_cmd.num_bytes - 1] ^= boot_cmd.buff[j]; } uint8_t reply[OREOLED_CMD_READ_LENGTH_MAX]; for (uint8_t retry = OEROLED_BOOT_COMMAND_RETRIES; retry > 0; retry--) { /* Send the I2C Write+Read */ memset(reply, 0, sizeof(reply)); transfer(boot_cmd.buff, boot_cmd.num_bytes, reply, 6); /* Check the response */ if (reply[1] == OREOLED_BASE_I2C_ADDR + boot_cmd.led_num && reply[2] == OREOLED_BOOT_CMD_APP_VER && reply[5] == boot_cmd.buff[boot_cmd.num_bytes - 1]) { warnx("bl app version OK from LED %i", boot_cmd.led_num); warnx("bl app version msb: 0x%x", reply[3]); warnx("bl app version lsb: 0x%x", reply[4]); ret = ((reply[3] << 8) | reply[4]); break; } else { warnx("bl app version FAIL from LED %i", boot_cmd.led_num); warnx("bl app version response ADDR: 0x%x", reply[1]); warnx("bl app version response CMD: 0x%x", reply[2]); warnx("bl app version response VER H: 0x%x", reply[3]); warnx("bl app version response VER L: 0x%x", reply[4]); warnx("bl app version response XOR: 0x%x", reply[5]); if (retry > 1) { warnx("bl app version retrying LED %i", boot_cmd.led_num); } else { warnx("bl app version failed on LED %i", boot_cmd.led_num); break; } } } _is_bootloading = false; return ret; } uint16_t OREOLED::bootloader_app_checksum(int led_num) { _is_bootloading = true; oreoled_cmd_t boot_cmd; boot_cmd.led_num = led_num; uint16_t ret = 0x0000; /* Set the current address */ set_address(OREOLED_BASE_I2C_ADDR + boot_cmd.led_num); boot_cmd.buff[0] = OREOLED_BOOT_CMD_APP_CRC; boot_cmd.buff[1] = OREOLED_BASE_I2C_ADDR + boot_cmd.led_num; boot_cmd.num_bytes = 2; for (uint8_t j = 0; j < boot_cmd.num_bytes - 1; j++) { boot_cmd.buff[boot_cmd.num_bytes - 1] ^= boot_cmd.buff[j]; } uint8_t reply[OREOLED_CMD_READ_LENGTH_MAX]; for (uint8_t retry = OEROLED_BOOT_COMMAND_RETRIES; retry > 0; retry--) { /* Send the I2C Write+Read */ memset(reply, 0, sizeof(reply)); transfer(boot_cmd.buff, boot_cmd.num_bytes, reply, 6); /* Check the response */ if (reply[1] == OREOLED_BASE_I2C_ADDR + boot_cmd.led_num && reply[2] == OREOLED_BOOT_CMD_APP_CRC && reply[5] == boot_cmd.buff[boot_cmd.num_bytes - 1]) { warnx("bl app checksum OK from LED %i", boot_cmd.led_num); warnx("bl app checksum msb: 0x%x", reply[3]); warnx("bl app checksum lsb: 0x%x", reply[4]); ret = ((reply[3] << 8) | reply[4]); break; } else { warnx("bl app checksum FAIL from LED %i", boot_cmd.led_num); warnx("bl app checksum response ADDR: 0x%x", reply[1]); warnx("bl app checksum response CMD: 0x%x", reply[2]); warnx("bl app checksum response VER H: 0x%x", reply[3]); warnx("bl app checksum response VER L: 0x%x", reply[4]); warnx("bl app checksum response XOR: 0x%x", reply[5]); if (retry > 1) { warnx("bl app checksum retrying LED %i", boot_cmd.led_num); } else { warnx("bl app checksum failed on LED %i", boot_cmd.led_num); break; } } } _is_bootloading = false; return ret; } int OREOLED::bootloader_set_colour(int led_num, uint8_t red, uint8_t green) { _is_bootloading = true; oreoled_cmd_t boot_cmd; boot_cmd.led_num = led_num; int ret = -1; /* Set the current address */ set_address(OREOLED_BASE_I2C_ADDR + boot_cmd.led_num); boot_cmd.buff[0] = OREOLED_BOOT_CMD_SET_COLOUR; boot_cmd.buff[1] = red; boot_cmd.buff[2] = green; boot_cmd.buff[3] = OREOLED_BASE_I2C_ADDR + boot_cmd.led_num; boot_cmd.num_bytes = 4; for (uint8_t j = 0; j < boot_cmd.num_bytes - 1; j++) { boot_cmd.buff[boot_cmd.num_bytes - 1] ^= boot_cmd.buff[j]; } uint8_t reply[OREOLED_CMD_READ_LENGTH_MAX]; for (uint8_t retry = OEROLED_BOOT_COMMAND_RETRIES; retry > 0; retry--) { /* Send the I2C Write+Read */ memset(reply, 0, sizeof(reply)); transfer(boot_cmd.buff, boot_cmd.num_bytes, reply, 4); /* Check the response */ if (reply[1] == OREOLED_BASE_I2C_ADDR + boot_cmd.led_num && reply[2] == OREOLED_BOOT_CMD_SET_COLOUR && reply[3] == boot_cmd.buff[boot_cmd.num_bytes - 1]) { warnx("bl set colour OK from LED %i", boot_cmd.led_num); ret = OK; break; } else { warnx("bl set colour FAIL from LED %i", boot_cmd.led_num); warnx("bl set colour response ADDR: 0x%x", reply[1]); warnx("bl set colour response CMD: 0x%x", reply[2]); warnx("bl set colour response XOR: 0x%x", reply[3]); if (retry > 1) { warnx("bl app colour retrying LED %i", boot_cmd.led_num); } else { warnx("bl app colour failed on LED %i", boot_cmd.led_num); break; } } } _is_bootloading = false; return ret; } int OREOLED::bootloader_flash(int led_num) { _is_bootloading = true; oreoled_cmd_t boot_cmd; boot_cmd.led_num = led_num; /* Open the bootloader file */ int fd = ::open(OREOLED_FW_FILE, O_RDONLY); /* check for error opening the file */ if (fd < 0) { return -1; } struct stat s; /* attempt to stat the file */ if (stat(OREOLED_FW_FILE, &s) != 0) { ::close(fd); return -1; } uint16_t fw_length = s.st_size - OREOLED_FW_FILE_HEADER_LENGTH; /* sanity-check file size */ if (fw_length > OREOLED_FW_FILE_SIZE_LIMIT) { ::close(fd); return -1; } uint8_t *buf = new uint8_t[s.st_size]; /* check that the buffer has been allocated */ if (buf == NULL) { ::close(fd); return -1; } /* check that the firmware can be read into the buffer */ if (::read(fd, buf, s.st_size) != s.st_size) { ::close(fd); delete[] buf; return -1; } ::close(fd); /* Grab the version bytes from the binary */ uint8_t version_major = buf[0]; uint8_t version_minor = buf[1]; /* calculate flash pages (rounded up to nearest integer) */ uint8_t flash_pages = ((fw_length + 64 - 1) / 64); /* Set the current address */ set_address(OREOLED_BASE_I2C_ADDR + boot_cmd.led_num); uint8_t reply[OREOLED_CMD_READ_LENGTH_MAX]; /* Loop through flash pages */ for (uint8_t page_idx = 0; page_idx < flash_pages; page_idx++) { /* Send the first half of the 64 byte flash page */ memset(boot_cmd.buff, 0, sizeof(boot_cmd.buff)); boot_cmd.buff[0] = OREOLED_BOOT_CMD_WRITE_FLASH_A; boot_cmd.buff[1] = page_idx; memcpy(boot_cmd.buff + 2, buf + (page_idx * 64) + OREOLED_FW_FILE_HEADER_LENGTH, 32); boot_cmd.buff[32 + 2] = OREOLED_BASE_I2C_ADDR + boot_cmd.led_num; boot_cmd.num_bytes = 32 + 3; for (uint8_t k = 0; k < boot_cmd.num_bytes - 1; k++) { boot_cmd.buff[boot_cmd.num_bytes - 1] ^= boot_cmd.buff[k]; } for (uint8_t retry = OEROLED_BOOT_COMMAND_RETRIES; retry > 0; retry--) { /* Send the I2C Write+Read */ memset(reply, 0, sizeof(reply)); transfer(boot_cmd.buff, boot_cmd.num_bytes, reply, 4); /* Check the response */ if (reply[1] == OREOLED_BASE_I2C_ADDR + boot_cmd.led_num && reply[2] == OREOLED_BOOT_CMD_WRITE_FLASH_A && reply[3] == boot_cmd.buff[boot_cmd.num_bytes - 1]) { warnx("bl flash %ia OK for LED %i", page_idx, boot_cmd.led_num); break; } else { warnx("bl flash %ia FAIL for LED %i", page_idx, boot_cmd.led_num); warnx("bl flash %ia response ADDR: 0x%x", page_idx, reply[1]); warnx("bl flash %ia response CMD: 0x%x", page_idx, reply[2]); warnx("bl flash %ia response XOR: 0x%x", page_idx, reply[3]); if (retry > 1) { warnx("bl flash %ia retrying LED %i", page_idx, boot_cmd.led_num); } else { warnx("bl flash %ia failed on LED %i", page_idx, boot_cmd.led_num); delete[] buf; return -1; } } } /* Send the second half of the 64 byte flash page */ memset(boot_cmd.buff, 0, sizeof(boot_cmd.buff)); boot_cmd.buff[0] = OREOLED_BOOT_CMD_WRITE_FLASH_B; memcpy(boot_cmd.buff + 1, buf + (page_idx * 64) + 32 + OREOLED_FW_FILE_HEADER_LENGTH, 32); boot_cmd.buff[32 + 1] = OREOLED_BASE_I2C_ADDR + boot_cmd.led_num; boot_cmd.num_bytes = 32 + 2; for (uint8_t k = 0; k < boot_cmd.num_bytes - 1; k++) { boot_cmd.buff[boot_cmd.num_bytes - 1] ^= boot_cmd.buff[k]; } for (uint8_t retry = OEROLED_BOOT_COMMAND_RETRIES; retry > 0; retry--) { /* Send the I2C Write+Read */ memset(reply, 0, sizeof(reply)); transfer(boot_cmd.buff, boot_cmd.num_bytes, reply, 4); /* Check the response */ if (reply[1] == OREOLED_BASE_I2C_ADDR + boot_cmd.led_num && reply[2] == OREOLED_BOOT_CMD_WRITE_FLASH_B && reply[3] == boot_cmd.buff[boot_cmd.num_bytes - 1]) { warnx("bl flash %ib OK for LED %i", page_idx, boot_cmd.led_num); break; } else { warnx("bl flash %ib FAIL for LED %i", page_idx, boot_cmd.led_num); warnx("bl flash %ib response ADDR: 0x%x", page_idx, reply[1]); warnx("bl flash %ib response CMD: 0x%x", page_idx, reply[2]); warnx("bl flash %ib response XOR: 0x%x", page_idx, reply[3]); if (retry > 1) { warnx("bl flash %ib retrying LED %i", page_idx, boot_cmd.led_num); } else { errx(1, "bl flash %ib failed on LED %i", page_idx, boot_cmd.led_num); delete[] buf; return -1; } } } /* Sleep to allow flash to write */ /* Wait extra long on the first write, to allow time for EEPROM updates */ if (page_idx == 0) { usleep(OREOLED_BOOT_FLASH_WAITMS * 1000 * 10); } else { usleep(OREOLED_BOOT_FLASH_WAITMS * 1000); } } uint16_t app_checksum = bootloader_fw_checksum(); /* Flash writes must have succeeded so finalise the flash */ boot_cmd.buff[0] = OREOLED_BOOT_CMD_FINALISE_FLASH; boot_cmd.buff[1] = version_major; boot_cmd.buff[2] = version_minor; boot_cmd.buff[3] = (uint8_t)(fw_length >> 8); boot_cmd.buff[4] = (uint8_t)(fw_length & 0xFF); boot_cmd.buff[5] = (uint8_t)(app_checksum >> 8); boot_cmd.buff[6] = (uint8_t)(app_checksum & 0xFF); boot_cmd.buff[7] = OREOLED_BASE_I2C_ADDR + boot_cmd.led_num; boot_cmd.num_bytes = 8; for (uint8_t k = 0; k < boot_cmd.num_bytes - 1; k++) { boot_cmd.buff[boot_cmd.num_bytes - 1] ^= boot_cmd.buff[k]; } /* Try to finalise for twice the amount of normal retries */ for (uint8_t retry = OEROLED_BOOT_COMMAND_RETRIES * 2; retry > 0; retry--) { /* Send the I2C Write */ memset(reply, 0, sizeof(reply)); transfer(boot_cmd.buff, boot_cmd.num_bytes, reply, 4); /* Check the response */ if (reply[1] == OREOLED_BASE_I2C_ADDR + boot_cmd.led_num && reply[2] == OREOLED_BOOT_CMD_FINALISE_FLASH && reply[3] == boot_cmd.buff[boot_cmd.num_bytes - 1]) { warnx("bl finalise OK from LED %i", boot_cmd.led_num); break; } else { warnx("bl finalise response ADDR: 0x%x", reply[1]); warnx("bl finalise response CMD: 0x%x", reply[2]); warnx("bl finalise response XOR: 0x%x", reply[3]); if (retry > 1) { warnx("bl finalise retrying LED %i", boot_cmd.led_num); } else { warnx("bl finalise failed on LED %i", boot_cmd.led_num); delete[] buf; return -1; } } } /* allow time for flash to finalise */ usleep(OREOLED_BOOT_FLASH_WAITMS * 1000 * 10); usleep(OREOLED_BOOT_FLASH_WAITMS * 1000 * 10); /* clean up file buffer */ delete[] buf; _is_bootloading = false; return 1; } int OREOLED::bootloader_boot(int led_num) { _is_bootloading = true; oreoled_cmd_t boot_cmd; boot_cmd.led_num = led_num; int ret = -1; /* Set the current address */ set_address(OREOLED_BASE_I2C_ADDR + boot_cmd.led_num); boot_cmd.buff[0] = OREOLED_BOOT_CMD_BOOT_APP; boot_cmd.buff[1] = OREOLED_BOOT_CMD_BOOT_NONCE; boot_cmd.buff[2] = OREOLED_BASE_I2C_ADDR + boot_cmd.led_num; boot_cmd.num_bytes = 3; for (uint8_t k = 0; k < boot_cmd.num_bytes - 1; k++) { boot_cmd.buff[boot_cmd.num_bytes - 1] ^= boot_cmd.buff[k]; } for (uint8_t retry = OEROLED_BOOT_COMMAND_RETRIES; retry > 0; retry--) { /* Send the I2C Write */ uint8_t reply[OREOLED_CMD_READ_LENGTH_MAX]; transfer(boot_cmd.buff, boot_cmd.num_bytes, reply, 4); /* Check the response */ if (reply[1] == OREOLED_BASE_I2C_ADDR + boot_cmd.led_num && reply[2] == OREOLED_BOOT_CMD_BOOT_APP && reply[3] == boot_cmd.buff[boot_cmd.num_bytes - 1]) { warnx("bl boot OK from LED %i", boot_cmd.led_num); /* decrement the inboot counter so we don't get confused */ _in_boot[led_num] = false; _num_inboot--; ret = OK; break; } else if (reply[1] == OREOLED_BASE_I2C_ADDR + boot_cmd.led_num && reply[2] == OREOLED_BOOT_CMD_BOOT_NONCE && reply[3] == boot_cmd.buff[boot_cmd.num_bytes - 1]) { warnx("bl boot error from LED %i: no app", boot_cmd.led_num); break; } else { warnx("bl boot response ADDR: 0x%x", reply[1]); warnx("bl boot response CMD: 0x%x", reply[2]); warnx("bl boot response XOR: 0x%x", reply[3]); if (retry > 1) { warnx("bl boot retrying LED %i", boot_cmd.led_num); } else { warnx("bl boot failed on LED %i", boot_cmd.led_num); break; } } } /* allow time for the LEDs to boot */ usleep(OREOLED_BOOT_FLASH_WAITMS * 1000 * 10); usleep(OREOLED_BOOT_FLASH_WAITMS * 1000 * 10); usleep(OREOLED_BOOT_FLASH_WAITMS * 1000 * 10); usleep(OREOLED_BOOT_FLASH_WAITMS * 1000 * 10); _is_bootloading = false; return ret; } uint16_t OREOLED::bootloader_fw_checksum(void) { /* Calculate the 16 bit XOR checksum of the firmware on the first call of this function */ if (_fw_checksum == 0x0000) { /* Open the bootloader file */ int fd = ::open(OREOLED_FW_FILE, O_RDONLY); /* check for error opening the file */ if (fd < 0) { return -1; } struct stat s; /* attempt to stat the file */ if (stat(OREOLED_FW_FILE, &s) != 0) { ::close(fd); return -1; } uint16_t fw_length = s.st_size - OREOLED_FW_FILE_HEADER_LENGTH; /* sanity-check file size */ if (fw_length > OREOLED_FW_FILE_SIZE_LIMIT) { ::close(fd); return -1; } uint8_t *buf = new uint8_t[s.st_size]; /* check that the buffer has been allocated */ if (buf == NULL) { ::close(fd); return -1; } /* check that the firmware can be read into the buffer */ if (::read(fd, buf, s.st_size) != s.st_size) { ::close(fd); delete[] buf; return -1; } ::close(fd); /* Calculate a 16 bit XOR checksum of the flash */ /* Skip the first two bytes which are the version information, plus the next two bytes which are modified by the bootloader */ uint16_t app_checksum = 0x0000; for (uint16_t j = 2 + OREOLED_FW_FILE_HEADER_LENGTH; j < s.st_size; j += 2) { app_checksum ^= (buf[j] << 8) | buf[j + 1]; } delete[] buf; warnx("fw length = %i", fw_length); warnx("fw checksum = %i", app_checksum); /* Store the checksum so it's only calculated once */ _fw_checksum = app_checksum; } return _fw_checksum; } int OREOLED::bootloader_coerce_healthy(void) { int ret = -1; /* check each unhealthy LED */ /* this re-checks "unhealthy" LEDs as they can sometimes power up with the wrong ID, */ /* but will have the correct ID once they jump to the application and be healthy again */ for (uint8_t i = 0; i < OREOLED_NUM_LEDS; i++) { if (!_healthy[i] && bootloader_app_ping(i) == OK) { /* mark as healthy */ _healthy[i] = true; _num_healthy++; ret = OK; } } return ret; } int OREOLED::ioctl(struct file *filp, int cmd, unsigned long arg) { int ret = -ENODEV; oreoled_cmd_t new_cmd; switch (cmd) { case OREOLED_SET_RGB: /* set the specified color */ new_cmd.led_num = ((oreoled_rgbset_t *) arg)->instance; new_cmd.buff[0] = ((oreoled_rgbset_t *) arg)->pattern; new_cmd.buff[1] = OREOLED_PARAM_BIAS_RED; new_cmd.buff[2] = ((oreoled_rgbset_t *) arg)->red; new_cmd.buff[3] = OREOLED_PARAM_BIAS_GREEN; new_cmd.buff[4] = ((oreoled_rgbset_t *) arg)->green; new_cmd.buff[5] = OREOLED_PARAM_BIAS_BLUE; new_cmd.buff[6] = ((oreoled_rgbset_t *) arg)->blue; new_cmd.num_bytes = 7; /* special handling for request to set all instances rgb values */ if (new_cmd.led_num == OREOLED_ALL_INSTANCES) { for (uint8_t i = 0; i < OREOLED_NUM_LEDS; i++) { /* add command to queue for all healthy leds */ if (_healthy[i]) { new_cmd.led_num = i; _cmd_queue->force(&new_cmd); ret = OK; } } } else if (new_cmd.led_num < OREOLED_NUM_LEDS) { /* request to set individual instance's rgb value */ if (_healthy[new_cmd.led_num]) { _cmd_queue->force(&new_cmd); ret = OK; } } return ret; case OREOLED_RUN_MACRO: /* run a macro */ new_cmd.led_num = ((oreoled_macrorun_t *) arg)->instance; new_cmd.buff[0] = OREOLED_PATTERN_PARAMUPDATE; new_cmd.buff[1] = OREOLED_PARAM_MACRO; new_cmd.buff[2] = ((oreoled_macrorun_t *) arg)->macro; new_cmd.num_bytes = 3; /* special handling for request to set all instances */ if (new_cmd.led_num == OREOLED_ALL_INSTANCES) { for (uint8_t i = 0; i < OREOLED_NUM_LEDS; i++) { /* add command to queue for all healthy leds */ if (_healthy[i]) { new_cmd.led_num = i; _cmd_queue->force(&new_cmd); ret = OK; } } } else if (new_cmd.led_num < OREOLED_NUM_LEDS) { /* request to set individual instance's rgb value */ if (_healthy[new_cmd.led_num]) { _cmd_queue->force(&new_cmd); ret = OK; } } return ret; case OREOLED_SEND_RESET: /* send a reset */ new_cmd.led_num = OREOLED_ALL_INSTANCES; new_cmd.buff[0] = OREOLED_PATTERN_PARAMUPDATE; new_cmd.buff[1] = OREOLED_PARAM_RESET; new_cmd.buff[2] = OEROLED_RESET_NONCE; new_cmd.num_bytes = 3; for (uint8_t i = 0; i < OREOLED_NUM_LEDS; i++) { /* add command to queue for all healthy leds */ if (_healthy[i]) { warnx("sending a reset... to %i", i); new_cmd.led_num = i; _cmd_queue->force(&new_cmd); ret = OK; } } return ret; case OREOLED_BL_PING: for (uint8_t i = 0; i < OREOLED_NUM_LEDS; i++) { if (_healthy[i]) { bootloader_ping(i); ret = OK; } } return ret; case OREOLED_BL_VER: for (uint8_t i = 0; i < OREOLED_NUM_LEDS; i++) { if (_healthy[i]) { bootloader_version(i); ret = OK; } } return ret; case OREOLED_BL_FLASH: for (uint8_t i = 0; i < OREOLED_NUM_LEDS; i++) { if (_healthy[i]) { bootloader_flash(i); ret = OK; } } return ret; case OREOLED_BL_APP_VER: for (uint8_t i = 0; i < OREOLED_NUM_LEDS; i++) { if (_healthy[i]) { bootloader_app_version(i); ret = OK; } } return ret; case OREOLED_BL_APP_CRC: for (uint8_t i = 0; i < OREOLED_NUM_LEDS; i++) { if (_healthy[i]) { bootloader_app_checksum(i); ret = OK; } } return ret; case OREOLED_BL_SET_COLOUR: new_cmd.led_num = OREOLED_ALL_INSTANCES; for (uint8_t i = 0; i < OREOLED_NUM_LEDS; i++) { if (_healthy[i]) { bootloader_set_colour(i, ((oreoled_rgbset_t *) arg)->red, ((oreoled_rgbset_t *) arg)->green); ret = OK; } } return ret; case OREOLED_BL_BOOT_APP: new_cmd.led_num = OREOLED_ALL_INSTANCES; for (uint8_t i = 0; i < OREOLED_NUM_LEDS; i++) { if (_healthy[i]) { bootloader_boot(i); ret = OK; } } return ret; case OREOLED_SEND_BYTES: /* send bytes */ new_cmd = *((oreoled_cmd_t *) arg); /* special handling for request to set all instances */ if (new_cmd.led_num == OREOLED_ALL_INSTANCES) { for (uint8_t i = 0; i < OREOLED_NUM_LEDS; i++) { /* add command to queue for all healthy leds */ if (_healthy[i]) { new_cmd.led_num = i; _cmd_queue->force(&new_cmd); ret = OK; } } } else if (new_cmd.led_num < OREOLED_NUM_LEDS) { /* request to set individual instance's rgb value */ if (_healthy[new_cmd.led_num]) { _cmd_queue->force(&new_cmd); ret = OK; } } return ret; case OREOLED_FORCE_SYNC: send_general_call(); break; default: /* see if the parent class can make any use of it */ ret = CDev::ioctl(filp, cmd, arg); break; } return ret; } /* send general call on I2C bus to syncronise all LEDs */ int OREOLED::send_general_call() { int ret = -ENODEV; /* set I2C address to zero */ set_address(0); /* prepare command : 0x01 = general hardware call, 0x00 = I2C address of master (but we don't act as a slave so set to zero)*/ uint8_t msg[] = {0x01, 0x00}; /* send I2C command */ if (transfer(msg, sizeof(msg), nullptr, 0) == OK) { ret = OK; } /* record time */ _last_gencall = hrt_absolute_time(); return ret; } /* send a cmd to an LEDs (used for testing only) */ int OREOLED::send_cmd(oreoled_cmd_t new_cmd) { int ret = -ENODEV; /* sanity check led number, health and cmd length */ if ((new_cmd.led_num < OREOLED_NUM_LEDS) && _healthy[new_cmd.led_num] && (new_cmd.num_bytes < OREOLED_CMD_LENGTH_MAX)) { /* set I2C address */ set_address(OREOLED_BASE_I2C_ADDR + new_cmd.led_num); /* add to queue */ _cmd_queue->force(&new_cmd); ret = OK; } return ret; } /* return the internal _is_ready flag indicating if initialisation is complete */ bool OREOLED::is_ready() { return _is_ready; } void oreoled_usage() { warnx("missing command: try 'start', 'test', 'info', 'off', 'stop', 'reset', 'rgb 30 40 50', 'macro 4', 'gencall', 'bytes <lednum> 7 9 6'"); warnx("bootloader commands: try 'blping', 'blver', 'blappver', 'blappcrc', 'blcolour <red> <green>', 'blflash', 'blboot'"); warnx("options:"); warnx(" -b i2cbus (%d)", PX4_I2C_BUS_LED); warnx(" -a addr (0x%x)", OREOLED_BASE_I2C_ADDR); } int oreoled_main(int argc, char *argv[]) { int i2cdevice = -1; int i2c_addr = OREOLED_BASE_I2C_ADDR; /* 7bit */ int ch; /* jump over start/off/etc and look at options first */ while ((ch = getopt(argc, argv, "a:b:")) != EOF) { switch (ch) { case 'a': i2c_addr = (int)strtol(optarg, NULL, 0); break; case 'b': i2cdevice = (int)strtol(optarg, NULL, 0); break; default: oreoled_usage(); exit(0); } } if (optind >= argc) { oreoled_usage(); exit(1); } const char *verb = argv[optind]; int ret; /* start driver */ if (!strcmp(verb, "start")) { if (g_oreoled != nullptr) { errx(1, "already started"); } /* by default use LED bus */ if (i2cdevice == -1) { i2cdevice = PX4_I2C_BUS_LED; } /* handle update flags */ bool autoupdate = false; bool alwaysupdate = false; if (argc > 2 && !strcmp(argv[2], "autoupdate")) { warnx("autoupdate enabled"); autoupdate = true; } else if (argc > 2 && !strcmp(argv[2], "alwaysupdate")) { warnx("alwaysupdate enabled"); alwaysupdate = true; } /* instantiate driver */ g_oreoled = new OREOLED(i2cdevice, i2c_addr, autoupdate, alwaysupdate); /* check if object was created */ if (g_oreoled == nullptr) { errx(1, "failed to allocated memory for driver"); } /* check object was created successfully */ if (g_oreoled->init() != OK) { delete g_oreoled; g_oreoled = nullptr; errx(1, "failed to start driver"); } /* wait for up to 20 seconds for the driver become ready */ for (uint8_t i = 0; i < 20; i++) { if (g_oreoled != nullptr && g_oreoled->is_ready()) { break; } sleep(1); } exit(0); } /* need the driver past this point */ if (g_oreoled == nullptr) { warnx("not started"); oreoled_usage(); exit(1); } if (!strcmp(verb, "test")) { int fd = open(OREOLED0_DEVICE_PATH, O_RDWR); if (fd == -1) { errx(1, "Unable to open " OREOLED0_DEVICE_PATH); } /* structure to hold desired colour */ oreoled_rgbset_t rgb_set_red = {OREOLED_ALL_INSTANCES, OREOLED_PATTERN_SOLID, 0xFF, 0x0, 0x0}; oreoled_rgbset_t rgb_set_blue = {OREOLED_ALL_INSTANCES, OREOLED_PATTERN_SOLID, 0x0, 0x0, 0xFF}; oreoled_rgbset_t rgb_set_off = {OREOLED_ALL_INSTANCES, OREOLED_PATTERN_OFF, 0x0, 0x0, 0x0}; /* flash red and blue for 3 seconds */ for (uint8_t i = 0; i < 30; i++) { /* red */ if ((ret = ioctl(fd, OREOLED_SET_RGB, (unsigned long)&rgb_set_red)) != OK) { errx(1, " failed to update rgb"); } /* sleep for 0.05 seconds */ usleep(50000); /* blue */ if ((ret = ioctl(fd, OREOLED_SET_RGB, (unsigned long)&rgb_set_blue)) != OK) { errx(1, " failed to update rgb"); } /* sleep for 0.05 seconds */ usleep(50000); } /* turn off LED */ if ((ret = ioctl(fd, OREOLED_SET_RGB, (unsigned long)&rgb_set_off)) != OK) { errx(1, " failed to turn off led"); } close(fd); exit(ret); } /* display driver status */ if (!strcmp(verb, "info")) { g_oreoled->info(); exit(0); } if (!strcmp(verb, "off") || !strcmp(verb, "stop")) { int fd = open(OREOLED0_DEVICE_PATH, 0); if (fd == -1) { errx(1, "Unable to open " OREOLED0_DEVICE_PATH); } /* turn off LED */ oreoled_rgbset_t rgb_set_off = {OREOLED_ALL_INSTANCES, OREOLED_PATTERN_OFF, 0x0, 0x0, 0x0}; ret = ioctl(fd, OREOLED_SET_RGB, (unsigned long)&rgb_set_off); close(fd); /* delete the oreoled object if stop was requested, in addition to turning off the LED. */ if (!strcmp(verb, "stop")) { OREOLED *tmp_oreoled = g_oreoled; g_oreoled = nullptr; delete tmp_oreoled; exit(0); } exit(ret); } /* send rgb request to all LEDS */ if (!strcmp(verb, "rgb")) { if (argc < 5) { errx(1, "Usage: oreoled rgb <red> <green> <blue>"); } int fd = open(OREOLED0_DEVICE_PATH, 0); if (fd == -1) { errx(1, "Unable to open " OREOLED0_DEVICE_PATH); } uint8_t red = (uint8_t)strtol(argv[2], NULL, 0); uint8_t green = (uint8_t)strtol(argv[3], NULL, 0); uint8_t blue = (uint8_t)strtol(argv[4], NULL, 0); oreoled_rgbset_t rgb_set = {OREOLED_ALL_INSTANCES, OREOLED_PATTERN_SOLID, red, green, blue}; if ((ret = ioctl(fd, OREOLED_SET_RGB, (unsigned long)&rgb_set)) != OK) { errx(1, "failed to set rgb"); } close(fd); exit(ret); } /* send macro request to all LEDS */ if (!strcmp(verb, "macro")) { if (argc < 3) { errx(1, "Usage: oreoled macro <macro_num>"); } int fd = open(OREOLED0_DEVICE_PATH, 0); if (fd == -1) { errx(1, "Unable to open " OREOLED0_DEVICE_PATH); } uint8_t macro = (uint8_t)strtol(argv[2], NULL, 0); /* sanity check macro number */ if (macro > OREOLED_PARAM_MACRO_ENUM_COUNT) { errx(1, "invalid macro number %d", (int)macro); exit(ret); } oreoled_macrorun_t macro_run = {OREOLED_ALL_INSTANCES, (enum oreoled_macro)macro}; if ((ret = ioctl(fd, OREOLED_RUN_MACRO, (unsigned long)&macro_run)) != OK) { errx(1, "failed to run macro"); } close(fd); exit(ret); } /* send reset request to all LEDS */ if (!strcmp(verb, "reset")) { if (argc < 2) { errx(1, "Usage: oreoled reset"); } int fd = open(OREOLED0_DEVICE_PATH, 0); if (fd == -1) { errx(1, "Unable to open " OREOLED0_DEVICE_PATH); } if ((ret = ioctl(fd, OREOLED_SEND_RESET, 0)) != OK) { errx(1, "failed to run macro"); } close(fd); exit(ret); } /* attempt to flash all LEDS in bootloader mode*/ if (!strcmp(verb, "blflash")) { if (argc < 2) { errx(1, "Usage: oreoled blflash"); } int fd = open(OREOLED0_DEVICE_PATH, 0); if (fd == -1) { errx(1, "Unable to open " OREOLED0_DEVICE_PATH); } if ((ret = ioctl(fd, OREOLED_BL_FLASH, 0)) != OK) { errx(1, "failed to run flash"); } close(fd); exit(ret); } /* send bootloader boot request to all LEDS */ if (!strcmp(verb, "blboot")) { if (argc < 2) { errx(1, "Usage: oreoled blboot"); } int fd = open(OREOLED0_DEVICE_PATH, 0); if (fd == -1) { errx(1, "Unable to open " OREOLED0_DEVICE_PATH); } if ((ret = ioctl(fd, OREOLED_BL_BOOT_APP, 0)) != OK) { errx(1, "failed to run boot"); } close(fd); exit(ret); } /* send bootloader ping all LEDs */ if (!strcmp(verb, "blping")) { if (argc < 2) { errx(1, "Usage: oreoled blping"); } int fd = open(OREOLED0_DEVICE_PATH, 0); if (fd == -1) { errx(1, "Unable to open " OREOLED0_DEVICE_PATH); } if ((ret = ioctl(fd, OREOLED_BL_PING, 0)) != OK) { errx(1, "failed to run blping"); } close(fd); exit(ret); } /* ask all LEDs for their bootloader version */ if (!strcmp(verb, "blver")) { if (argc < 2) { errx(1, "Usage: oreoled blver"); } int fd = open(OREOLED0_DEVICE_PATH, 0); if (fd == -1) { errx(1, "Unable to open " OREOLED0_DEVICE_PATH); } if ((ret = ioctl(fd, OREOLED_BL_VER, 0)) != OK) { errx(1, "failed to get bootloader version"); } close(fd); exit(ret); } /* ask all LEDs for their application version */ if (!strcmp(verb, "blappver")) { if (argc < 2) { errx(1, "Usage: oreoled blappver"); } int fd = open(OREOLED0_DEVICE_PATH, 0); if (fd == -1) { errx(1, "Unable to open " OREOLED0_DEVICE_PATH); } if ((ret = ioctl(fd, OREOLED_BL_APP_VER, 0)) != OK) { errx(1, "failed to get boot app version"); } close(fd); exit(ret); } /* ask all LEDs for their application crc */ if (!strcmp(verb, "blappcrc")) { if (argc < 2) { errx(1, "Usage: oreoled blappcrc"); } int fd = open(OREOLED0_DEVICE_PATH, 0); if (fd == -1) { errx(1, "Unable to open " OREOLED0_DEVICE_PATH); } if ((ret = ioctl(fd, OREOLED_BL_APP_CRC, 0)) != OK) { errx(1, "failed to get boot app crc"); } close(fd); exit(ret); } /* set the default bootloader LED colour on all LEDs */ if (!strcmp(verb, "blcolour")) { if (argc < 4) { errx(1, "Usage: oreoled blcolour <red> <green>"); } int fd = open(OREOLED0_DEVICE_PATH, 0); if (fd == -1) { errx(1, "Unable to open " OREOLED0_DEVICE_PATH); } uint8_t red = (uint8_t)strtol(argv[2], NULL, 0); uint8_t green = (uint8_t)strtol(argv[3], NULL, 0); oreoled_rgbset_t rgb_set = {OREOLED_ALL_INSTANCES, OREOLED_PATTERN_SOLID, red, green, 0}; if ((ret = ioctl(fd, OREOLED_BL_SET_COLOUR, (unsigned long)&rgb_set)) != OK) { errx(1, "failed to set boot startup colours"); } close(fd); exit(ret); } /* send general hardware call to all LEDS */ if (!strcmp(verb, "gencall")) { ret = g_oreoled->send_general_call(); warnx("sent general call"); exit(ret); } /* send a string of bytes to an LED using send_bytes function */ if (!strcmp(verb, "bytes")) { if (argc < 3) { errx(1, "Usage: oreoled bytes <led_num> <byte1> <byte2> <byte3> ..."); } /* structure to be sent */ oreoled_cmd_t sendb; /* maximum of 20 bytes can be sent */ if (argc > 20 + 3) { errx(1, "Max of 20 bytes can be sent"); } /* check led num */ sendb.led_num = (uint8_t)strtol(argv[optind + 1], NULL, 0); if (sendb.led_num > 3) { errx(1, "led number must be between 0 ~ 3"); } /* get bytes */ sendb.num_bytes = argc - (optind + 2); uint8_t byte_count; for (byte_count = 0; byte_count < sendb.num_bytes; byte_count++) { sendb.buff[byte_count] = (uint8_t)strtol(argv[byte_count + optind + 2], NULL, 0); } /* send bytes */ if ((ret = g_oreoled->send_cmd(sendb)) != OK) { errx(1, "failed to send command"); } else { warnx("sent %d bytes", (int)sendb.num_bytes); } exit(ret); } oreoled_usage(); exit(0); }
54,305
25,325
#include <catch/catch.hpp> #include "utils.h" #include <util/func.h> namespace tests { TEST_CASE("Test eigen vectorization", "[worker]") { cleanSystem(); message::Message msg = util::messageFactory("demo", "eigen_vec"); execFunction(msg); } }
277
89
#include "DigiKeyboard.h" #define PIN_BUTTON 1 #define KEY_ESC 41 void setup() { } // setup() void loop() { while ( digitalRead(PIN_BUTTON) == 0 ) { DigiKeyboard.delay(10); } DigiKeyboard.update(); DigiKeyboard.sendKeyPress(KEY_ESC,0); DigiKeyboard.delay(200); DigiKeyboard.sendKeyPress(0,0); while ( digitalRead(PIN_BUTTON) == 1 ) { DigiKeyboard.delay(10); } DigiKeyboard.delay(100); } // loop()
451
232
/*============================================================================= Spirit v1.6.0 Copyright (c) 2001-2003 Joel de Guzman http://spirit.sourceforge.net/ Permission to copy, use, modify, sell and distribute this software is granted provided this copyright notice appears in all copies. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose. =============================================================================*/ #ifndef BOOST_SPIRIT_RANGE_RUN_IPP #define BOOST_SPIRIT_RANGE_RUN_IPP /////////////////////////////////////////////////////////////////////////////// #if !defined(BOOST_SPIRIT_RANGE_RUN_HPP) #include "boost/spirit/utility/impl/chset/range_run.hpp" #endif #if !defined(BOOST_SPIRIT_MAIN_DEBUG_HPP) #include "boost/spirit/debug.hpp" #endif #if !defined(BOOST_LIMITS_HPP) #include "boost/limits.hpp" #endif /////////////////////////////////////////////////////////////////////////////// namespace boost { namespace spirit { namespace impl { /////////////////////////////////////////////////////////////////////// // // range class implementation // /////////////////////////////////////////////////////////////////////// template <typename CharT> inline range<CharT>::range(CharT first_, CharT last_) : first(first_), last(last_) {} ////////////////////////////////// template <typename CharT> inline bool range<CharT>::is_valid() const { return first <= last; } ////////////////////////////////// template <typename CharT> inline bool range<CharT>::includes(range const& r) const { return (first <= r.first) && (last >= r.last); } ////////////////////////////////// template <typename CharT> inline bool range<CharT>::includes(CharT v) const { return (first <= v) && (last >= v); } ////////////////////////////////// template <typename CharT> inline bool range<CharT>::is_adjacent(range const& r) const { CharT decr_first = first == std::numeric_limits<CharT>::min() ? first : first-1; CharT incr_last = last == std::numeric_limits<CharT>::max() ? last : last+1; return ((decr_first <= r.first) && (incr_last >= r.first)) || ((decr_first <= r.last) && (incr_last >= r.last)); } ////////////////////////////////// template <typename CharT> inline void range<CharT>::merge(range const& r) { first = std::min(first, r.first); last = std::max(last, r.last); } /////////////////////////////////////////////////////////////////////// // // range_run class implementation // /////////////////////////////////////////////////////////////////////// template <typename CharT> inline bool range_run<CharT>::test(CharT v) const { if (!run.empty()) { const_iterator iter = std::lower_bound( run.begin(), run.end(), v, range_char_compare<CharT>() ); if (iter != run.end() && iter->includes(v)) return true; if (iter != run.begin()) return (--iter)->includes(v); } return false; } ////////////////////////////////// template <typename CharT> inline void range_run<CharT>::swap(range_run& rr) { run.swap(rr.run); } ////////////////////////////////// template <typename CharT> void range_run<CharT>::merge(iterator iter, range<CharT> const& r) { iter->merge(r); iterator i = iter + 1; while (i != run.end() && iter->is_adjacent(*i)) iter->merge(*i++); run.erase(iter+1, i); } ////////////////////////////////// template <typename CharT> void range_run<CharT>::set(range<CharT> const& r) { BOOST_SPIRIT_ASSERT(r.is_valid()); if (!run.empty()) { iterator iter = std::lower_bound( run.begin(), run.end(), r, range_compare<CharT>() ); if (iter != run.end() && iter->includes(r) || ((iter != run.begin()) && (iter - 1)->includes(r))) return; if (iter != run.begin() && (iter - 1)->is_adjacent(r)) merge(--iter, r); else if (iter != run.end() && iter->is_adjacent(r)) merge(iter, r); else run.insert(iter, r); } else { run.push_back(r); } } ////////////////////////////////// template <typename CharT> void range_run<CharT>::clear(range<CharT> const& r) { BOOST_SPIRIT_ASSERT(r.is_valid()); if (!run.empty()) { iterator iter = std::lower_bound( run.begin(), run.end(), r, range_compare<CharT>() ); iterator left_iter; if ((iter != run.begin()) && (left_iter = (iter - 1))->includes(r.first)) if (left_iter->last > r.last) { CharT save_last = left_iter->last; left_iter->last = r.first-1; run.insert(iter, range<CharT>(r.last+1, save_last)); return; } else { left_iter->last = r.first-1; } iterator i = iter; while (i != run.end() && r.includes(*i)) i++; if (i != run.end() && i->includes(r.last)) i->first = r.last+1; run.erase(iter, i); } } ////////////////////////////////// template <typename CharT> inline void range_run<CharT>::clear() { run.clear(); } ////////////////////////////////// template <typename CharT> inline typename range_run<CharT>::const_iterator range_run<CharT>::begin() const { return run.begin(); } ////////////////////////////////// template <typename CharT> inline typename range_run<CharT>::const_iterator range_run<CharT>::end() const { return run.end(); } } // namespace impl }} // namespace boost::spirit #endif
7,295
1,972
// Copyright (c) 2020 ETH Zurich // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #pragma once #include <pika/config.hpp> #include <pika/functional/function.hpp> namespace pika { namespace parallel { namespace util { namespace detail { using parallel_exception_termination_handler_type = pika::util::function<void()>; PIKA_EXPORT void set_parallel_exception_termination_handler( parallel_exception_termination_handler_type f); PIKA_NORETURN PIKA_EXPORT void parallel_exception_termination_handler(); }}}} // namespace pika::parallel::util::detail
730
245
/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | https://www.mrpt.org/ | | | | Copyright (c) 2005-2022, Individual contributors, see AUTHORS file | | See: https://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See: https://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #include "camera_calib_guiApp.h" //(*AppHeaders #include <wx/image.h> #include "camera_calib_guiMain.h" //*) #include <wx/log.h> IMPLEMENT_APP(camera_calib_guiApp) bool camera_calib_guiApp::OnInit() { // Starting in wxWidgets 2.9.0, we must reset numerics locale to "C", // if we want numbers to use "." in all countries. The App::OnInit() is a // perfect place to undo // the default wxWidgets settings. (JL @ Sep-2009) wxSetlocale(LC_NUMERIC, wxString(wxT("C"))); //(*AppInitialize bool wxsOK = true; wxInitAllImageHandlers(); if (wxsOK) { camera_calib_guiDialog Dlg(nullptr); SetTopWindow(&Dlg); Dlg.ShowModal(); wxsOK = false; } //*) return wxsOK; }
1,312
438
/*----------------------------------------------------------------------------/ Lovyan GFX - Graphics library for embedded devices. Original Source: https://github.com/lovyan03/LovyanGFX/ Licence: [FreeBSD](https://github.com/lovyan03/LovyanGFX/blob/master/license.txt) Author: [lovyan03](https://twitter.com/lovyan03) Contributors: [ciniml](https://github.com/ciniml) [mongonta0716](https://github.com/mongonta0716) [tobozo](https://github.com/tobozo) /----------------------------------------------------------------------------*/ #if defined (ESP32) || defined (CONFIG_IDF_TARGET_ESP32) || defined (CONFIG_IDF_TARGET_ESP32S2) || defined (ESP_PLATFORM) #include "Light_PWM.hpp" #if defined ARDUINO #include <esp32-hal-ledc.h> #else #include <driver/ledc.h> #endif namespace lgfx { inline namespace v1 { //---------------------------------------------------------------------------- void Light_PWM::init(std::uint8_t brightness) { #ifdef ARDUINO ledcSetup(_cfg.pwm_channel, _cfg.freq, 8); ledcAttachPin(_cfg.pin_bl, _cfg.pwm_channel); #else static ledc_channel_config_t ledc_channel; { ledc_channel.gpio_num = (gpio_num_t)_cfg.pin_bl; #if SOC_LEDC_SUPPORT_HS_MODE ledc_channel.speed_mode = LEDC_HIGH_SPEED_MODE; #else ledc_channel.speed_mode = LEDC_LOW_SPEED_MODE; #endif ledc_channel.channel = (ledc_channel_t)_cfg.pwm_channel; ledc_channel.intr_type = LEDC_INTR_DISABLE; ledc_channel.timer_sel = (ledc_timer_t)((_cfg.pwm_channel >> 1) & 3); ledc_channel.duty = _cfg.invert ? 256 : 0; ledc_channel.hpoint = 0; }; ledc_channel_config(&ledc_channel); static ledc_timer_config_t ledc_timer; { #if SOC_LEDC_SUPPORT_HS_MODE ledc_timer.speed_mode = LEDC_HIGH_SPEED_MODE; // timer mode #else ledc_timer.speed_mode = LEDC_LOW_SPEED_MODE; #endif ledc_timer.duty_resolution = (ledc_timer_bit_t)8; // resolution of PWM duty ledc_timer.freq_hz = _cfg.freq; // frequency of PWM signal ledc_timer.timer_num = ledc_channel.timer_sel; // timer index }; ledc_timer_config(&ledc_timer); #endif setBrightness(brightness); } void Light_PWM::setBrightness(std::uint8_t brightness) { if (_cfg.invert) brightness = ~brightness; std::uint32_t duty = brightness + (brightness >> 7); #ifdef ARDUINO ledcWrite(_cfg.pwm_channel, duty); #elif SOC_LEDC_SUPPORT_HS_MODE ledc_set_duty(LEDC_HIGH_SPEED_MODE, (ledc_channel_t)_cfg.pwm_channel, duty); ledc_update_duty(LEDC_HIGH_SPEED_MODE, (ledc_channel_t)_cfg.pwm_channel); #else ledc_set_duty(LEDC_LOW_SPEED_MODE, (ledc_channel_t)_cfg.pwm_channel, duty); ledc_update_duty(LEDC_LOW_SPEED_MODE, (ledc_channel_t)_cfg.pwm_channel); #endif } //---------------------------------------------------------------------------- } } #endif
2,879
1,151
// Copyright (C) 2018-2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "transformations/convert_subtract.hpp" #include <memory> #include <vector> #include <ngraph/opsets/opset1.hpp> void ngraph::pass::ConvertSubtract::convert_subtract() { auto input0 = std::make_shared<pattern::op::Label>(element::i64, Shape{1, 1, 1, 1}); auto input1 = std::make_shared<pattern::op::Label>(element::i64, Shape{1, 1, 1, 1}); auto sub = std::make_shared<ngraph::opset1::Subtract>(input0, input1); ngraph::graph_rewrite_callback callback = [](pattern::Matcher& m) { auto sub = std::dynamic_pointer_cast<ngraph::opset1::Subtract> (m.get_match_root()); if (!sub) { return false; } auto neg = std::make_shared<ngraph::opset1::Multiply>(sub->input(1).get_source_output(), opset1::Constant::create(sub->get_input_element_type(1), Shape{1}, {-1})); auto add = std::make_shared<ngraph::opset1::Add>(sub->input(0).get_source_output(), neg); add->set_friendly_name(sub->get_friendly_name()); ngraph::replace_node(sub, add); return true; }; auto m = std::make_shared<ngraph::pattern::Matcher>(sub, "ConvertSubtract"); this->add_matcher(m, callback, PassProperty::CHANGE_DYNAMIC_STATE); }
1,360
485
#pragma once #include <SFML/Graphics.hpp> #include "global_defines.hpp" #include "game_entity.hpp" #include "utils.hpp" /** * @brief Class for the Entity representing the HUD */ class HUD : public GameEntity { private: protected: public: /** * @brief Create the HUD Entity * * @param _manager The global GameManager pointer * @param parent The parent GameEntity node */ HUD(GameManager *_manager, GameEntity *parent); /** * @brief Update the HUD */ virtual void update() override; /** * @brief Draw the HUD * * @param renderer The RenderTarget to draw to */ virtual void draw(sf::RenderTarget &renderer) const override; /** * @brief font for the HUD */ static sf::Font entryFont; /** * @brief Constructs the Gun Info Pane as a Drawable Group * * @param gun The gun * @param compareGun The gun to compare to * * @return Drawable Group of Gun Info */ static utils::DrawableGroup craftGunInfo(Gun *gun, Gun *compareGun = nullptr); /** * @brief Construct the Mini Gun Info Pane as a Drawable Group * * @param gun The gun * * @return Drawable Group of Gun Info */ static utils::DrawableGroup craftGunMiniInfo(Gun *gun); };
1,346
477
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include <memory> #include <transformations_visibility.hpp> #include <ngraph/function.hpp> #include <ngraph/op/op.hpp> #include <ngraph/rt_info.hpp> #include <ngraph/pass/manager.hpp> #include "snippets/generator.hpp" namespace ngraph { namespace snippets { namespace op { /** * @interface Subgraph * @brief An operation that is implemented by a function * @ingroup snippets */ class TRANSFORMATIONS_API Subgraph : public ngraph::op::Op { public: // < 1, 42, 17, 15, 16> < 0, 1, 2, 3, 1> // should be: // A = < 1, 42, 17, 15> -> < 1, 3, 17, 15, 16> < 0, 1, 2, 3, 1> // B = < 1, 1, 17, 15> -> < 1, 1, 17, 15, 16> < 0, 1, 2, 3, 1> // D = < 1, 42, 1, 1 > -> < 1, 3, 1, 1, 16> < 0, 1, 2, 3, 1> ??? // C = A + B // C = < 1, 42, 17, 15> -> < 1, 3, 17, 15, 16> < 0, 1, 2, 3, 1> // // how it works now (multi-demention broadcast): // [BroadcastLoad] doesn't perform post increment // [Load] performs += vlan // [ScalarLoad] performs += 1 // A = < 1, 42, 17, 15> -> < 1, 3, 17, 15, 16> < 0, 1, 2, 3, 1> // B = < 1, 1, 17, 15> -> < 1, 1, 17, 15, 1> < 0, 1, 2, 3, 1> // [A] [B] // [Load] [ScalarLoad] <- should consider AxisVector to choose right type of load // [Broadcast] // [Add] // [Store] // [C] // C = A + B // C = < 1, 42, 17, 15> -> < 1, 3, 17, 15, 16> < 0, 1, 2, 3, 1> // // Multiple-dimension broadcasts support? // A = < 1, 42, 17, 15> -> < 1, 3, 17, 15, 16> < 0, 1, 2, 3, 4> // B = < 1, 1, 17, 15> -> < 1, 1, 17, 15, 1> < 0, 1, 2, 3, 4> // // A = < 1, 42, 17, 15> -> < 1, 3, 17, 15, 16> < 0, 1, 2, 3, 4> // B = < 1, 1, 17, 15> -> < 1, 3, 17, 15, 1> < 0, 1, 2, 3, 4> // // Collapse moat varying dimensions with broadcast // A = < 1, 42, 17, 15> -> < 1, 3, 17, 15, 16> < 0, 1, 2, 3, 1> // B = < 1, 1, 17, 15> -> < 1, 3, 17, 15, 1> < 0, 1, 2, 3, 1> // // Collapse for mixed broadcast // A = < 1, 3, 17, 15, 32> < 0, 1, 2, 3, 4> // B = < 1, 3, 17, 1, 32> < 0, 1, 2, 3, 4> // C = < 1, 3, 1, 15, 32> < 0, 1, 2, 3, 4> // // D = < 1, 3, 17, 15, 32> < 0, 1, 2, 3, 4> // E = < 1, 3, 17, 1, 32> < 0, 1, 2, 3, 4> using BlockedShape = std::tuple<ngraph::Shape, ngraph::AxisVector, ngraph::element::Type>; using BlockedShapeVector = std::vector<BlockedShape>; NGRAPH_RTTI_DECLARATION; Subgraph(const OutputVector& args, std::shared_ptr<Function> body); Subgraph(const NodeVector& args, std::shared_ptr<Function> body); bool visit_attributes(AttributeVisitor& visitor) override; void validate_and_infer_types() override; std::shared_ptr<Node> clone_with_new_inputs(const OutputVector& inputs) const override; std::shared_ptr<Function> get_body() const { return m_body; } std::shared_ptr<ngraph::snippets::Generator> get_generator() const { return m_generator; } std::shared_ptr<Subgraph> make_canonical_from_this(); snippets::Schedule generate(const BlockedShapeVector& output_shapes, const BlockedShapeVector& input_shapes, ngraph::pass::Manager opt = ngraph::pass::Manager()); bool evaluate(const HostTensorVector& output_values, const HostTensorVector& input_values) const override; /// Set a new body for the op; body needs to satisfy requirements on inputs/outputs void set_body(std::shared_ptr<Function> body); // plugin sets generator for a snippet to some specific generator. // it's going to be replaced with Jitters table later void set_generator(std::shared_ptr<ngraph::snippets::Generator> generator); void print() const; void print_statistics(bool verbose); void serialize() const; static auto wrap_node_as_subgraph(const std::shared_ptr<ngraph::Node>& node) -> std::shared_ptr<Subgraph>; private: void canonicalize(const BlockedShapeVector& output_shapes, const BlockedShapeVector& input_shapes); void convert_to_snippet_dialect(); std::shared_ptr<Function> m_body; std::shared_ptr<ngraph::snippets::Generator> m_generator; }; static inline std::ostream& operator<<(std::ostream& os, const op::Subgraph::BlockedShape& blocked_shape) { os << std::get<0>(blocked_shape) << " " << std::get<1>(blocked_shape) << " " << std::get<2>(blocked_shape); return os; } static inline auto is_scalar_constant(const std::shared_ptr<ngraph::Node>& source_output_node) -> bool { return !!ngraph::as_type_ptr<ngraph::opset1::Constant>(source_output_node) && (source_output_node->get_shape() == ngraph::Shape() || ngraph::shape_size(source_output_node->get_shape()) == 1); }; static inline auto create_body(std::string name, const ngraph::ResultVector& results, const ngraph::ParameterVector& parameters) -> std::shared_ptr<ngraph::Function> { auto body = std::make_shared<ngraph::Function>(results, parameters, name); return body; }; static inline auto build_subgraph(const std::shared_ptr<ngraph::Node>& node, const ngraph::OutputVector& inputs, const std::shared_ptr<ngraph::Function>& body) -> std::shared_ptr<Subgraph>{ auto subgraph = std::make_shared<Subgraph>(inputs, body); copy_runtime_info(node, subgraph); subgraph->set_friendly_name(node->get_friendly_name()); return subgraph; }; } // namespace op } // namespace snippets } // namespace ngraph
5,484
2,326
#include<iostream> #include"Point.h" using namespace std; /** * @file : PointCloudTEST.cpp * @Author : Muzaffer Arda Uslu (usluarda58@gmail.com) * @date : 12 Aralik 2019, Persembe * @brief : Bu kod parcacigi olusturulan Point sinifinin dogru calisip calismadigini kontrol etmek amaciyla yazilmistir. */ int main() { Point P1, P2; P1.setX(1); P1.setY(2); P1.setZ(3); P2.setX(4); P2.setY(5); P2.setZ(6); cout << "P1 x->" << P1.getX() << " y->" << P1.getY() << " z->" << P1.getZ() << endl; cout << "P2 x->" << P2.getX() << " y->" << P2.getY() << " z->" << P2.getZ() << endl; if (P1 == P2) cout << "Point nesneleri ayni!" << endl; else cout << "Point nesneleri ayni degil!" << endl; cout << "P1 ve P2 arasindaki uzaklik -> " << P1.distance(P2) << endl; system("pause"); }
792
393
// Generated by imageconverter. Please, do not edit! #include <touchgfx/hal/Config.hpp> LOCATION_EXTFLASH_PRAGMA KEEP extern const unsigned char _toggle_off[] LOCATION_EXTFLASH_ATTRIBUTE = { // 90x70 ARGB8888 pixels. 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00, 0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00, 0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00, 0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00, 0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x0c, 0xff,0xff,0xff,0x1b,0xff,0xff,0xff,0x27,0xff,0xff,0xff,0x2e,0xff,0xff,0xff,0x32,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x32,0xff,0xff,0xff,0x2e,0xff,0xff,0xff,0x27,0xff,0xff,0xff,0x1c,0xff,0xff,0xff,0x0c,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00, 0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x14,0xff,0xff,0xff,0x2c,0xf6,0xf5,0xf2,0x35,0xdf,0xdc,0xd3,0x3b,0xcf,0xcb,0xbe,0x40,0xc4,0xbf,0xaf,0x44,0xc1,0xbc,0xab,0x45,0xc2,0xbc,0xac,0x45,0xc6,0xc2,0xb3,0x43, 0xcf,0xcb,0xbe,0x40,0xdf,0xdc,0xd3,0x3b,0xf6,0xf5,0xf2,0x35,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x2c,0xff,0xff,0xff,0x14,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x07, 0xff,0xff,0xff,0x28,0xf2,0xf1,0xed,0x36,0xd5,0xd2,0xc6,0x3e,0xb7,0xb1,0x9e,0x49,0x9e,0x97,0x7d,0x56,0x8f,0x86,0x68,0x61,0x87,0x7d,0x5d,0x68,0x84,0x79,0x59,0x6b,0x84,0x79,0x59,0x6b,0x88,0x7e,0x5e,0x67,0x8f,0x86,0x68,0x61,0x9e,0x97,0x7d,0x56,0xb7,0xb1,0x9e,0x49,0xd5,0xd2,0xc6,0x3e,0xf2,0xf1,0xed,0x36,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x28,0xff,0xff,0xff,0x07,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x0d,0xf6,0xf5,0xf2,0x31,0xd8,0xd5,0xcb,0x3d,0xb6,0xb0,0x9c,0x4a,0x97,0x8f,0x73,0x5b,0x96,0x8c,0x71,0x75,0xca,0xc6,0xb8,0xae,0xe8,0xe6,0xe0,0xd7, 0xf6,0xf5,0xf3,0xf0,0xfd,0xfd,0xfd,0xfc,0xfc,0xfb,0xfb,0xf9,0xf3,0xf2,0xef,0xeb,0xe8,0xe6,0xe0,0xd7,0xca,0xc6,0xb8,0xae,0x96,0x8c,0x71,0x75,0x97,0x8f,0x73,0x5b,0xb6,0xb0,0x9c,0x4a,0xd8,0xd5,0xcb,0x3d,0xf6,0xf5,0xf2,0x35,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x2f,0xff,0xff,0xff,0x0c,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00, 0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x0e,0xf6,0xf5,0xf2,0x34,0xcc,0xc8,0xbb,0x41,0x9e,0x97,0x7d,0x56,0x8d,0x82,0x65,0x70,0xd1,0xcd,0xc1,0xb8,0xfb,0xfa,0xf9,0xf7,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xfb,0xfa,0xf9,0xf7,0xd1,0xcd,0xc1,0xb9,0x8e,0x84,0x66,0x70,0x9e,0x97,0x7d,0x56,0xcc,0xc8,0xbb,0x41,0xf6,0xf5,0xf2,0x35,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x32,0xff,0xff,0xff,0x0e,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x08,0xf7,0xf5,0xf3,0x32,0xcf,0xcb,0xbe,0x40,0x9a,0x92,0x77,0x59,0x9d,0x94,0x7b,0x83,0xf2,0xf1,0xed,0xe9, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xf2,0xf1,0xed,0xe9,0x9d,0x94,0x7b,0x83,0x9a,0x92,0x77,0x59,0xcf,0xcb,0xbe,0x40, 0xf7,0xf5,0xf3,0x35,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x31,0xff,0xff,0xff,0x08,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x01,0xff,0xff,0xff,0x28,0xdc,0xd9,0xd0,0x3c,0xa0,0x98,0x7f,0x55,0x9a,0x90,0x76,0x81,0xf7,0xf6,0xf4,0xf1,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xf7,0xf6,0xf4,0xf1,0x9a,0x90,0x76,0x81,0xa0,0x98,0x7f,0x55,0xdc,0xd9,0xd0,0x3c,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x28,0xff,0xff,0xff,0x01,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x14,0xf2,0xf1,0xed,0x36,0xb6,0xb0,0x9c,0x4a, 0x8e,0x83,0x66,0x6f,0xef,0xee,0xea,0xe4,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xef,0xee,0xea,0xe4,0x8f,0x85,0x68,0x6f,0xb6,0xb0,0x9c,0x4a,0xf2,0xf1,0xed,0x36,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x14,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x2c,0xd5,0xd2,0xc6,0x3e,0x97,0x8f,0x73,0x5b,0xd0,0xcc,0xbf,0xb8,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xd1,0xcd,0xc1,0xb8,0x95,0x8d,0x71,0x5c,0xd5,0xd2,0xc6,0x3e, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x2c,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00, 0xff,0xff,0xff,0x0d,0xf6,0xf5,0xf2,0x35,0xb7,0xb1,0x9e,0x49,0x97,0x8d,0x72,0x75,0xfb,0xfb,0xfa,0xf7,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xfb,0xfb,0xfa,0xf7,0x97,0x8d,0x72,0x75,0xb7,0xb1,0x9e,0x49,0xf6,0xf5,0xf2,0x35,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x0d,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x1b,0xdf,0xdc,0xd3,0x3b,0x9e,0x97,0x7d,0x56,0xcb,0xc7,0xb9,0xaf,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xcb,0xc7,0xb9,0xaf,0x9e,0x97,0x7d,0x56,0xdf,0xdc,0xd3,0x3b,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x1b,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x27,0xcf,0xcb,0xbe,0x40,0x8f,0x86,0x68,0x61,0xe7,0xe5,0xdf,0xd7,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xe8,0xe6,0xe0,0xd7,0x8f,0x86,0x68,0x61,0xcf,0xcb,0xbe,0x40,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x27,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x2e,0xc4,0xbf,0xaf,0x44, 0x87,0x7d,0x5d,0x68,0xf7,0xf6,0xf4,0xf0,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xf7,0xf6,0xf4,0xf0,0x87,0x7d,0x5d,0x68,0xc4,0xbf,0xaf,0x44,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x2e, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x32,0xc1,0xbc,0xab,0x45,0x84,0x79,0x59,0x6b,0xfd,0xfd,0xfd,0xfc,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xfd,0xfd,0xfd,0xfc,0x84,0x79,0x59,0x6b,0xc1,0xbc,0xab,0x45,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x32,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x32,0xc2,0xbc,0xac,0x45,0x84,0x79,0x59,0x6b,0xfc,0xfb,0xfb,0xf8,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xfd,0xfd,0xfd,0xfc,0x84,0x79,0x59,0x6b,0xc1,0xbc,0xab,0x45,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x32,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x2e,0xc6,0xc2,0xb3,0x43,0x88,0x7e,0x5e,0x67,0xf3,0xf2,0xef,0xec, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xf7,0xf6,0xf4,0xf0,0x87,0x7d,0x5d,0x68,0xc4,0xbf,0xaf,0x44,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x2e,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x27,0xcf,0xcb,0xbe,0x40,0x8f,0x86,0x68,0x61,0xe7,0xe5,0xdf,0xd7,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xe8,0xe6,0xe0,0xd7,0x8f,0x86,0x68,0x61, 0xcf,0xcb,0xbe,0x40,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x27,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00, 0xff,0xff,0xff,0x1c,0xdf,0xdc,0xd3,0x3b,0x9e,0x97,0x7d,0x56,0xcb,0xc7,0xb9,0xaf,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xcb,0xc7,0xb9,0xaf,0x9e,0x97,0x7d,0x56,0xdf,0xdc,0xd3,0x3b,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x1b,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x0d,0xf6,0xf5,0xf2,0x35,0xb7,0xb1,0x9e,0x49,0x97,0x8d,0x72,0x75,0xfb,0xfb,0xfa,0xf7,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xfb,0xfb,0xfa,0xf7,0x97,0x8d,0x72,0x75,0xb7,0xb1,0x9e,0x49,0xf6,0xf5,0xf2,0x35,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x0d,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x2c,0xd5,0xd2,0xc6,0x3e,0x95,0x8d,0x71,0x5c,0xd1,0xcd,0xc1,0xb8,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xd1,0xcd,0xc1,0xb8,0x95,0x8d,0x71,0x5c,0xd5,0xd2,0xc6,0x3e,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x2c,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x14, 0xf2,0xf1,0xed,0x36,0xb6,0xb0,0x9c,0x4a,0x8e,0x84,0x66,0x70,0xf2,0xf1,0xed,0xe8,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xf2,0xf1,0xed,0xe9,0x8e,0x84,0x66,0x70,0xb6,0xb0,0x9c,0x4a,0xf2,0xf1,0xed,0x36,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x14,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x01,0xff,0xff,0xff,0x29,0xd8,0xd5,0xcb,0x3d,0x9e,0x97,0x7d,0x56,0xa0,0x98,0x7f,0x85,0xf7,0xf7,0xf5,0xf2,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xf7,0xf7,0xf5,0xf1,0xa0,0x98,0x7f,0x85,0x9e,0x97,0x7d,0x56, 0xd8,0xd5,0xcb,0x3d,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x29,0xff,0xff,0xff,0x01,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x08,0xf6,0xf5,0xf2,0x33,0xcc,0xc8,0xbb,0x41,0x9a,0x92,0x77,0x59,0x9e,0x95,0x7c,0x83,0xf2,0xf1,0xed,0xe9,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xf2,0xf1,0xed,0xe9,0x9d,0x94,0x7b,0x83,0x9a,0x92,0x77,0x59,0xcc,0xc8,0xbb,0x41,0xf6,0xf5,0xf2,0x35,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x31,0xff,0xff,0xff,0x08,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x0f, 0xf6,0xf5,0xf2,0x34,0xcc,0xc8,0xbb,0x41,0x9e,0x97,0x7d,0x56,0x8e,0x84,0x66,0x70,0xd1,0xcd,0xc1,0xb9,0xfb,0xfa,0xf9,0xf7,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xfb,0xfa,0xf9,0xf7,0xd1,0xcd,0xc1,0xb9, 0x8e,0x84,0x66,0x70,0x9e,0x97,0x7d,0x56,0xcc,0xc8,0xbb,0x41,0xf6,0xf5,0xf2,0x35,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x32,0xff,0xff,0xff,0x0f,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x0f,0xf6,0xf5,0xf2,0x33,0xd8,0xd5,0xcb,0x3d,0xb6,0xb0,0x9c,0x4a,0x97,0x8f,0x73,0x5b,0x96,0x8c,0x71,0x75, 0xcb,0xc7,0xb9,0xaf,0xe8,0xe6,0xe0,0xd7,0xf6,0xf5,0xf3,0xf0,0xfd,0xfd,0xfd,0xfd,0xfd,0xfd,0xfd,0xfd,0xf6,0xf5,0xf3,0xf0,0xe8,0xe6,0xe0,0xd7,0xcb,0xc7,0xb9,0xaf,0x96,0x8c,0x71,0x75,0x97,0x8f,0x73,0x5b,0xb6,0xb0,0x9c,0x4a,0xd8,0xd5,0xcb,0x3d,0xf6,0xf5,0xf2,0x35,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x31,0xff,0xff,0xff,0x0f,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00, 0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x08,0xff,0xff,0xff,0x29,0xf2,0xf1,0xed,0x36,0xd5,0xd2,0xc6,0x3e,0xb7,0xb1,0x9e,0x49,0x9e,0x97,0x7d,0x56,0x8f,0x86,0x68,0x61,0x87,0x7d,0x5d,0x68,0x82,0x78,0x57,0x6c,0x82,0x78,0x57,0x6c,0x87,0x7d,0x5d,0x68, 0x8f,0x86,0x68,0x61,0x9e,0x97,0x7d,0x56,0xb7,0xb1,0x9e,0x49,0xd5,0xd2,0xc6,0x3e,0xf2,0xf1,0xed,0x36,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x29,0xff,0xff,0xff,0x08,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00, 0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x14,0xff,0xff,0xff,0x2c,0xf6,0xf5,0xf2,0x35,0xdf,0xdc,0xd3,0x3b,0xcf,0xcb,0xbe,0x40,0xc4,0xbf,0xaf,0x44,0xc1,0xbc,0xab,0x45,0xc1,0xbc,0xab,0x45,0xc4,0xbf,0xaf,0x44,0xcf,0xcb,0xbe,0x40,0xdf,0xdc,0xd3,0x3b,0xf6,0xf5,0xf2,0x35,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x2c,0xff,0xff,0xff,0x14,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x0c,0xff,0xff,0xff,0x1c,0xff,0xff,0xff,0x27, 0xff,0xff,0xff,0x2e,0xff,0xff,0xff,0x32,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33, 0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x32,0xff,0xff,0xff,0x2e,0xff,0xff,0xff,0x27,0xff,0xff,0xff,0x1c,0xff,0xff,0xff,0x0c,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00, 0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00, 0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00, 0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00, 0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00, 0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00,0x42,0x32,0x00,0x00, 0x42,0x32,0x00,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00, 0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00,0xff,0xff,0xff,0x00 };
126,677
108,460
/* 如果引用了iostream或者vector,又加了using namespace std;这条语句,就尽量不要使用hash这样的变量名 因为这样会跟std命名空间里面的hash变量名冲突,导致编译失败或者运行出错 这种情况解决办法要么单独用std,比如std::cin、std::endl,要么直接避开hash作为变量名(可以改用HashTable) 类似的还有math.h的y1变量名,如果将其作为全局变量,就会导致编译错误 若编译有报错或者运行莫名出错,则可以考虑这些因素 */
245
226
#include "main.h" #include "alarm.h" #include "file.h" #include <stdio.h> #include <string.h> static void print_help() { fputs("Usage: alarm set [DATE] [TIME] [OPTIONS]\n\n" "Sets an alarm at the given time.\n\n" "If --help or --version (or their short versions) are used as\n" "options, only the first one will be used, and no time or date\n" "should be specified. Otherwise, TIME is mandatory.\n\n" "DATE uses the format is YYYY-MM-DD. If the date is omitted,\n" "today's date is used if the time has not already passed;\n" "otherwise tomorrow's date is used.\n\n" "TIME is mandatory if neither --help or --version is used.\n" "The format for time is HH:MM:SS, using a 24-hour system.\n\n" "If multiple alarm levels are given, most severe one is used.\n\n" "OPTIONS can be any of the following, in (almost) any order:\n" "\t--help (-h) - display this help. If specified, this must be the first\n" "\t\toption, and neither TIME nor DATE can be specified.\n" "\t--version (-v) - display the version. If specified, this must be the\n" "\t\tfirst option, and neither TIME nor DATE can be specified.\n" "\t--critical (-c) - the alarm is of critical level\n" "\t--warning (-w) - the alarm is of warning level\n" "\t--nosleep (-ns) - prevent the user from sleeping this alarm\n" "\t--nosound (-nd) - prevent the alarm from making sound\n" "\t--novisual (-nv) - prevent the alarm from making visual effects.\n" "\t--nowake (-nk) - only raise an alarm if the computer is already awake.\n", stdout); } static void print_version() { fputs("alarm set - version 1.0\n" "last updated 2014-10-03\n", stdout); } int set_main(int argc, char **argv, const char *argstr) { Alarm alarm; FILE *f; if (argc == 0) { print_help(); return 0; } if (strcmp(argv[0], "--help") == 0 || strcmp(argv[0], "-h") == 0) { print_help(); return 0; } if (strcmp(argv[0], "--version") == 0 || strcmp(argv[0], "-v") == 0) { print_version(); return 0; } if (alarm.read_arg_str(argstr) != 0) { print_help(); return 1; } f = fopen(FILE_NAME, "a"); if (f == NULL) { file_err("a"); return 1; } if (alarm.print_file(f) != 0) { fclose(f); return 1; } fclose(f); return 0; }
2,240
920
#include <assert.h> #include <stdio.h> #include <cilk/cilk.h> #include "test.h" int global; int test1(char *arr) { int *x = (int *) &arr[2]; *x = 3; return 0; } int test2(char *arr) { int *x = (int *) &arr[0]; global = *x; return 0; } int main(void) { char arr[8] = {'0', '1', '0', '0', '0', '1', '6', '7'}; fprintf(stderr, "arr is %p.\n", arr); cilk_spawn test1(arr); test2(arr); cilk_sync; assert(__cilksan_error_count() == 1); return 0; }
480
242
#include<iostream> //array implementation of Queue-we will use a circular array using namespace std; int main() { return 0; }
131
43
/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * Created on: April 2022 * Author: Kira Duwe */ #include <chrono> #include <ios> //std::ios_base::failure #include <iostream> //std::cout #include <stdexcept> //std::invalid_argument std::exception #include <thread> #include <vector> #include <adios2.h> #include <julea.h> #include <julea-dai.h> void TestDAISettings() { /** Application variable */ std::vector<float> myFloats = {12345.6, 1, 2, 3, 4, 5, 6, 7, 8, -42.333}; std::vector<int> myInts = {333, 1, 2, 3, 4, 5, 6, 7, 8, 9}; const std::size_t Nx = myFloats.size(); const std::size_t Nx2 = myInts.size(); std::string fileName = "testFile.jb"; std::string varName = "juleaFloats"; std::string varName2 = "juleaInts"; // JDAIOperator compare = J_DAI_OP_GT; // JDAIStatistic statistic = J_DAI_STAT_MAX; // JDAITagGranularity granularity = J_DAI_TGRAN_BLOCK; std::cout << "JuleaEngineTest Writing ... " << std::endl; /** ADIOS class factory of IO class objects, DebugON is recommended */ adios2::ADIOS adios(adios2::DebugON); /*** IO class object: settings and factory of Settings: Variables, * Parameters, Transports, and Execution: Engines */ adios2::IO juleaIO = adios.DeclareIO("juleaIO"); // juleaIO.SetEngine("julea-kv"); juleaIO.SetEngine("julea-db-dai"); // juleaIO.SetEngine("julea-db"); /** global array: name, { shape (total dimensions) }, { start (local) }, * { count (local) }, all are constant dimensions */ adios2::Variable<float> juleaFloats = juleaIO.DefineVariable<float>( varName, {Nx}, {0}, {Nx}, adios2::ConstantDims); adios2::Variable<int> juleaInts = juleaIO.DefineVariable<int>( varName2, {Nx2}, {0}, {Nx2}, adios2::ConstantDims); /** Engine derived class, spawned to start IO operations */ adios2::Engine juleaWriter = juleaIO.Open(fileName, adios2::Mode::Write); // This is probably when the DAI call should happen at latest. Maybe even at earliest // j_dai_tag_feature_i(fileName, varName, "test_hot_days", J_DAI_STAT_MAX, 25, J_DAI_OP_GT, J_DAI_GRAN_BLOCK ); // j_dai_tag_feature_i(fileName, varName, "test_hot_days", statistic, 25, compare, granularity ); /** Write variable for buffering */ juleaWriter.Put<float>(juleaFloats, myFloats.data(), adios2::Mode::Deferred); juleaWriter.Put<int>(juleaInts, myInts.data(), adios2::Mode::Deferred); /** Create bp file, engine becomes unreachable after this*/ juleaWriter.Close(); } int main(int argc, char *argv[]) { /** Application variable */ std::vector<float> myFloats = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; const std::size_t Nx = myFloats.size(); int err = -1; try { std::cout << "JuleaDAITest :)" << std::endl; TestDAISettings(); std::cout << "\n JuleaDAITest :) Write variable finished \n" << std::endl; } catch (std::invalid_argument &e) { std::cout << "Invalid argument exception, STOPPING PROGRAM\n"; std::cout << e.what() << "\n"; } catch (std::ios_base::failure &e) { std::cout << "IO System base failure exception, STOPPING PROGRAM\n"; std::cout << e.what() << "\n"; } catch (std::exception &e) { std::cout << "Exception, STOPPING PROGRAM\n"; std::cout << e.what() << "\n"; } return 0; }
3,503
1,339
#if defined(__linux__) /* * Copyright (c) 2014 Craig Lilley <cralilley@gmail.com> * This software is made available under the terms of the MIT licence. * A copy of the licence can be obtained from: * http://opensource.org/licenses/MIT */ #include <cstdarg> #include <cstdio> #include <cstdlib> #include <fstream> #include <iostream> #include <sstream> #include <stdexcept> #include <string> #include <vector> #include <glob.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "serial/serial.h" using serial::PortInfo; using std::cout; using std::endl; using std::getline; using std::ifstream; using std::istringstream; using std::string; using std::vector; static vector<string> glob(const vector<string>& patterns); static string basename(const string& path); static string dirname(const string& path); static bool path_exists(const string& path); static string realpath(const string& path); static string usb_sysfs_friendly_name(const string& sys_usb_path); static vector<string> get_sysfs_info(const string& device_path); static string read_line(const string& file); static string usb_sysfs_hw_string(const string& sysfs_path); static string format(const char* format, ...); vector<string> glob(const vector<string>& patterns) { vector<string> paths_found; if (patterns.size() == 0) return paths_found; glob_t glob_results; int glob_retval = glob(patterns[0].c_str(), 0, NULL, &glob_results); vector<string>::const_iterator iter = patterns.begin(); while (++iter != patterns.end()) { glob_retval = glob(iter->c_str(), GLOB_APPEND, NULL, &glob_results); } for (int path_index = 0; path_index < glob_results.gl_pathc; path_index++) { paths_found.push_back(glob_results.gl_pathv[path_index]); } globfree(&glob_results); return paths_found; } string basename(const string& path) { size_t pos = path.rfind("/"); if (pos == std::string::npos) return path; return string(path, pos + 1, string::npos); } string dirname(const string& path) { size_t pos = path.rfind("/"); if (pos == std::string::npos) return path; else if (pos == 0) return "/"; return string(path, 0, pos); } bool path_exists(const string& path) { struct stat sb; if (stat(path.c_str(), &sb) == 0) return true; return false; } string realpath(const string& path) { char* real_path = realpath(path.c_str(), NULL); string result; if (real_path != NULL) { result = real_path; free(real_path); } return result; } string usb_sysfs_friendly_name(const string& sys_usb_path) { unsigned int device_number = 0; istringstream(read_line(sys_usb_path + "/devnum")) >> device_number; string manufacturer = read_line(sys_usb_path + "/manufacturer"); string product = read_line(sys_usb_path + "/product"); string serial = read_line(sys_usb_path + "/serial"); if (manufacturer.empty() && product.empty() && serial.empty()) return ""; return format("%s %s %s", manufacturer.c_str(), product.c_str(), serial.c_str()); } vector<string> get_sysfs_info(const string& device_path) { string device_name = basename(device_path); string friendly_name; string hardware_id; string sys_device_path = format("/sys/class/tty/%s/device", device_name.c_str()); if (device_name.compare(0, 6, "ttyUSB") == 0) { sys_device_path = dirname(dirname(realpath(sys_device_path))); if (path_exists(sys_device_path)) { friendly_name = usb_sysfs_friendly_name(sys_device_path); hardware_id = usb_sysfs_hw_string(sys_device_path); } } else if (device_name.compare(0, 6, "ttyACM") == 0) { sys_device_path = dirname(realpath(sys_device_path)); if (path_exists(sys_device_path)) { friendly_name = usb_sysfs_friendly_name(sys_device_path); hardware_id = usb_sysfs_hw_string(sys_device_path); } } else { // Try to read ID string of PCI device string sys_id_path = sys_device_path + "/id"; if (path_exists(sys_id_path)) hardware_id = read_line(sys_id_path); } if (friendly_name.empty()) friendly_name = device_name; if (hardware_id.empty()) hardware_id = "n/a"; vector<string> result; result.push_back(friendly_name); result.push_back(hardware_id); return result; } string read_line(const string& file) { ifstream ifs(file.c_str(), ifstream::in); string line; if (ifs) { getline(ifs, line); } return line; } string format(const char* format, ...) { va_list ap; size_t buffer_size_bytes = 256; string result; char* buffer = (char*)malloc(buffer_size_bytes); if (buffer == NULL) return result; bool done = false; unsigned int loop_count = 0; while (!done) { va_start(ap, format); int return_value = vsnprintf(buffer, buffer_size_bytes, format, ap); if (return_value < 0) { done = true; } else if (return_value >= buffer_size_bytes) { // Realloc and try again. buffer_size_bytes = return_value + 1; char* new_buffer_ptr = (char*)realloc(buffer, buffer_size_bytes); if (new_buffer_ptr == NULL) { done = true; } else { buffer = new_buffer_ptr; } } else { result = buffer; done = true; } va_end(ap); if (++loop_count > 5) done = true; } free(buffer); return result; } string usb_sysfs_hw_string(const string& sysfs_path) { string serial_number = read_line(sysfs_path + "/serial"); if (serial_number.length() > 0) { serial_number = format("SNR=%s", serial_number.c_str()); } string vid = read_line(sysfs_path + "/idVendor"); string pid = read_line(sysfs_path + "/idProduct"); return format("USB VID:PID=%s:%s %s", vid.c_str(), pid.c_str(), serial_number.c_str()); } vector<PortInfo> serial::list_ports() { vector<PortInfo> results; vector<string> search_globs; search_globs.push_back("/dev/ttyACM*"); search_globs.push_back("/dev/ttyS*"); search_globs.push_back("/dev/ttyUSB*"); search_globs.push_back("/dev/tty.*"); search_globs.push_back("/dev/cu.*"); vector<string> devices_found = glob(search_globs); vector<string>::iterator iter = devices_found.begin(); while (iter != devices_found.end()) { string device = *iter++; vector<string> sysfs_info = get_sysfs_info(device); string friendly_name = sysfs_info[0]; string hardware_id = sysfs_info[1]; PortInfo device_entry; device_entry.port = device; device_entry.description = friendly_name; device_entry.hardware_id = hardware_id; results.push_back(device_entry); } return results; } #endif // defined(__linux__)
7,362
2,529
// This file is auto-generated. Do not edit! #include "precomp.hpp" #include "opencl_kernels_calib3d.hpp" #ifdef HAVE_OPENCL namespace cv { namespace ocl { namespace calib3d { const struct ProgramEntry stereobm={"stereobm", "#define MAX_VAL 32767\n" "#ifndef WSZ\n" "#define WSZ 2\n" "#endif\n" "#define WSZ2 (WSZ / 2)\n" "#ifdef DEFINE_KERNEL_STEREOBM\n" "#define DISPARITY_SHIFT 4\n" "#define FILTERED ((MIN_DISP - 1) << DISPARITY_SHIFT)\n" "void calcDisp(__local short * cost, __global short * disp, int uniquenessRatio,\n" "__local int * bestDisp, __local int * bestCost, int d, int x, int y, int cols, int rows)\n" "{\n" "int best_disp = *bestDisp, best_cost = *bestCost;\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "short c = cost[0];\n" "int thresh = best_cost + (best_cost * uniquenessRatio / 100);\n" "bool notUniq = ( (c <= thresh) && (d < (best_disp - 1) || d > (best_disp + 1) ) );\n" "if (notUniq)\n" "*bestCost = FILTERED;\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "if( *bestCost != FILTERED && x < cols - WSZ2 - MIN_DISP && y < rows - WSZ2 && d == best_disp)\n" "{\n" "int d_aprox = 0;\n" "int yp =0, yn = 0;\n" "if ((0 < best_disp) && (best_disp < NUM_DISP - 1))\n" "{\n" "yp = cost[-2 * BLOCK_SIZE_Y];\n" "yn = cost[2 * BLOCK_SIZE_Y];\n" "d_aprox = yp + yn - 2 * c + abs(yp - yn);\n" "}\n" "disp[0] = (short)(((best_disp + MIN_DISP)*256 + (d_aprox != 0 ? (yp - yn) * 256 / d_aprox : 0) + 15) >> 4);\n" "}\n" "}\n" "short calcCostBorder(__global const uchar * leftptr, __global const uchar * rightptr, int x, int y, int nthread,\n" "short * costbuf, int *h, int cols, int d, short cost)\n" "{\n" "int head = (*h) % WSZ;\n" "__global const uchar * left, * right;\n" "int idx = mad24(y + WSZ2 * (2 * nthread - 1), cols, x + WSZ2 * (1 - 2 * nthread));\n" "left = leftptr + idx;\n" "right = rightptr + (idx - d);\n" "short costdiff = 0;\n" "if (0 == nthread)\n" "{\n" "#pragma unroll\n" "for (int i = 0; i < WSZ; i++)\n" "{\n" "costdiff += abs( left[0] - right[0] );\n" "left += cols;\n" "right += cols;\n" "}\n" "}\n" "else\n" "{\n" "#pragma unroll\n" "for (int i = 0; i < WSZ; i++)\n" "{\n" "costdiff += abs(left[i] - right[i]);\n" "}\n" "}\n" "cost += costdiff - costbuf[head];\n" "costbuf[head] = costdiff;\n" "*h = head + 1;\n" "return cost;\n" "}\n" "short calcCostInside(__global const uchar * leftptr, __global const uchar * rightptr, int x, int y,\n" "int cols, int d, short cost_up_left, short cost_up, short cost_left)\n" "{\n" "__global const uchar * left, * right;\n" "int idx = mad24(y - WSZ2 - 1, cols, x - WSZ2 - 1);\n" "left = leftptr + idx;\n" "right = rightptr + (idx - d);\n" "int idx2 = WSZ*cols;\n" "uchar corrner1 = abs(left[0] - right[0]),\n" "corrner2 = abs(left[WSZ] - right[WSZ]),\n" "corrner3 = abs(left[idx2] - right[idx2]),\n" "corrner4 = abs(left[idx2 + WSZ] - right[idx2 + WSZ]);\n" "return cost_up + cost_left - cost_up_left + corrner1 -\n" "corrner2 - corrner3 + corrner4;\n" "}\n" "__kernel void stereoBM(__global const uchar * leftptr,\n" "__global const uchar * rightptr,\n" "__global uchar * dispptr, int disp_step, int disp_offset,\n" "int rows, int cols,\n" "int textureTreshold, int uniquenessRatio)\n" "{\n" "int lz = get_local_id(0);\n" "int gx = get_global_id(1) * BLOCK_SIZE_X;\n" "int gy = get_global_id(2) * BLOCK_SIZE_Y;\n" "int nthread = lz / NUM_DISP;\n" "int disp_idx = lz % NUM_DISP;\n" "__global short * disp;\n" "__global const uchar * left, * right;\n" "__local short costFunc[2 * BLOCK_SIZE_Y * NUM_DISP];\n" "__local short * cost;\n" "__local int best_disp[2];\n" "__local int best_cost[2];\n" "best_cost[nthread] = MAX_VAL;\n" "best_disp[nthread] = -1;\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "short costbuf[WSZ];\n" "int head = 0;\n" "int shiftX = WSZ2 + NUM_DISP + MIN_DISP - 1;\n" "int shiftY = WSZ2;\n" "int x = gx + shiftX, y = gy + shiftY, lx = 0, ly = 0;\n" "int costIdx = disp_idx * 2 * BLOCK_SIZE_Y + (BLOCK_SIZE_Y - 1);\n" "cost = costFunc + costIdx;\n" "int tempcost = 0;\n" "if (x < cols - WSZ2 - MIN_DISP && y < rows - WSZ2)\n" "{\n" "if (0 == nthread)\n" "{\n" "#pragma unroll\n" "for (int i = 0; i < WSZ; i++)\n" "{\n" "int idx = mad24(y - WSZ2, cols, x - WSZ2 + i);\n" "left = leftptr + idx;\n" "right = rightptr + (idx - disp_idx);\n" "short costdiff = 0;\n" "for(int j = 0; j < WSZ; j++)\n" "{\n" "costdiff += abs( left[0] - right[0] );\n" "left += cols;\n" "right += cols;\n" "}\n" "costbuf[i] = costdiff;\n" "}\n" "}\n" "else\n" "{\n" "#pragma unroll\n" "for (int i = 0; i < WSZ; i++)\n" "{\n" "int idx = mad24(y - WSZ2 + i, cols, x - WSZ2);\n" "left = leftptr + idx;\n" "right = rightptr + (idx - disp_idx);\n" "short costdiff = 0;\n" "for (int j = 0; j < WSZ; j++)\n" "{\n" "costdiff += abs( left[j] - right[j]);\n" "}\n" "tempcost += costdiff;\n" "costbuf[i] = costdiff;\n" "}\n" "}\n" "}\n" "if (nthread == 1)\n" "{\n" "cost[0] = tempcost;\n" "atomic_min(best_cost + 1, tempcost);\n" "}\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "if (best_cost[1] == tempcost)\n" "atomic_max(best_disp + 1, disp_idx);\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "int dispIdx = mad24(gy, disp_step, mad24((int)sizeof(short), gx, disp_offset));\n" "disp = (__global short *)(dispptr + dispIdx);\n" "calcDisp(cost, disp, uniquenessRatio, best_disp + 1, best_cost + 1, disp_idx, x, y, cols, rows);\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "lx = 1 - nthread;\n" "ly = nthread;\n" "for (int i = 0; i < BLOCK_SIZE_Y * BLOCK_SIZE_X / 2; i++)\n" "{\n" "x = (lx < BLOCK_SIZE_X) ? gx + shiftX + lx : cols;\n" "y = (ly < BLOCK_SIZE_Y) ? gy + shiftY + ly : rows;\n" "best_cost[nthread] = MAX_VAL;\n" "best_disp[nthread] = -1;\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "costIdx = mad24(2 * BLOCK_SIZE_Y, disp_idx, (BLOCK_SIZE_Y - 1 - ly + lx));\n" "if (0 > costIdx)\n" "costIdx = BLOCK_SIZE_Y - 1;\n" "cost = costFunc + costIdx;\n" "if (x < cols - WSZ2 - MIN_DISP && y < rows - WSZ2)\n" "{\n" "tempcost = (ly * (1 - nthread) + lx * nthread == 0) ?\n" "calcCostBorder(leftptr, rightptr, x, y, nthread, costbuf, &head, cols, disp_idx, cost[2*nthread-1]) :\n" "calcCostInside(leftptr, rightptr, x, y, cols, disp_idx, cost[0], cost[1], cost[-1]);\n" "}\n" "cost[0] = tempcost;\n" "atomic_min(best_cost + nthread, tempcost);\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "if (best_cost[nthread] == tempcost)\n" "atomic_max(best_disp + nthread, disp_idx);\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "dispIdx = mad24(gy + ly, disp_step, mad24((int)sizeof(short), (gx + lx), disp_offset));\n" "disp = (__global short *)(dispptr + dispIdx);\n" "calcDisp(cost, disp, uniquenessRatio, best_disp + nthread, best_cost + nthread, disp_idx, x, y, cols, rows);\n" "barrier(CLK_LOCAL_MEM_FENCE);\n" "if (lx + nthread - 1 == ly)\n" "{\n" "lx = (lx + nthread + 1) * (1 - nthread);\n" "ly = (ly + 1) * nthread;\n" "}\n" "else\n" "{\n" "lx += nthread;\n" "ly = ly - nthread + 1;\n" "}\n" "}\n" "}\n" "#endif\n" "__kernel void prefilter_norm(__global unsigned char *input, __global unsigned char *output,\n" "int rows, int cols, int prefilterCap, int scale_g, int scale_s)\n" "{\n" "int x = get_global_id(0);\n" "int y = get_global_id(1);\n" "if(x < cols && y < rows)\n" "{\n" "int cov1 = input[ max(y-1, 0) * cols + x] * 1 +\n" "input[y * cols + max(x-1,0)] * 1 + input[ y * cols + x] * 4 + input[y * cols + min(x+1, cols-1)] * 1 +\n" "input[min(y+1, rows-1) * cols + x] * 1;\n" "int cov2 = 0;\n" "for(int i = -WSZ2; i < WSZ2+1; i++)\n" "for(int j = -WSZ2; j < WSZ2+1; j++)\n" "cov2 += input[clamp(y+i, 0, rows-1) * cols + clamp(x+j, 0, cols-1)];\n" "int res = (cov1*scale_g - cov2*scale_s)>>10;\n" "res = clamp(res, -prefilterCap, prefilterCap) + prefilterCap;\n" "output[y * cols + x] = res;\n" "}\n" "}\n" "__kernel void prefilter_xsobel(__global unsigned char *input, __global unsigned char *output,\n" "int rows, int cols, int prefilterCap)\n" "{\n" "int x = get_global_id(0);\n" "int y = get_global_id(1);\n" "if(x < cols && y < rows)\n" "{\n" "if (0 < x && !((y == rows-1) & (rows%2==1) ) )\n" "{\n" "int cov = input[ ((y > 0) ? y-1 : y+1) * cols + (x-1)] * (-1) + input[ ((y > 0) ? y-1 : y+1) * cols + ((x<cols-1) ? x+1 : x-1)] * (1) +\n" "input[ (y) * cols + (x-1)] * (-2) + input[ (y) * cols + ((x<cols-1) ? x+1 : x-1)] * (2) +\n" "input[((y<rows-1)?(y+1):(y-1))* cols + (x-1)] * (-1) + input[((y<rows-1)?(y+1):(y-1))* cols + ((x<cols-1) ? x+1 : x-1)] * (1);\n" "cov = clamp(cov, -prefilterCap, prefilterCap) + prefilterCap;\n" "output[y * cols + x] = cov;\n" "}\n" "else\n" "output[y * cols + x] = prefilterCap;\n" "}\n" "}\n" , "8ede5990f0c9582639e5bef29cfd6cf9"}; ProgramSource stereobm_oclsrc(stereobm.programStr); } }} #endif
8,650
4,259
#include "Gamepad.h" namespace Lib830 { Gamepad::Gamepad(int port): joystick(port) { button_state.resize(joystick.GetButtonCount()); axis_state.resize(joystick.GetAxisCount()); pov_state.resize(joystick.GetPOVCount()); } Gamepad::~Gamepad() { } bool Gamepad::ButtonState(int button) { return joystick.GetRawButton(button); } bool Gamepad::GetEvent(Event &event) { // button IDs are 1-indexed for (size_t button = 1; button <= button_state.size(); ++button) { bool state = ButtonState(button); if (button_state[button - 1] != state) { button_state[button - 1] = state; event.type = Event::BUTTON_EVENT; event.id = button; event.state = state; event.value = 0; event.angle = 0; return true; } } for (size_t axis = 0; axis < axis_state.size(); ++axis) { float value = joystick.GetRawAxis(axis); if (std::fabs(value - axis_state[axis]) > AXIS_THRESHOLD) { axis_state[axis] = value; event.type = Event::AXIS_EVENT; event.id = axis; event.state = (value > AXIS_THRESHOLD); event.value = value; event.angle = 0; return true; } } for (size_t pov = 0; pov < pov_state.size(); ++pov) { int angle = joystick.GetPOV(pov); if (angle != pov_state[pov]) { pov_state[pov] = angle; event.type = Event::POV_EVENT; event.id = pov; event.state = (angle >= 0); // angle is -1 if not pressed event.value = 0; event.angle = angle; return true; } } return false; } }
1,497
683
/** * Copyright (c) 2006-2020 LOVE Development Team * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. **/ #include "WaveDecoder.h" #include <string.h> #include "common/config.h" #include "common/Exception.h" namespace love { namespace sound { namespace lullaby { // Callbacks static wuff_sint32 read_callback(void *userdata, wuff_uint8 *buffer, size_t *size) { WaveFile *input = (WaveFile *) userdata; size_t bytes_left = input->size - input->offset; size_t target_size = *size < bytes_left ? *size : bytes_left; memcpy(buffer, input->data + input->offset, target_size); input->offset += target_size; *size = target_size; return WUFF_SUCCESS; } static wuff_sint32 seek_callback(void *userdata, wuff_uint64 offset) { WaveFile *input = (WaveFile *)userdata; input->offset = (size_t) (offset < input->size ? offset : input->size); return WUFF_SUCCESS; } static wuff_sint32 tell_callback(void *userdata, wuff_uint64 *offset) { WaveFile *input = (WaveFile *)userdata; *offset = input->offset; return WUFF_SUCCESS; } wuff_callback WaveDecoderCallbacks = {read_callback, seek_callback, tell_callback}; WaveDecoder::WaveDecoder(Data *data, int bufferSize) : Decoder(data, bufferSize) { dataFile.data = (char *) data->getData(); dataFile.size = data->getSize(); dataFile.offset = 0; int wuff_status = wuff_open(&handle, &WaveDecoderCallbacks, &dataFile); if (wuff_status < 0) throw love::Exception("Could not open WAVE"); try { wuff_status = wuff_stream_info(handle, &info); if (wuff_status < 0) throw love::Exception("Could not retrieve WAVE stream info"); if (info.channels > 2) throw love::Exception("Multichannel audio not supported"); if (info.format != WUFF_FORMAT_PCM_U8 && info.format != WUFF_FORMAT_PCM_S16) { wuff_status = wuff_format(handle, WUFF_FORMAT_PCM_S16); if (wuff_status < 0) throw love::Exception("Could not set output format"); } } catch (love::Exception &) { wuff_close(handle); throw; } } WaveDecoder::~WaveDecoder() { wuff_close(handle); } bool WaveDecoder::accepts(const std::string &ext) { static const std::string supported[] = { "wav", "" }; for (int i = 0; !(supported[i].empty()); i++) { if (supported[i].compare(ext) == 0) return true; } return false; } love::sound::Decoder *WaveDecoder::clone() { return new WaveDecoder(data.get(), bufferSize); } int WaveDecoder::decode() { size_t size = 0; while (size < (size_t) bufferSize) { size_t bytes = bufferSize-size; int wuff_status = wuff_read(handle, (wuff_uint8 *) buffer+size, &bytes); if (wuff_status < 0) return 0; else if (bytes == 0) { eof = true; break; } size += bytes; } return (int) size; } bool WaveDecoder::seek(double s) { int wuff_status = wuff_seek(handle, (wuff_uint64) (s * info.sample_rate)); if (wuff_status >= 0) { eof = false; return true; } return false; } bool WaveDecoder::rewind() { int wuff_status = wuff_seek(handle, 0); if (wuff_status >= 0) { eof = false; return true; } return false; } bool WaveDecoder::isSeekable() { return true; } int WaveDecoder::getChannelCount() const { return info.channels; } int WaveDecoder::getBitDepth() const { return info.bits_per_sample == 8 ? 8 : 16; } int WaveDecoder::getSampleRate() const { return info.sample_rate; } double WaveDecoder::getDuration() { return (double) info.length / (double) info.sample_rate; } } // lullaby } // sound } // love
4,261
1,627
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "precomp.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/ml.hpp" #include <iostream> #include <fstream> #include <set> namespace cv { namespace text { using namespace std; using namespace cv::ml; /* OCR BeamSearch Decoder */ void OCRBeamSearchDecoder::run(Mat& image, string& output_text, vector<Rect>* component_rects, vector<string>* component_texts, vector<float>* component_confidences, int component_level) { CV_Assert( (image.type() == CV_8UC1) || (image.type() == CV_8UC3) ); CV_Assert( (component_level == OCR_LEVEL_TEXTLINE) || (component_level == OCR_LEVEL_WORD) ); output_text.clear(); if (component_rects != NULL) component_rects->clear(); if (component_texts != NULL) component_texts->clear(); if (component_confidences != NULL) component_confidences->clear(); } void OCRBeamSearchDecoder::run(Mat& image, Mat& mask, string& output_text, vector<Rect>* component_rects, vector<string>* component_texts, vector<float>* component_confidences, int component_level) { CV_Assert(mask.type() == CV_8UC1); CV_Assert( (image.type() == CV_8UC1) || (image.type() == CV_8UC3) ); CV_Assert( (component_level == OCR_LEVEL_TEXTLINE) || (component_level == OCR_LEVEL_WORD) ); output_text.clear(); if (component_rects != NULL) component_rects->clear(); if (component_texts != NULL) component_texts->clear(); if (component_confidences != NULL) component_confidences->clear(); } CV_WRAP String OCRBeamSearchDecoder::run(InputArray image, int min_confidence, int component_level) { std::string output1; std::string output2; vector<string> component_texts; vector<float> component_confidences; Mat image_m = image.getMat(); run(image_m, output1, NULL, &component_texts, &component_confidences, component_level); for(unsigned int i = 0; i < component_texts.size(); i++) { //cout << "confidence: " << component_confidences[i] << " text:" << component_texts[i] << endl; if(component_confidences[i] > min_confidence) { output2 += component_texts[i]; } } return String(output2); } CV_WRAP String OCRBeamSearchDecoder::run(InputArray image, InputArray mask, int min_confidence, int component_level) { std::string output1; std::string output2; vector<string> component_texts; vector<float> component_confidences; Mat image_m = image.getMat(); Mat mask_m = mask.getMat(); run(image_m, mask_m, output1, NULL, &component_texts, &component_confidences, component_level); for(unsigned int i = 0; i < component_texts.size(); i++) { //cout << "confidence: " << component_confidences[i] << " text:" << component_texts[i] << endl; if(component_confidences[i] > min_confidence) { output2 += component_texts[i]; } } return String(output2); } void OCRBeamSearchDecoder::ClassifierCallback::eval( InputArray image, vector< vector<double> >& recognition_probabilities, vector<int>& oversegmentation) { CV_Assert(( image.getMat().type() == CV_8UC3 ) || ( image.getMat().type() == CV_8UC1 )); if (!recognition_probabilities.empty()) { for (size_t i=0; i<recognition_probabilities.size(); i++) recognition_probabilities[i].clear(); } recognition_probabilities.clear(); oversegmentation.clear(); } struct beamSearch_node { double score; vector<int> segmentation; bool expanded; // TODO calculating score of its child would be much faster if we store the last column // of their "root" path. }; bool beam_sort_function ( beamSearch_node a, beamSearch_node b ); bool beam_sort_function ( beamSearch_node a, beamSearch_node b ) { return (a.score > b.score); } class OCRBeamSearchDecoderImpl CV_FINAL : public OCRBeamSearchDecoder { public: //Default constructor OCRBeamSearchDecoderImpl( Ptr<OCRBeamSearchDecoder::ClassifierCallback> _classifier, const string& _vocabulary, InputArray transition_probabilities_table, InputArray emission_probabilities_table, decoder_mode _mode, int _beam_size) { classifier = _classifier; step_size = classifier->getStepSize(); win_size = classifier->getWindowSize(); emission_p = emission_probabilities_table.getMat(); vocabulary = _vocabulary; mode = _mode; beam_size = _beam_size; transition_probabilities_table.getMat().copyTo(transition_p); for (int i=0; i<transition_p.rows; i++) { for (int j=0; j<transition_p.cols; j++) { if (transition_p.at<double>(i,j) == 0) transition_p.at<double>(i,j) = -DBL_MAX; else transition_p.at<double>(i,j) = log(transition_p.at<double>(i,j)); } } } ~OCRBeamSearchDecoderImpl() CV_OVERRIDE { } void run( Mat& src, Mat& mask, string& out_sequence, vector<Rect>* component_rects, vector<string>* component_texts, vector<float>* component_confidences, int component_level) CV_OVERRIDE { CV_Assert(mask.type() == CV_8UC1); //nothing to do with a mask here run( src, out_sequence, component_rects, component_texts, component_confidences, component_level); } void run( Mat& src, string& out_sequence, vector<Rect>* component_rects, vector<string>* component_texts, vector<float>* component_confidences, int component_level) CV_OVERRIDE { CV_Assert( (src.type() == CV_8UC1) || (src.type() == CV_8UC3) ); CV_Assert( (src.cols > 0) && (src.rows > 0) ); CV_Assert( component_level == OCR_LEVEL_WORD ); out_sequence.clear(); if (component_rects != NULL) component_rects->clear(); if (component_texts != NULL) component_texts->clear(); if (component_confidences != NULL) component_confidences->clear(); if(src.type() == CV_8UC3) { cvtColor(src,src,COLOR_RGB2GRAY); } // TODO if input is a text line (not a word) we may need to split into words here! // do sliding window classification along a cropped word image classifier->eval(src, recognition_probabilities, oversegmentation); // if the number of oversegmentation points found is less than 2 we can not do nothing!! if (oversegmentation.size() < 2) return; //NMS of recognitions double last_best_p = 0; int last_best_idx = -1; for (size_t i=0; i<recognition_probabilities.size(); ) { double best_p = 0; int best_idx = -1; for (size_t j=0; j<recognition_probabilities[i].size(); j++) { if (recognition_probabilities[i][j] > best_p) { best_p = recognition_probabilities[i][j]; best_idx = (int)j; } } if ((i>0) && (best_idx == last_best_idx) && (oversegmentation[i]*step_size < oversegmentation[i-1]*step_size + win_size) ) { if (last_best_p > best_p) { //remove i'th elements and do not increment i recognition_probabilities.erase (recognition_probabilities.begin()+i); oversegmentation.erase (oversegmentation.begin()+i); continue; } else { //remove (i-1)'th elements and do not increment i recognition_probabilities.erase (recognition_probabilities.begin()+i-1); oversegmentation.erase (oversegmentation.begin()+i-1); last_best_idx = best_idx; last_best_p = best_p; continue; } } last_best_idx = best_idx; last_best_p = best_p; i++; } /*Now we go with the beam search algorithm to optimize the recognition score*/ //convert probabilities to log probabilities for (size_t i=0; i<recognition_probabilities.size(); i++) { for (size_t j=0; j<recognition_probabilities[i].size(); j++) { if (recognition_probabilities[i][j] == 0) recognition_probabilities[i][j] = -DBL_MAX; else recognition_probabilities[i][j] = log(recognition_probabilities[i][j]); } } // initialize the beam with all possible character's pairs int generated_chids = 0; for (size_t i=0; i<recognition_probabilities.size()-1; i++) { for (size_t j=i+1; j<recognition_probabilities.size(); j++) { beamSearch_node node; node.segmentation.push_back((int)i); node.segmentation.push_back((int)j); node.score = score_segmentation(node.segmentation, out_sequence); vector< vector<int> > childs = generate_childs( node.segmentation ); node.expanded = true; beam.push_back( node ); if (!childs.empty()) update_beam( childs ); generated_chids += (int)childs.size(); } } while (generated_chids != 0) { generated_chids = 0; for (size_t i=0; i<beam.size(); i++) { vector< vector<int> > childs; if (!beam[i].expanded) { childs = generate_childs( beam[i].segmentation ); beam[i].expanded = true; } if (!childs.empty()) update_beam( childs ); generated_chids += (int)childs.size(); } } // Done! Get the best prediction found into out_sequence double lp = score_segmentation( beam[0].segmentation, out_sequence ); // fill other (dummy) output parameters component_rects->push_back(Rect(0,0,src.cols,src.rows)); component_texts->push_back(out_sequence); component_confidences->push_back((float)exp(lp)); return; } private: int win_size; int step_size; vector< beamSearch_node > beam; vector< vector<double> > recognition_probabilities; vector<int> oversegmentation; vector< vector<int> > generate_childs( vector<int> &segmentation ) { vector< vector<int> > childs; for (size_t i=segmentation[segmentation.size()-1]+1; i<oversegmentation.size(); i++) { int seg_point = (int)i; if (find(segmentation.begin(), segmentation.end(), seg_point) == segmentation.end()) { vector<int> child = segmentation; child.push_back(seg_point); childs.push_back(child); } } return childs; } void update_beam ( vector< vector<int> > &childs ) { string out_sequence; double min_score = -DBL_MAX; //min score value to be part of the beam if ((int)beam.size() >= beam_size) min_score = beam[beam_size-1].score; //last element has the lowest score for (size_t i=0; i<childs.size(); i++) { double score = score_segmentation(childs[i], out_sequence); if (score > min_score) { beamSearch_node node; node.score = score; node.segmentation = childs[i]; node.expanded = false; beam.push_back(node); sort(beam.begin(),beam.end(),beam_sort_function); if ((int)beam.size() > beam_size) { beam.erase(beam.begin()+beam_size,beam.end()); min_score = beam[beam.size()-1].score; } } } } double score_segmentation( vector<int> &segmentation, string& outstring ) { // Score Heuristics: // No need to use Viterbi to know a given segmentation is bad // e.g.: in some cases we discard a segmentation because it includes a very large character // in other cases we do it because the overlapping between two chars is too large // TODO Add more heuristics (e.g. penalize large inter-character variance) Mat interdist ((int)segmentation.size()-1, 1, CV_32F, 1); for (size_t i=0; i<segmentation.size()-1; i++) { interdist.at<float>((int)i,0) = (float)oversegmentation[segmentation[(int)i+1]]*step_size - (float)oversegmentation[segmentation[(int)i]]*step_size; if ((float)interdist.at<float>((int)i,0)/win_size > 2.25) // TODO explain how did you set this thrs { return -DBL_MAX; } if ((float)interdist.at<float>((int)i,0)/win_size < 0.15) // TODO explain how did you set this thrs { return -DBL_MAX; } } Scalar m, std; meanStdDev(interdist, m, std); //double interdist_std = std[0]; //TODO Extracting start probs from lexicon (if we have it) may boost accuracy! vector<double> start_p(vocabulary.size()); for (int i=0; i<(int)vocabulary.size(); i++) start_p[i] = log(1.0/vocabulary.size()); Mat V = Mat::ones((int)segmentation.size(),(int)vocabulary.size(),CV_64FC1); V = V * -DBL_MAX; vector<string> path(vocabulary.size()); // Initialize base cases (t == 0) for (int i=0; i<(int)vocabulary.size(); i++) { V.at<double>(0,i) = start_p[i] + recognition_probabilities[segmentation[0]][i]; path[i] = vocabulary.at(i); } // Run Viterbi for t > 0 for (int t=1; t<(int)segmentation.size(); t++) { vector<string> newpath(vocabulary.size()); for (int i=0; i<(int)vocabulary.size(); i++) { double max_prob = -DBL_MAX; int best_idx = 0; for (int j=0; j<(int)vocabulary.size(); j++) { double prob = V.at<double>(t-1,j) + transition_p.at<double>(j,i) + recognition_probabilities[segmentation[t]][i]; if ( prob > max_prob) { max_prob = prob; best_idx = j; } } V.at<double>(t,i) = max_prob; newpath[i] = path[best_idx] + vocabulary.at(i); } // Don't need to remember the old paths path.swap(newpath); } double max_prob = -DBL_MAX; int best_idx = 0; for (int i=0; i<(int)vocabulary.size(); i++) { double prob = V.at<double>((int)segmentation.size()-1,i); if ( prob > max_prob) { max_prob = prob; best_idx = i; } } outstring = path[best_idx]; return (max_prob / (segmentation.size()-1)); } }; Ptr<OCRBeamSearchDecoder> OCRBeamSearchDecoder::create( Ptr<OCRBeamSearchDecoder::ClassifierCallback> _classifier, const string& _vocabulary, InputArray transition_p, InputArray emission_p, decoder_mode _mode, int _beam_size) { return makePtr<OCRBeamSearchDecoderImpl>(_classifier, _vocabulary, transition_p, emission_p, _mode, _beam_size); } Ptr<OCRBeamSearchDecoder> OCRBeamSearchDecoder::create(Ptr<OCRBeamSearchDecoder::ClassifierCallback> _classifier, const String& _vocabulary, InputArray transition_p, InputArray emission_p, int _mode, int _beam_size) { return makePtr<OCRBeamSearchDecoderImpl>(_classifier, _vocabulary, transition_p, emission_p, (decoder_mode)_mode, _beam_size); } Ptr<OCRBeamSearchDecoder> OCRBeamSearchDecoder::create(const String& _filename, const String& _vocabulary, InputArray transition_p, InputArray emission_p, int _mode, int _beam_size) { return makePtr<OCRBeamSearchDecoderImpl>(loadOCRBeamSearchClassifierCNN(_filename), _vocabulary, transition_p, emission_p, (decoder_mode)_mode, _beam_size); } class OCRBeamSearchClassifierCNN CV_FINAL : public OCRBeamSearchDecoder::ClassifierCallback { public: //constructor OCRBeamSearchClassifierCNN(const std::string& filename); // Destructor ~OCRBeamSearchClassifierCNN() CV_OVERRIDE {} void eval( InputArray src, vector< vector<double> >& recognition_probabilities, vector<int>& oversegmentation ) CV_OVERRIDE; int getWindowSize() {return window_size;} int getStepSize() {return step_size;} void setStepSize(int _step_size) {step_size = _step_size;} protected: void normalizeAndZCA(Mat& patches); double eval_feature(Mat& feature, double* prob_estimates); private: int window_size; // window size int step_size; // sliding window step int nr_class; // number of classes int nr_feature; // number of features Mat feature_min; // scale range Mat feature_max; Mat weights; // Logistic Regression weights Mat kernels; // CNN kernels Mat M, P; // ZCA Whitening parameters int quad_size; int patch_size; int num_quads; // extract 25 quads (12x12) from each image int num_tiles; // extract 25 patches (8x8) from each quad double alpha; // used in non-linear activation function z = max(0, |D*a| - alpha) }; OCRBeamSearchClassifierCNN::OCRBeamSearchClassifierCNN (const string& filename) { if (ifstream(filename.c_str())) { FileStorage fs(filename, FileStorage::READ); // Load kernels bank and withenning params fs["kernels"] >> kernels; fs["M"] >> M; fs["P"] >> P; // Load Logistic Regression weights fs["weights"] >> weights; // Load feature scaling ranges fs["feature_min"] >> feature_min; fs["feature_max"] >> feature_max; fs.release(); } else CV_Error(Error::StsBadArg, "Default classifier data file not found!"); nr_feature = weights.rows; nr_class = weights.cols; patch_size = cvRound(sqrt((float)kernels.cols)); window_size = 4*patch_size; step_size = 4; quad_size = 12; num_quads = 25; num_tiles = 25; alpha = 0.5; // used in non-linear activation function z = max(0, |D*a| - alpha) } void OCRBeamSearchClassifierCNN::eval( InputArray _src, vector< vector<double> >& recognition_probabilities, vector<int>& oversegmentation) { CV_Assert(( _src.getMat().type() == CV_8UC3 ) || ( _src.getMat().type() == CV_8UC1 )); if (!recognition_probabilities.empty()) { for (size_t i=0; i<recognition_probabilities.size(); i++) recognition_probabilities[i].clear(); } recognition_probabilities.clear(); oversegmentation.clear(); Mat src = _src.getMat(); if(src.type() == CV_8UC3) { cvtColor(src,src,COLOR_RGB2GRAY); } resize(src,src,Size(window_size*src.cols/src.rows,window_size),0,0,INTER_LINEAR_EXACT); int seg_points = 0; Mat quad; Mat tmp; Mat img; int sz = src.cols - window_size; int sz_window_quad = window_size - quad_size; int sz_half_quad = (int)(quad_size/2-1); int sz_quad_patch = quad_size - patch_size; // begin sliding window loop foreach detection window for (int x_c = 0; x_c <= sz; x_c += step_size) { img = src(Rect(Point(x_c,0),Size(window_size,window_size))); int patch_count = 0; vector< vector<double> > data_pool(9); int quad_id = 1; for (int q_x = 0; q_x <= sz_window_quad; q_x += sz_half_quad) { for (int q_y = 0; q_y <= sz_window_quad; q_y += sz_half_quad) { Rect quad_rect = Rect(q_x,q_y,quad_size,quad_size); quad = img(quad_rect); //start sliding window (8x8) in each tile and store the patch as row in data_pool for (int w_x = 0; w_x <= sz_quad_patch; w_x++) { for (int w_y = 0; w_y <= sz_quad_patch; w_y++) { quad(Rect(w_x,w_y,patch_size,patch_size)).convertTo(tmp, CV_64F); tmp = tmp.reshape(0,1); normalizeAndZCA(tmp); vector<double> patch; tmp.copyTo(patch); if ((quad_id == 1)||(quad_id == 2)||(quad_id == 6)||(quad_id == 7)) data_pool[0].insert(data_pool[0].end(),patch.begin(),patch.end()); if ((quad_id == 2)||(quad_id == 7)||(quad_id == 3)||(quad_id == 8)||(quad_id == 4)||(quad_id == 9)) data_pool[1].insert(data_pool[1].end(),patch.begin(),patch.end()); if ((quad_id == 4)||(quad_id == 9)||(quad_id == 5)||(quad_id == 10)) data_pool[2].insert(data_pool[2].end(),patch.begin(),patch.end()); if ((quad_id == 6)||(quad_id == 11)||(quad_id == 16)||(quad_id == 7)||(quad_id == 12)||(quad_id == 17)) data_pool[3].insert(data_pool[3].end(),patch.begin(),patch.end()); if ((quad_id == 7)||(quad_id == 12)||(quad_id == 17)||(quad_id == 8)||(quad_id == 13)||(quad_id == 18)||(quad_id == 9)||(quad_id == 14)||(quad_id == 19)) data_pool[4].insert(data_pool[4].end(),patch.begin(),patch.end()); if ((quad_id == 9)||(quad_id == 14)||(quad_id == 19)||(quad_id == 10)||(quad_id == 15)||(quad_id == 20)) data_pool[5].insert(data_pool[5].end(),patch.begin(),patch.end()); if ((quad_id == 16)||(quad_id == 21)||(quad_id == 17)||(quad_id == 22)) data_pool[6].insert(data_pool[6].end(),patch.begin(),patch.end()); if ((quad_id == 17)||(quad_id == 22)||(quad_id == 18)||(quad_id == 23)||(quad_id == 19)||(quad_id == 24)) data_pool[7].insert(data_pool[7].end(),patch.begin(),patch.end()); if ((quad_id == 19)||(quad_id == 24)||(quad_id == 20)||(quad_id == 25)) data_pool[8].insert(data_pool[8].end(),patch.begin(),patch.end()); patch_count++; } } quad_id++; } } //do dot product of each normalized and whitened patch //each pool is averaged and this yields a representation of 9xD Mat feature = Mat::zeros(9,kernels.rows,CV_64FC1); for (int i=0; i<9; i++) { Mat pool = Mat(data_pool[i]); pool = pool.reshape(0,(int)data_pool[i].size()/kernels.cols); for (int p=0; p<pool.rows; p++) { for (int f=0; f<kernels.rows; f++) { feature.row(i).at<double>(0,f) = feature.row(i).at<double>(0,f) + max(0.0,std::abs(pool.row(p).dot(kernels.row(f)))-alpha); } } } feature = feature.reshape(0,1); // data must be normalized within the range obtained during training double lower = -1.0; double upper = 1.0; for (int k=0; k<feature.cols; k++) { feature.at<double>(0,k) = lower + (upper-lower) * (feature.at<double>(0,k)-feature_min.at<double>(0,k))/ (feature_max.at<double>(0,k)-feature_min.at<double>(0,k)); } double *p = new double[nr_class]; double predict_label = eval_feature(feature,p); if ( (predict_label < 0) || (predict_label > nr_class) ) CV_Error(Error::StsOutOfRange, "OCRBeamSearchClassifierCNN::eval Error: unexpected prediction in eval_feature()"); vector<double> recognition_p(p, p+nr_class); recognition_probabilities.push_back(recognition_p); oversegmentation.push_back(seg_points); seg_points++; } } // normalize for contrast and apply ZCA whitening to a set of image patches void OCRBeamSearchClassifierCNN::normalizeAndZCA(Mat& patches) { //Normalize for contrast for (int i=0; i<patches.rows; i++) { Scalar row_mean, row_std; meanStdDev(patches.row(i),row_mean,row_std); row_std[0] = sqrt(pow(row_std[0],2)*patches.cols/(patches.cols-1)+10); patches.row(i) = (patches.row(i) - row_mean[0]) / row_std[0]; } //ZCA whitening if ((M.dims == 0) || (P.dims == 0)) { Mat CC; calcCovarMatrix(patches,CC,M,COVAR_NORMAL|COVAR_ROWS|COVAR_SCALE); CC = CC * patches.rows / (patches.rows-1); Mat e_val,e_vec; eigen(CC.t(),e_val,e_vec); e_vec = e_vec.t(); sqrt(1./(e_val + 0.1), e_val); Mat V = Mat::zeros(e_vec.rows, e_vec.cols, CV_64FC1); Mat D = Mat::eye(e_vec.rows, e_vec.cols, CV_64FC1); for (int i=0; i<e_vec.cols; i++) { e_vec.col(e_vec.cols-i-1).copyTo(V.col(i)); D.col(i) = D.col(i) * e_val.at<double>(0,e_val.rows-i-1); } P = V * D * V.t(); } for (int i=0; i<patches.rows; i++) patches.row(i) = patches.row(i) - M; patches = patches * P; } double OCRBeamSearchClassifierCNN::eval_feature(Mat& feature, double* prob_estimates) { for(int i=0;i<nr_class;i++) prob_estimates[i] = 0; for(int idx=0; idx<nr_feature; idx++) for(int i=0;i<nr_class;i++) prob_estimates[i] += weights.at<float>(idx,i)*feature.at<double>(0,idx); //TODO use vectorized dot product int dec_max_idx = 0; for(int i=1;i<nr_class;i++) { if(prob_estimates[i] > prob_estimates[dec_max_idx]) dec_max_idx = i; } for(int i=0;i<nr_class;i++) prob_estimates[i]=1/(1+exp(-prob_estimates[i])); double sum=0; for(int i=0; i<nr_class; i++) sum+=prob_estimates[i]; for(int i=0; i<nr_class; i++) prob_estimates[i]=prob_estimates[i]/sum; return dec_max_idx; } Ptr<OCRBeamSearchDecoder::ClassifierCallback> loadOCRBeamSearchClassifierCNN(const String& filename) { return makePtr<OCRBeamSearchClassifierCNN>(std::string(filename)); } } }
29,730
9,462
/* * Copyright (C) 2013-2014, The OpenFlint Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include <string> #include <sstream> #include <ctime> #include <boost/bind.hpp> #include <boost/algorithm/string.hpp> #include <boost/algorithm/string_regex.hpp> #include <boost/format.hpp> #include <boost/tokenizer.hpp> #include <boost/regex.hpp> #include "SSDPServer.h" #include "utils/Logging.h" #include "platform/Platform.h" #include "net/NetworkManager.h" namespace flint { SSDPServer::SSDPServer(boost::asio::io_service &ioService) : IServer(), timer_(ioService), socket_(ioService) { std::string uuid = Platform::getDeviceUUID(); usn_ = "uuid:" + uuid + "::" + FLINT_SEARCH_TARGET; } SSDPServer::~SSDPServer() { // TODO Auto-generated destructor stub } void SSDPServer::init_socket() { // LOG_DEBUG << "SSDPServer init!!!"; boost::asio::ip::address address = boost::asio::ip::address::from_string( "0.0.0.0"); boost::asio::ip::udp::endpoint endpoint(address, FLINT_SSDP_PORT); // open socket_.open(endpoint.protocol()); // reuse address, must set before binding!!! boost::asio::ip::udp::socket::reuse_address reuse_option(true); socket_.set_option(reuse_option); // close quickly boost::asio::socket_base::linger linger_option(true, 0); socket_.set_option(linger_option); try { // bind socket_.bind(endpoint); } catch (boost::system::system_error &e) { LOG_ERROR << "SSDPServer bind: " << e.what(); } // join the multicast group. boost::asio::ip::address multicastAddress = boost::asio::ip::address::from_string(FLINT_SSDP_ADDRESS); try { std::string ip = NetworkManager::getInstance()->getIpAddr(); if (boost::iequals(ip, "")) { // LOG_INFO << "join group: " << multicastAddress.to_string(); socket_.set_option( boost::asio::ip::multicast::join_group(multicastAddress)); } else { // LOG_INFO << "join group: " << multicastAddress.to_string() << " | " // << ip; socket_.set_option( boost::asio::ip::multicast::join_group( multicastAddress.to_v4(), boost::asio::ip::address::from_string(ip).to_v4())); } } catch (boost::system::system_error &e) { LOG_ERROR << "SSDPServer join group: " << e.what(); } advertise_endpoint_ = boost::asio::ip::udp::endpoint(multicastAddress, FLINT_SSDP_PORT); // LOG_DEBUG << "SSDPServer init!!!- end"; } void SSDPServer::onStart() { LOG_INFO << "SSDPServer start!!!"; init_socket(); advertise(); wait_packet(); } void SSDPServer::onStop() { socket_.close(); timer_.cancel(); } /** * receive methods */ void SSDPServer::wait_packet() { // LOG_DEBUG << "SSDPServer wait packet!!!"; socket_.async_receive_from(boost::asio::buffer(recv_buffer_), client_endpoint_, boost::bind(&SSDPServer::handle_packet, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); // LOG_DEBUG << "SSDPServer wait packet!!! end"; } void SSDPServer::handle_packet(const boost::system::error_code& error, std::size_t len) { // LOG_DEBUG << "SSDPServer handle packet!!!"; if (!error || error == boost::asio::error::message_size) { if (len > 0) { std::string message; message.assign(recv_buffer_.data(), len); parseMessage(message); } wait_packet(); } // LOG_DEBUG << "SSDPServer handle packet!!! end"; } void SSDPServer::parseMessage(const std::string &message) { if (boost::starts_with(message, "M-SEARCH")) { onSearch(message); } else if (boost::starts_with(message, "NOTIFY")) { // ignore } else { LOG_INFO << "unknow message: " << message; } } void SSDPServer::onSearch(const std::string &message) { // LOG_INFO << "onSearch:\n" << message; std::vector<std::string> messageVector; std::map<std::string, std::string> vars; boost::algorithm::split_regex(messageVector, message, boost::regex("\r\n")); size_t v_size = messageVector.size(); if (v_size > 0) { //i = 1, ignore command line, such as M-SEARCH for (size_t i = 1; i < v_size; i++) { if (messageVector[i].size() > 0) { std::string _tmp = boost::trim_copy_if(messageVector[i], boost::is_space()); // trim space std::vector<std::string> _v_tmp; boost::algorithm::split_regex(_v_tmp, _tmp, boost::regex(":")); // string maybe contains >= 2 ":" if (_v_tmp.size() >= 2) { std::string key = _v_tmp[0]; _v_tmp.erase(_v_tmp.begin()); std::string value = boost::trim_copy_if( boost::join(_v_tmp, ":"), boost::is_any_of(" \"")); //trim " and space vars.insert( std::pair<std::string, std::string>(key, value)); } } } } if (vars.size() > 0) { if (vars.find("MAN") != vars.end() && vars.find("MX") != vars.end() && vars.find("ST") != vars.end()) { std::map<std::string, std::string>::iterator _itMan = vars.find( "MAN"); std::map<std::string, std::string>::iterator _itSt = vars.find( "ST"); // LOG_DEBUG << "man = " << _itMan->second << ", st = " << _itSt->second; if (("ssdp:all" == _itMan->second) || ("ssdp:discover" == _itMan->second && FLINT_SEARCH_TARGET == _itSt->second)) { // LOG_INFO << "handle M-SEARCH"; // LOG_INFO << "send to: " // << client_endpoint_.address().to_string() << ":" // << client_endpoint_.port(); std::string ip = NetworkManager::getInstance()->getIpAddr(); if (!boost::iequals(ip, "")) { std::string msg = join_message(ip); // socket_.send_to(boost::asio::buffer(msg), client_endpoint_); socket_.async_send_to(boost::asio::buffer(msg), client_endpoint_, boost::bind(&SSDPServer::handle_send, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } } } } } void SSDPServer::handle_send(const boost::system::error_code& error, std::size_t bytes_transferred) { // LOG_INFO << "send ---------- > " << bytes_transferred; } /** * advertise */ void SSDPServer::advertise() { // LOG_DEBUG << "SSDPServer advertise!!"; timer_.expires_from_now(boost::posix_time::seconds(3)); timer_.async_wait( boost::bind(&SSDPServer::handle_advertise, this, boost::asio::placeholders::error)); // LOG_DEBUG << "SSDPServer advertise!! - end"; } void SSDPServer::handle_advertise(const boost::system::error_code& error) { // LOG_DEBUG << "SSDPServer handle advertise!!"; if (!error) { std::string ip = NetworkManager::getInstance()->getIpAddr(); if (!boost::iequals(ip, "")) { std::string msg = join_message(ip, true); // LOG_DEBUG << "advertise:\n" << msg; socket_.async_send_to(boost::asio::buffer(msg), advertise_endpoint_, boost::bind(&SSDPServer::handle_advertise_send, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } advertise(); } } void SSDPServer::handle_advertise_send(const boost::system::error_code& error, std::size_t bytes_transferred) { // LOG_INFO << "advertise ---------- > " << bytes_transferred; } std::string SSDPServer::join_message(const std::string &ip, bool advertise) { std::stringstream ss; if (advertise) { ss << "NOTIFY * HTTP/1.1\r\n"; ss << "HOST: " << FLINT_SSDP_ADDRESS << ":" << FLINT_SSDP_PORT << "\r\n"; ss << "NT: " << FLINT_SEARCH_TARGET << "\r\n"; ss << "NTS: ssdp:alive\r\n"; } else { ss << "HTTP/1.1 200 OK\r\n"; ss << "ST: " << FLINT_SEARCH_TARGET << "\r\n"; } ss << "USN: " << usn_ << "\r\n"; ss << "LOCATION: " << join_location(ip) << "\r\n"; ss << "CACHE-CONTROL: max-age=" << FLINT_SSDP_TTL << "\r\n"; ss << "SERVER: " << "Linux/3.8.13+, UPnP/1.0, Portable SDK for UPnP devices/1.6.18" << "\r\n"; ss << "DATE: " + get_date() << "\r\n"; ss << "BOOTID.UPNP.ORG: 9\r\n"; ss << "CONFIGID.UPNP.ORG: 1\r\n"; ss << "OPT: \"http://schemas.upnp.org/upnp/1/0/\"; ns=01\r\n"; ss << "X-USER-AGENT: redsonic\r\n"; ss << "EXT:\r\n"; ss << "\r\n"; return ss.str(); } std::string SSDPServer::get_date() { time_t t = time(NULL); char buf[128] = { 0 }; strftime(buf, 127, "%a, %d %b %Y %H:%M:%S GMT", gmtime(&t)); return std::string(buf); } std::string SSDPServer::join_location(const std::string &ip) { std::stringstream ss; ss << "http://" << ip << ":" << FLINT_HTTP_PORT << "/" << FLINT_HTTP_DESCRIPTOR; return ss.str(); } } /* namespace flint */
8,766
3,581
// Copyright 2021 RobosoftAI Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /***************************************************************************************************************** * * Authors: Pablo Inigo Blasco, Brett Aldrich * ******************************************************************************************************************/ #include <sm_dance_bot_lite/clients/cl_led/cl_led.hpp> //#include <pluginlib/class_list_macros.h> namespace sm_dance_bot_lite { namespace cl_led { ClLED::ClLED(std::string actionServerName) : SmaccActionClientBase<sm_dance_bot_lite::action::LEDControl>(actionServerName) { } std::string ClLED::getName() const { return "TOOL ACTION CLIENT"; } ClLED::~ClLED() {} std::ostream & operator<<( std::ostream & out, const sm_dance_bot_lite::action::LEDControl::Goal & msg) { out << "LED CONTROL: " << msg.command; return out; } } // namespace cl_led //PLUGINLIB_EXPORT_CLASS(cl_led::ClLED, smacc2::ISmaccComponent) } // namespace sm_dance_bot_lite
1,534
474
#include "R3D/RigidBodyEngine/BVHNode.h" #include "R3D/RigidBodyEngine/BoundingSphere.h" #include "R3D/RigidBodyEngine/BoundingBox.h" #include "R3D/RigidBodyEngine/RigidBody.h" namespace r3 { namespace { template<class T> class has_overlap_method { template<typename U, bool (U::*)(const U*) const> struct checker {}; template<typename U> static char test(checker<U, &U::overlap>*); template<typename U> static int test(...); public: static const bool value = sizeof(test<T>(nullptr)) == sizeof(char); }; } template<class BoundingVolumeClass> BVHNode<BoundingVolumeClass>::BVHNode(BVHNode<BoundingVolumeClass>* parent, const BoundingVolumeClass& volume, RigidBody* body) : m_parent(parent), m_body(body), m_volume(volume) { //static_assert(has_overlap_method<BoundingVolumeClass>::value, // "Bounding volume class doens't support overlap method!"); } template<class BoundingVolumeClass> BVHNode<BoundingVolumeClass>::~BVHNode() { auto* sibling = getSibling(); if(sibling) { // �berschreibe Elternknoten mit Geschwisterdaten m_parent->m_volume = sibling->m_volume; m_parent->m_body = sibling->m_body; m_parent->m_children[0] = sibling->m_children[0]; m_parent->m_children[1] = sibling->m_children[1]; // L�sche das urspr�nglicheGeschwisterojekt. sibling->m_parent = nullptr; sibling->m_body = nullptr; sibling->m_children[0] = nullptr; sibling->m_children[1] = nullptr; delete sibling; // Eltern Volumen neu berechnen: m_parent->recalculateBoundingVolume(); } // L�sche Kinder. if(m_children[0]) { m_children[0]->m_parent = nullptr; delete m_children[0]; } if(m_children[1]) { m_children[1]->m_parent = nullptr; delete m_children[1]; } } template<class BoundingVolumeClass> bool BVHNode<BoundingVolumeClass>::isLeaf() const { return m_body != nullptr; } template<class BoundingVolumeClass> void BVHNode<BoundingVolumeClass>::getPotentialContacts(FixedSizeContainer<CollisionPair>& contacts) const { if(isLeaf() || contacts.isFull()) { return; } // Potentielle Kontakte eines unserer Kinder mit dem anderen. m_children[0]->getPotentialContactsWith(m_children[1], contacts); } template <class BoundingVolumeClass> BVHNode<BoundingVolumeClass>* BVHNode<BoundingVolumeClass>::getSibling() const { if(!m_parent) { return nullptr; } if (this == m_parent->m_children[0]) { return m_parent->m_children[1]; } return m_parent->m_children[0]; } template<class BoundingVolumeClass> bool BVHNode<BoundingVolumeClass>::overlaps(BVHNode<BoundingVolumeClass> * other) const { return m_volume.overlaps(&(other->m_volume)); } template<class BoundingVolumeClass> void BVHNode<BoundingVolumeClass>::getPotentialContactsWith(BVHNode<BoundingVolumeClass>* other, FixedSizeContainer<CollisionPair>& contacts) const { if(!overlaps(other) || contacts.isFull()) return; /** Potential contact if both are leaf nodes. */ if(isLeaf() && other->isLeaf()) { auto entry = contacts.getAvailableEntry(); entry->init(m_body, other->m_body); return; } /** Recursively get potential contacts with child nodes. */ if(other->isLeaf() || (!isLeaf() && m_volume.getVolume() >= other->m_volume.getVolume())) { m_children[0]->getPotentialContactsWith(other, contacts); m_children[1]->getPotentialContactsWith(other, contacts); return; } getPotentialContactsWith(other->m_children[0], contacts); getPotentialContactsWith(other->m_children[1], contacts); } template<class BoundingVolumeClass> void BVHNode<BoundingVolumeClass>::recalculateBoundingVolume() { if(isLeaf()) return; m_volume = BoundingVolumeClass(m_children[0]->m_volume, m_children[1]->m_volume); if(m_parent) { m_parent->recalculateBoundingVolume(); } } template<class BoundingVolumeClass> void BVHNode<BoundingVolumeClass>::insert(RigidBody* newBody, const BoundingVolumeClass &newVolume) { // Wenn this ein Blatt ist, brauchen wir zwei Kinder, eines // mit this und das andere mit newBody if(isLeaf()) { // Kopie von this in Kind_0. m_children[0] = new BVHNode<BoundingVolumeClass>(this, m_volume, m_body); // Kind2 ist neuer Festk�rper m_children[1] = new BVHNode<BoundingVolumeClass>(this, newVolume, newBody); // And we now loose the body (we're no longer a leaf) m_body = nullptr; recalculateBoundingVolume(); } // F�ge neuen Festk�rper dort ein, wo resultierendes Volumen // am kleinsten ist: else { if(m_children[0]->m_volume.getGrowth(newVolume) < m_children[1]->m_volume.getGrowth(newVolume)) { m_children[0]->insert(newBody, newVolume); } else { m_children[1]->insert(newBody, newVolume); } } } // Widerspricht dem Template-Konzept, sorgt jedoch f�r // Information Hiding der Implementierung. Es d�rfen seitens // der Nutzer der Klasse lediglich Instanzen mit aktuellem // Klassenparameter BoundingSphere gebildet werden. template class BVHNode<BoundingSphere>; template class BVHNode<BoundingBox>; }
5,147
2,102
/* Copyright (c) 2015 Diego Ongaro * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <cassert> #include <getopt.h> #include <iostream> #include <string> #include <vector> #include "Client/ClientImpl.h" #include "Core/ProtoBuf.h" #include "ServerControl.pb.h" #include "include/LogCabin/Client.h" #include "include/LogCabin/Debug.h" #include "include/LogCabin/Util.h" namespace LogCabin { namespace Client { namespace { using Client::Util::parseNonNegativeDuration; /** * Parses argv for the main function. */ class OptionParser { public: OptionParser(int& argc, char**& argv) : argc(argc) , argv(argv) , args() , lastIndex(0) , logPolicy("") , server("localhost:5254") , timeout(parseNonNegativeDuration("0s")) { while (true) { static struct option longOptions[] = { {"help", no_argument, NULL, 'h'}, {"server", required_argument, NULL, 's'}, {"timeout", required_argument, NULL, 't'}, {"verbose", no_argument, NULL, 'v'}, {"verbosity", required_argument, NULL, 256}, {0, 0, 0, 0} }; int c = getopt_long(argc, argv, "s:t:hv", longOptions, NULL); // Detect the end of the options. if (c == -1) break; switch (c) { case 'h': usage(); exit(0); case 's': server = optarg; break; case 't': timeout = parseNonNegativeDuration(optarg); break; case 'v': logPolicy = "VERBOSE"; break; case 256: logPolicy = optarg; break; case '?': default: // getopt_long already printed an error message. usage(); exit(1); } } args.assign(&argv[optind], &argv[argc]); } /** * Return the positional argument at the given index, * or panic if there were not enough arguments. */ std::string at(uint64_t index) { if (args.size() <= index) usageError("Missing arguments"); lastIndex = index; return args.at(index); } /** * Return all arguments at index or following it. */ std::string remaining(uint64_t index) { lastIndex = args.size(); std::string r; while (index < args.size()) { r += args.at(index); if (index < args.size() - 1) r += " "; ++index; } if (index < args.size()) r += args.at(index); return r; } /** * Panic if are any unused arguments remain. */ void done() { if (args.size() > lastIndex + 1) usageError("Too many arguments"); } /** * Print an error and the usage message and exit nonzero. */ void usageError(const std::string& message) { std::cerr << message << std::endl; usage(); exit(1); } /** * Helper for spacing in usage() message. */ std::string ospace(std::string option) { std::string after; if (option.size() < 31 - 2) after = std::string(31 - 2 - option.size(), ' '); return " " + option + after; } void usage() { std::cout << "Inspect or modify the state of a single LogCabin server." << std::endl << std::endl << "This program was added in LogCabin v1.1.0." << std::endl; std::cout << std::endl; std::cout << "Usage: " << argv[0] << " [options] <command> [<args>]" << std::endl; std::cout << std::endl; std::string space(31, ' '); std::cout << "Commands:" << std::endl; std::cout << ospace("info get") << "Print server ID and addresses." << std::endl << ospace("debug filename get") << "Print the server's debug log filename." << std::endl << ospace("debug filename set <path>") << "Change the server's debug log filename." << std::endl << ospace("debug policy get") << "Print the server's debug log policy." << std::endl << ospace("debug policy set <value>") << "Change the server's debug log policy." << std::endl << ospace("debug rotate") << "Rotate the server's debug log file." << std::endl << ospace("snapshot inhibit get") << "Print the remaining time for which the server" << std::endl << space << "was prevented from taking snapshots." << std::endl << ospace("snapshot inhibit set [<time>]") << " Abort the server's current snapshot if one is" << std::endl << space << " in progress, and disallow the server from" << std::endl << space << " starting automated snapshots for the given" << std::endl << space << " duration [default: 1week]." << std::endl << ospace("snapshot inhibit clear") << "Allow the server to take snapshots normally." << std::endl << ospace("snapshot start") << "Begin taking a snapshot if none is in progress." << std::endl << ospace("snapshot stop") << "Abort the current snapshot if one is in" << std::endl << space << "progress." << std::endl << ospace("snapshot restart") << "Abort the current snapshot if one is in" << std::endl << space << "progress, then begin taking a new snapshot." << std::endl << ospace("stats get") << "Print detailed server metrics." << std::endl << ospace("stats dump") << "Write detailed server metrics to server's debug" << std::endl << space << "log." << std::endl << std::endl; std::cout << "Options:" << std::endl; std::cout << ospace("-h, --help") << "Print this usage information and exit" << std::endl << " -s <addresses>, --server=<addresses> " << "Network addresses of the target" << std::endl << " " << "LogCabin server, comma-separated" << std::endl << " " << "[default: localhost:5254]" << std::endl << ospace("-t <time>, --timeout=<time>") << "Set timeout for the operation" << std::endl << space << "(0 means wait forever) [default: 0s]" << std::endl << ospace("-v, --verbose") << "Same as --verbosity=VERBOSE" << std::endl << ospace("--verbosity=<policy>") << "Set which log messages are shown." << std::endl << space << "Comma-separated LEVEL or PATTERN@LEVEL rules." << std::endl << space << "Levels: SILENT, ERROR, WARNING, NOTICE, VERBOSE." << std::endl << space << "Patterns match filename prefixes or suffixes." << std::endl << space << "Example: Client@NOTICE,Test.cc@SILENT,VERBOSE." << std::endl; // TODO(ongaro): human-readable vs machine-readable output? } int& argc; char**& argv; std::vector<std::string> args; uint64_t lastIndex; std::string logPolicy; std::string server; uint64_t timeout; }; /** * Print an error message and exit nonzero. */ void error(const std::string& message) { std::cerr << "Error: " << message << std::endl; exit(1); } namespace Proto = Protocol::ServerControl; /** * Wrapper for invoking ServerControl RPCs. */ class ServerControl { public: ServerControl(const std::string& server, ClientImpl::TimePoint timeout) : clientImpl() , server(server) , timeout(timeout) { clientImpl.init("-INVALID-"); // shouldn't attempt to connect to this } #define DEFINE_RPC(type, opcode) \ void type(const Proto::type::Request& request, \ Proto::type::Response& response) { \ Result result = clientImpl.serverControl( \ server, \ timeout, \ Proto::OpCode::opcode, \ request, response); \ if (result.status != Status::OK) { \ error(result.error); \ } \ } DEFINE_RPC(DebugFilenameGet, DEBUG_FILENAME_GET) DEFINE_RPC(DebugFilenameSet, DEBUG_FILENAME_SET) DEFINE_RPC(DebugPolicyGet, DEBUG_POLICY_GET) DEFINE_RPC(DebugPolicySet, DEBUG_POLICY_SET) DEFINE_RPC(DebugRotate, DEBUG_ROTATE) DEFINE_RPC(ServerInfoGet, SERVER_INFO_GET) DEFINE_RPC(ServerStatsDump, SERVER_STATS_DUMP) DEFINE_RPC(ServerStatsGet, SERVER_STATS_GET) DEFINE_RPC(SnapshotControl, SNAPSHOT_CONTROL) DEFINE_RPC(SnapshotInhibitGet, SNAPSHOT_INHIBIT_GET) DEFINE_RPC(SnapshotInhibitSet, SNAPSHOT_INHIBIT_SET) #undef DEFINE_RPC void snapshotControl(Proto::SnapshotCommand command) { Proto::SnapshotControl::Request request; Proto::SnapshotControl::Response response; request.set_command(command); SnapshotControl(request, response); if (response.has_error()) error(response.error()); } ClientImpl clientImpl; std::string server; ClientImpl::TimePoint timeout; }; } // namespace LogCabin::Client::<anonymous> } // namespace LogCabin::Client } // namespace LogCabin int main(int argc, char** argv) { using namespace LogCabin; using namespace LogCabin::Client; using Core::ProtoBuf::dumpString; try { Client::OptionParser options(argc, argv); Client::Debug::setLogPolicy( Client::Debug::logPolicyFromString(options.logPolicy)); ServerControl server(options.server, ClientImpl::absTimeout(options.timeout)); if (options.at(0) == "info") { if (options.at(1) == "get") { options.done(); Proto::ServerInfoGet::Request request; Proto::ServerInfoGet::Response response; server.ServerInfoGet(request, response); std::cout << dumpString(response); return 0; } } else if (options.at(0) == "debug") { if (options.at(1) == "filename") { if (options.at(2) == "get") { options.done(); Proto::DebugFilenameGet::Request request; Proto::DebugFilenameGet::Response response; server.DebugFilenameGet(request, response); std::cout << response.filename() << std::endl; return 0; } else if (options.at(2) == "set") { std::string value = options.at(3); options.done(); Proto::DebugFilenameSet::Request request; Proto::DebugFilenameSet::Response response; request.set_filename(value); server.DebugFilenameSet(request, response); if (response.has_error()) error(response.error()); return 0; } } else if (options.at(1) == "policy") { if (options.at(2) == "get") { options.done(); Proto::DebugPolicyGet::Request request; Proto::DebugPolicyGet::Response response; server.DebugPolicyGet(request, response); std::cout << response.policy() << std::endl; return 0; } else if (options.at(2) == "set") { std::string value = options.at(3); options.done(); Proto::DebugPolicySet::Request request; Proto::DebugPolicySet::Response response; request.set_policy(value); server.DebugPolicySet(request, response); return 0; } } else if (options.at(1) == "rotate") { options.done(); Proto::DebugRotate::Request request; Proto::DebugRotate::Response response; server.DebugRotate(request, response); if (response.has_error()) error(response.error()); return 0; } } else if (options.at(0) == "snapshot") { using Proto::SnapshotCommand; if (options.at(1) == "start") { options.done(); server.snapshotControl(SnapshotCommand::START_SNAPSHOT); return 0; } else if (options.at(1) == "stop") { options.done(); server.snapshotControl(SnapshotCommand::STOP_SNAPSHOT); return 0; } else if (options.at(1) == "restart") { options.done(); server.snapshotControl(SnapshotCommand::RESTART_SNAPSHOT); return 0; } else if (options.at(1) == "inhibit") { if (options.at(2) == "get") { options.done(); Proto::SnapshotInhibitGet::Request request; Proto::SnapshotInhibitGet::Response response; server.SnapshotInhibitGet(request, response); std::chrono::nanoseconds ns(response.nanoseconds()); std::cout << ns << std::endl; return 0; } else if (options.at(2) == "set") { Proto::SnapshotInhibitSet::Request request; std::string time = options.remaining(3); if (time.empty()) time = "1week"; request.set_nanoseconds(parseNonNegativeDuration(time)); Proto::SnapshotInhibitSet::Response response; server.SnapshotInhibitSet(request, response); if (response.has_error()) error(response.error()); return 0; } else if (options.at(2) == "clear") { options.done(); Proto::SnapshotInhibitSet::Request request; request.set_nanoseconds(0); Proto::SnapshotInhibitSet::Response response; server.SnapshotInhibitSet(request, response); if (response.has_error()) error(response.error()); return 0; } } } else if (options.at(0) == "stats") { if (options.at(1) == "get") { options.done(); Proto::ServerStatsGet::Request request; Proto::ServerStatsGet::Response response; server.ServerStatsGet(request, response); std::cout << dumpString(response.server_stats()); return 0; } else if (options.at(1) == "dump") { options.done(); Proto::ServerStatsDump::Request request; Proto::ServerStatsDump::Response response; server.ServerStatsDump(request, response); return 0; } } options.usageError("Unknown command"); } catch (const LogCabin::Client::Exception& e) { std::cerr << "Exiting due to LogCabin::Client::Exception: " << e.what() << std::endl; exit(1); } }
17,031
4,744
#include <utt/Configuration.h> #include <utt/Coin.h> #include <utt/RegAuth.h> #include <utt/Tx.h> #include <utt/Wallet.h> #include <utt/Serialization.h> // WARNING: Must include last std::ostream& operator<<(std::ostream& out, const libutt::Wallet& w) { out << w.p; out << w.ask; out << w.rpk; out << w.bpk; libutt::serializeVector(out, w.coins); out << w.budgetCoin; return out; } std::istream& operator>>(std::istream& in, libutt::Wallet& w) { in >> w.p; in >> w.ask; in >> w.rpk; in >> w.bpk; libutt::deserializeVector(in, w.coins); in >> w.budgetCoin; return in; } namespace libutt { void Wallet::__print() const { loginfo << "pid: " << getUserPid() << endl; loginfo << "# coins: " << numCoins() << endl; loginfo << "total: " << totalValue() << endl; loginfo << "budget coin? " << hasBudgetCoin() << endl; } void Wallet::addNormalCoin(const Coin& c) { if(c.pid_hash != ask.getPidHash()) { throw std::runtime_error("You are adding another person's coin to your wallet"); } //logdbg << "Adding coin..." << endl; assertTrue(c.hasValidSig(bpk)); testAssertTrue(c.isNormal()); coins.push_back(c); } void Wallet::setBudgetCoin(const Coin& c) { if(c.pid_hash != ask.getPidHash()) { throw std::runtime_error("You are adding another person's coin to your wallet"); } assertTrue(c.hasValidSig(bpk)); testAssertTrue(!budgetCoin.has_value()); testAssertTrue(!c.isNormal()); budgetCoin = c; } Tx Wallet::spendTwoRandomCoins(const std::string& pid, bool removeFromWallet) { testAssertGreaterThanOrEqual(coins.size(), 2); // Input coins std::vector<Coin> c; if(removeFromWallet) { c.push_back(coins.back()); // remove one coin from the wallet coins.pop_back(); c.push_back(coins.back()); // remove one coin from the wallet coins.pop_back(); } else { c.push_back(coins.at(coins.size() - 1)); c.push_back(coins.at(coins.size() - 2)); } // the recipients and their amounts received std::vector<std::tuple<std::string, Fr>> recip; // split these two input coins randomly amongst sender and recipient Fr totalVal = c.at(0).val + c.at(1).val; int totalValInt = static_cast<int>(totalVal.as_ulong()); Fr val1; val1.set_ulong(static_cast<unsigned long>(rand() % (totalValInt - 1) + 1)); // i.e., random in [1, totalVal) Fr val2 = totalVal - val1; testAssertEqual(val1 + val2, totalVal); logdbg << "'" << ask.pid << "' sends $" << val1 << " to '" << pid << "'" << endl; logdbg << "'" << ask.pid << "' gets $" << val2 << " change" << endl; recip.push_back(std::make_tuple(pid, val1)); // send some money to someone else recip.push_back(std::make_tuple(ask.pid, val2)); // give yourself some change // ...and Tx::Tx() will take care of the budget change testAssertTrue(hasBudgetCoin()); Coin b = *budgetCoin; if(removeFromWallet) { budgetCoin.reset(); // remove from wallet; caller is responsible for adding budget change back testAssertFalse(hasBudgetCoin()); } return Tx(p, ask, c, b, recip, bpk, rpk); } }
3,499
1,207
#include "gmock/gmock.h" #include "gtest/gtest.h" #include "../src/UniversalIdentifier.hpp" #include "mocks.h" #include "helpers.h" namespace { using namespace xmreg; //string addr_56Vbjcz {"56VbjczrFCVZiLn66S3Qzv8QfmtcwkdXgM5cWGsXAPxoQeMQ79md51PLPCijvzk1iHbuHi91pws5B7iajTX9KTtJ4Z6HAo6"}; //string viewkey_56Vbjcz {"f747f4a4838027c9af80e6364a941b60c538e67e9ea198b6ec452b74c276de06"}; //string spendkey_56Vbjcz {"509a9761fde8856fc38e79ca705d85f979143524f178f8e2e0eb539fc050e905"}; //// ./xmr2csv --stagenet -b /home/mwo/stagenet/node_01/stagenet/lmdb/ -a 56VbjczrFCVZiLn66S3Qzv8QfmtcwkdXgM5cWGsXAPxoQeMQ79md51PLPCijvzk1iHbuHi91pws5B7iajTX9KTtJ4Z6HAo6 -v f747f4a4838027c9af80e6364a941b60c538e67e9ea198b6ec452b74c276de06 //string known_outputs_csv_2_56bCoE {"./res/outputs_stagenet_2_56Vbjcz.csv"}; inline bool operator==(const Output::info& lhs, const JsonTx::output& rhs) { return lhs.amount == rhs.amount && lhs.pub_key == rhs.pub_key && lhs.idx_in_tx == rhs.index; } inline bool operator!=(const Output::info& lhs, const JsonTx::output& rhs) { return !(lhs == rhs); } inline bool operator==(const vector<Output::info>& lhs, const vector<JsonTx::output>& rhs) { if (lhs.size() != rhs.size()) return false; for (size_t i = 0; i < lhs.size(); i++) { if (lhs[i] != rhs[i]) return false; } return true; } TEST(MODULAR_IDENTIFIER, OutputsRingCT) { auto jtx = construct_jsontx("ddff95211b53c194a16c2b8f37ae44b643b8bd46b4cb402af961ecabeb8417b2"); ASSERT_TRUE(jtx); auto identifier = make_identifier(jtx->tx, make_unique<Output>(&jtx->sender.address, &jtx->sender.viewkey)); identifier.identify(); ASSERT_EQ(identifier.get<0>()->get().size(), jtx->sender.outputs.size()); ASSERT_TRUE(identifier.get<0>()->get() == jtx->sender.outputs); ASSERT_EQ(identifier.get<0>()->get_total(), jtx->sender.change); } TEST(MODULAR_IDENTIFIER, OutputsRingCTCoinbaseTx) { auto jtx = construct_jsontx("f3c84fe925292ec5b4dc383d306d934214f4819611566051bca904d1cf4efceb"); ASSERT_TRUE(jtx); auto identifier = make_identifier(jtx->tx, make_unique<Output>(&jtx->recipients.at(0).address, &jtx->recipients.at(0).viewkey)); identifier.identify(); ASSERT_TRUE(identifier.get<0>()->get() == jtx->recipients.at(0).outputs); ASSERT_EQ(identifier.get<0>()->get_total(), jtx->recipients.at(0).amount); } TEST(MODULAR_IDENTIFIER, MultiOutputsRingCT) { auto jtx = construct_jsontx("d7dcb2daa64b5718dad71778112d48ad62f4d5f54337037c420cb76efdd8a21c"); ASSERT_TRUE(jtx); for (auto const& jrecipient: jtx->recipients) { auto identifier = make_identifier(jtx->tx, make_unique<Output>(&jrecipient.address, &jrecipient.viewkey)); identifier.identify(); EXPECT_TRUE(identifier.get<0>()->get() == jrecipient.outputs); } } TEST(MODULAR_IDENTIFIER, LegacyPaymentID) { auto jtx = construct_jsontx("d7dcb2daa64b5718dad71778112d48ad62f4d5f54337037c420cb76efdd8a21c"); ASSERT_TRUE(jtx); auto identifier = make_identifier(jtx->tx, make_unique<LegacyPaymentID>(nullptr, nullptr)); identifier.identify(); EXPECT_TRUE(identifier.get<0>()->get() == jtx->payment_id); } TEST(MODULAR_IDENTIFIER, IntegratedPaymentID) { auto jtx = construct_jsontx("ddff95211b53c194a16c2b8f37ae44b643b8bd46b4cb402af961ecabeb8417b2"); ASSERT_TRUE(jtx); auto identifier = make_identifier(jtx->tx, make_unique<IntegratedPaymentID>( &jtx->recipients[0].address, &jtx->recipients[0].viewkey)); identifier.identify(); EXPECT_TRUE(identifier.get<0>()->get() == jtx->payment_id8e); } TEST(MODULAR_IDENTIFIER, RealInputRingCT) { auto jtx = construct_jsontx("d7dcb2daa64b5718dad71778112d48ad62f4d5f54337037c420cb76efdd8a21c"); ASSERT_TRUE(jtx); MockMicroCore mcore; EXPECT_CALL(mcore, get_output_tx_and_index(_, _, _)) .WillRepeatedly( Invoke(&*jtx, &JsonTx::get_output_tx_and_index)); EXPECT_CALL(mcore, get_tx(_, _)) .WillRepeatedly( Invoke(&*jtx, &JsonTx::get_tx)); auto identifier = make_identifier(jtx->tx, make_unique<RealInput>( &jtx->sender.address, &jtx->sender.viewkey, &jtx->sender.spendkey, &mcore)); identifier.identify(); for (auto const& input_info: identifier.get<0>()->get()) cout << input_info << endl; EXPECT_TRUE(identifier.get<0>()->get().size() == 2); } //// private testnet wallet 9wq792k9sxVZiLn66S3Qzv8QfmtcwkdXgM5cWGsXAPxoQeMQ79md51PLPCijvzk1iHbuHi91pws5B7iajTX9KTtJ4bh2tCh //// viewkey f747f4a4838027c9af80e6364a941b60c538e67e9ea198b6ec452b74c276de06 //// spendkey 509a9761fde8856fc38e79ca705d85f979143524f178f8e2e0eb539fc050e905 //// seed: deftly large tirade gumball android leech sidekick opened iguana voice gels focus poaching itches network espionage much jailed vaults winter oatmeal eleven science siren winter //string addr_9wq792k {"9wq792k9sxVZiLn66S3Qzv8QfmtcwkdXgM5cWGsXAPxoQeMQ79md51PLPCijvzk1iHbuHi91pws5B7iajTX9KTtJ4bh2tCh"}; //string viewkey_9wq792k {"f747f4a4838027c9af80e6364a941b60c538e67e9ea198b6ec452b74c276de06"}; //string spendkey_9wq792k {"509a9761fde8856fc38e79ca705d85f979143524f178f8e2e0eb539fc050e905"}; //// ./xmr2csv --testnet -b /home/mwo/testnet/node_01/testnet/lmdb/ -a 9wq792k9sxVZiLn66S3Qzv8QfmtcwkdXgM5cWGsXAPxoQeMQ79md51PLPCijvzk1iHbuHi91pws5B7iajTX9KTtJ4bh2tCh -v f747f4a4838027c9af80e6364a941b60c538e67e9ea198b6ec452b74c276de06 //string known_outputs_csv_9wq792k {"./res/outputs_testnet_9wq792k9.csv"}; //TEST(MODULAR_IDENTIFIER, IncomingPreRingctTransaction) //{ // // private testnet tx_hash 01e3d29a5b6b6e1999b9e7e48b9abe101bb93055b701b23d98513fb0646e7570 // // the tx has only one output for 10 xmr, so we check // // if we can identify it. // string tx_hex {"0100020280e08d84ddcb0107041e6508060e1df9733757fb1563579b3a0ecefb4063dc66a75ad6bae3d0916ab862789c31f6aa0280e08d84ddcb01075f030f17031713f43315e59fbd6bacb3aa1a868edc33a0232f5031f6c573d6d7b23e752b6beee10580d0b8e1981a02e04e4d7d674381d16bf50bdc1581f75f7b2df591b7a40d73efd8f5b3c4be2a828088aca3cf02025c3fb06591f216cab833bb6deb2e173e0a9a138addf527eaff80912b8f4ff47280f882ad1602779945c0e6cbbc7def201e170a38bb9822109ddc01f330a5b00d12eb26b6fd4880e0bcefa757024f05eb53b5ebd60e502abd5a2fcb74b057b523acccd191df8076e27083ef619180c0caf384a302022dffb5574d937c1add2cf88bd374af40d577c7cc1a22c3c8805afd49840a60962101945fd9057dd42ef52164368eab1a5f430268e029f83815897d4f1e08b0e00873dbf5b4127be86ba01f23f021a40f29e29110f780fa0be36041ecf00b6c7b480edb090ba58dea640ca19aa4921a56c4b6dcbf11897c53db427dfdbc2f3072480b6c02f409b45c5d2401a19d8cfb13d9124d858d2774d9945f448f19e1e243e004588368813689c1c1be4e1242c633b7a2eb4936546fda57c99dac7fab81e40d0512e39d04ce285f96ac80f6d91ee39157189d73e198fa6b397bd34d8685dbf20e3f869043b686c291f8d4401f673978c683841ec39c45ce06564ccf87c68a080ad17bcce3d7240cd8d57ecbb190fef27578679cdd39ea3c868ab65d6d1d2c20062e921ceea054f755ceef8cd24e54078f9a5bedea2ca59d90ad277bd250c90605b3dd832aa15a4eb01080210ade74638f1558e203c644aa608147c9f596ce3c03023e99f9ca5b3cae41cbd230bc20f2b87f1e06967c852115abc7e56566ddaf09b5774568375fa0f27b45d946cfb2859f1c7a3ad6b7a8e097e955a6ee77c6db0b083dbda85b317dcd77e4be29079420bf683a91ac94feb0f788d5e3dfe72bef028768d76f9ebffd4cb2fd4a314e293df51cb43f12091632e93f4f97fdab7ab60dd50611233fbb1048dccd6478184b914710c894d8116620fcfd09d73ef304c90af210a4724c9e8adb2c47396a67944d6fe827a9b06f7a3c3b6cd2946f328cc306e0a0d194443734cc90fb94ccdb74f8fa7a19690793ddc2b0b06e52d0d4d8530ac227d58a2936fbbf18bbbc2af03443a44ff2a844be527371fedc03c50cce200e8e2b4fdb501e2fba103aafc2487be7faaa83f3894bdcfad873a6697ad930500bc56e28139ef4c6d9b8ee06390b4bcb1b6bfcc6e3136be89e3bdccff50d104906d354569aedfd8b2a5cb62b8738218760a9ebbc5dff3de038ab2e0369f28e3d0d921d28b388acdf69988b5c77120de5317be614da7c774f1f815a7137625da90f0342ca5df7bbc8515066c3d8fa37f1d69727f69e540ff66578bd0e6adf73fa074ce25809e47f06edc9d8ac9f49b4f02b8fd48ef8b03d7a6e823c6e2fc105ee0384a5a3a4bfefc41cf7240847e50121233de0083bbd904903b9879ecdd5a3b701a2196e13e438cf3980ab0b85c5e4e3595c46f034cb393b1e291e3e288678c90e9aac0abe0723520d47e94584ff65dfec8d4d1b1d2c378f87347f429a2178b10ad530bfe406441d7b21c1f0ea04920c9715434b16e6f5c561eab4e8b31040a30b280fc0e3ebc71d1d85a6711591487a50e4ca1362aae564c6e332b97da65c0c07"}; // TX_AND_ADDR_VIEWKEY_FROM_STRING(tx_hex, addr_9wq792k, viewkey_9wq792k, // network_type::TESTNET); // auto identifier = make_identifier(tx, // make_unique<Output>(&address, &viewkey)); // identifier.identify(); // ASSERT_EQ(identifier.get<Output>()->get().size(), 1); // ASSERT_EQ(identifier.get<Output>()->get_total(), 10000000000000); //} //TEST(MODULAR_IDENTIFIER, OutgingPreRingctTransaction) //{ // // private testnet tx_hash 0889658a54ddfaa61f62fdc0393adc498e1227195d413de45c5f0e0da3f5068d // // the tx has only one output for 10 xmr, so we check // // if we can identify it. // string tx_hex {"0100020280e08d84ddcb0107b902e401081b2c10418ba25b21dc2e9fd3d6d8dd69c14888ab0ed429f8cc86a7edba20bdd2bde61bab0280c0caf384a30207d10194012438201e78879c4ee5f780a4fcabc5ce20716080392fc4715db6334f956e210283beed920f0580c0caf384a302020ffede2e6e4a3d613f6ebcca9d3337d54c5b65f7095cc04faf6c9408206b463c80f882ad16021b48cdc46b84e348596f35a0fb4f0107da3a7e5f8b486be6a36fc90ff052117e80d0b8e1981a02e6de1aa8176921a8d5f8ef02a12004f5183f77a601c347f84e7be18c400572e18088aca3cf02022f061ade6afb847d57d29609255089b477d2c33c34d06e13ec5982d18eb785c580c0f9decfae010211c7792d1a8d8c23bbd0e2c4c79b28a711fa4d6ff64906013ddd2b8bca42a6d444022100000000000000000000000000000000000000000000006f70656e6d6f6e65726f0189bb4ab10d9ae0b84096fe0f4b95da56e3949b71c6eca5f284a4a02c83ed174675d6b1d2e529f5e4199bb738a47e7f50fc7acbf86a3908eb0c3023013ea9e808974dd6e0c0fe2c9853d316d63a35206628790b60997a22cefb9383762ba05a0fb11987072d29d76b172700ea6b9cb61ddbdea60372b35de748f9a7fc0d18f30a02b76e272c76446d828b6cef9a2df96f867792da27f08ca116dca121f73bcf09fe4fff1a1b8a099fffafefac87f10ecdaf02f48e0b903ced2d737bcb803f0c0525588ed99e71b21c35878ce0697990bf768bc35e0e6841bf1cf91c1fc116ee0a01343ec7e52ded6bdb89571b40590834d4c04715b4eb28102dad54b455dd6d03380e9eac3c058159e7fa4f5d3da30b3eda24c7e49a87e1523e5b478efdb8020fa03a4788d214a7ec64454366525ebf66ef8692a0db97a2ff96e1ad926e315105104c7ef19f59aff25265f54489f7e0fdde6205e6f62b4beb6b0d5a2a233a4807e5460bd83dfa3929b56bd84705cee12ce7bcaca09539bd128fc9e7513a3e63022297c65ef1ac04bb1807b85fa3ef38342aa8342ec33dfe4979a1590d372218034649bbb7975d6790e04105cef27a6337996896758f4fa6a962425fc802dd790114020c4f14efe604f00b8f829d6c82bd2c9719a60c39565944998d43f299070ab78325c8a20557e03dd2e50e516503d16bd436b5af949a978097e0ce347a700c13c5ce0d039ea7bfc7cc8e975c0710e74b6b0930ffd597eaf80c0fdc18711e0e6c8e1aed3c2bd4ff035df0745e69d30ec0dff351c0d780cda8873c010419d209c19d6fc4c366911170892c6e696709069e6469018ff2c61f5f42b283bd4c590a3e5f71f7934635c1e7cca1cbf0ec91517ce65673c1b6c6c961625537b2e93208db342fb9c2f246c6d636adf66bece8bae648be290140452d63c6d87fb3ff990c86725d7bc4968cac48f10d7b6a4d35b63e3040c42f6e76e7224fa308a042b10807cd36ffe28daca3e2a755645be3f588565f9ee79b19b7f8c572a872bb61fd08c9d6473dfe2a5ae4f100744ed91e2e8817ef417309c4d0f4a5023272b87b8b00c08ee85c037417b5241e6715db7b0e932ef7e08cba00914bf485a46690f0370016d3e2ca265accec86c295cd02c13d67fa6bcc1f51803d537eaef804bdeaef05316c79554916dc5afb6ac1581436a26ac5cd687d83b4ccbbfae8e230eac2aa0c2b87f2db0b70cea9ad4cf9cb3218c4aa37da05245bc401a1ea4afcdcd833d40fadc38c6d38bd75fe63a364a0bed1c9b6656b4f803b944e5947d1c398a9eed200"}; // TX_AND_ADDR_VIEWKEY_FROM_STRING(tx_hex, addr_9wq792k, viewkey_9wq792k, // network_type::TESTNET); // SPENDKEY_FROM_STRING(spendkey_9wq792k); // string ring_member_data_hex {"011673657269616c697a6174696f6e3a3a6172636869766500000000010200000001080001d102650102890102c10102e10102ff010277020600a0724e1809000001070001a03730613039333763663136313063306466363332333864373363323235346163363039623031343565663335333436653034373331656534633166343336643830653031303030303030303030303030643230303030303030303030303030303136336464363832656339373763646461353935333164613366666137323939386136663838333761626164633633366161656463386265313962326437633701a03262306634636561663332353534613665386637306433383662613630343166613664316635346134326430363937663832663436393936396531346336303161313031303030303030303030303030363530313030303030303030303030303136336464363832656339373763646461353935333164613366666137323939386136663838333761626164633633366161656463386265313962326437633701a06137623538633963396133333837653637336464646232306433336632626566336131393239636261653434353338346336656361346361313934646237653263353031303030303030303030303030383930313030303030303030303030303136336464363832656339373763646461353935333164613366666137323939386136663838333761626164633633366161656463386265313962326437633701a03538336531303131363633313133326666383361633364636135393831656335393634626634386434663439366331333537343137653361366539646333333866643031303030303030303030303030633130313030303030303030303030303136336464363832656339373763646461353935333164613366666137323939386136663838333761626164633633366161656463386265313962326437633701a03866363363633930346637643033626131343565366638323039333334353064633332313661306365393537666135613234373139336463323434653063623630303030303030303030303030303030646630313030303030303030303030303136336464363832656339373763646461353935333164613366666137323939386136663838333761626164633633366161656463386265313962326437633701a03832653363626164653363333963323636386534666439303861383662663237376533366637316563326631663465386432636363306666646236363236393133393032303030303030303030303030666430313030303030303030303030303136336464363832656339373763646461353935333164613366666137323939386136663838333761626164633633366161656463386265313962326437633701a035366261663166393130653861316366326264396235313464386333313030633531393731303565383033643462306230636137616664383863643462353764623130323030303030303030303030303735303230303030303030303030303031363364643638326563393737636464613539353331646133666661373239393861366638383337616261646336333661616564633862653139623264376337010800023901021d02022502024002026c02027c0202bd0206007083d05d0601070001a06236616662313139646231396538616266656636303062326431383135653332636238626236366130663566363532396434303931313534653163313330623037363031303030303030303030303030336130313030303030303030303030303539613033613331353361393934643732333237653464393234323164336533323931623166613162323430646534346239326437663632656330313238663101a03439346533303462643861376261626131343331633065633563383431623162346236333137626232353131663561636531393461343066653534323366646635613032303030303030303030303030316530323030303030303030303030303539613033613331353361393934643732333237653464393234323164336533323931623166613162323430646534346239326437663632656330313238663101a03732353739376634623939636163373736396362343264646532313434303731346138363362303036363739306431343937386634336138643261653431353436323032303030303030303030303030323630323030303030303030303030303539613033613331353361393934643732333237653464393234323164336533323931623166613162323430646534346239326437663632656330313238663101a03439383766656363333237663463646266323461343564386162366334323535623930303535623263633730323364386161656538626461633133303466343637643032303030303030303030303030343130323030303030303030303030303539613033613331353361393934643732333237653464393234323164336533323931623166613162323430646534346239326437663632656330313238663101a03565663938366461323138346133353333636531396163653365613735333138353363393631323765336534663336613638613139393562333162663037363561393032303030303030303030303030366430323030303030303030303030303539613033613331353361393934643732333237653464393234323164336533323931623166613162323430646534346239326437663632656330313238663101a06462343733353534326330626539376161653635613464646534353162613761396164653666613438393133303765313336393261633361336632373163356462393032303030303030303030303030376430323030303030303030303030303539613033613331353361393934643732333237653464393234323164336533323931623166613162323430646534346239326437663632656330313238663101a034313366633266643236663931333732333233323137366233393031376638643537636234396331643733666530616163303934666139633662343238613930666130323030303030303030303030306265303230303030303030303030303035396130336133313533613939346437323332376534643932343231643365333239316231666131623234306465343462393264376636326563303132386631"}; // GET_RING_MEMBER_OUTPUTS(ring_member_data_hex); // GET_KNOWN_OUTPUTS(known_outputs_csv_9wq792k); // MOCK_MCORE_GET_OUTPUT_KEY(); // auto identifier = make_identifier(tx, // make_unique<Input>(&address, &viewkey, // &known_outputs, mcore.get()), // make_unique<RealInput>(&address, &viewkey, // &spendkey, mcore.get()) // ); // identifier.identify(); // ASSERT_EQ(identifier.get<Input>()->get().size(), 2); // ASSERT_EQ(identifier.get<Input>()->get_total(), 17000000000000ull); // ASSERT_EQ(identifier.get<RealInput>()->get().size(), 2); // ASSERT_EQ(identifier.get<RealInput>()->get_total(), 17000000000000ull); //} //TEST(MODULAR_IDENTIFIER, DefaultConstruction) //{ // string tx_hex {"020011028094ebdc030704314a0f060129e87744d511a9442adecacc0ed57393251a60bb99cffe7a99a7f3681c2aa371e70280d293ad0307050d7803200612e7cea6a2f34794c259fd23cd6e343bd6e82c7a888940f33bf28d52833df52e090280c09e90acbb140700010201010201df726719bf76d6d4d6763a19095de1710bc12409d6bb0a5be3fd6ee3aa29765f0280d0acf30e07ee03f408de01860163ad020cdd17c2b969bc533f8687900ba3e1df05e5d137addd68747708f512a644ec2e9e0280c0fc82aa0207c0041c9c048401950af40624dca383d04176f3f4fac05b1525e10aac499aac034fe5cc98eb2a7b37bf8ab9120280c089a9a2f50f0700020201010101dbaf23996694ec61e8b3159a2284145595aa05d84bde0dd6f98304ec9a17c3250280b09dc2df0107d304ec0bb30267c401ef02ad02d9b9dbea21bbf083b1345b60a2e88d68d43b92bdb2ec061b391ab19de35ca936020007abf301c88f02dd0396108d04b001cc04d875845c042498a05fdbd585b17eb974895a754b32551932b0719c4c79a0bded020007a2b903b031b51cec069a0b8202ec08c3860c7e39306ced8fd9337ad49f0057796d84c87fca1746ff2d1e41712897470280c089a9a2f50f070003010101010196d823627d093a5a6c9850ada8a448480e4decf8ec81137a162bb92e8f792ad90280d0b8e1981a070309140301020446a2c27067de4a7b91c585fa813095bc7105b5570a3d39933021d079c2ea7e5b0280e8eda1ba0107d504c5038502f301ee01940a32442817aac5f26652544cd0835906a94ca3339bd9fd40fa94fe4dde5cbfbc4dff0280c0a8ca9a3a0700010201010101441f1bb37c8dcf54f9e3b5c67d3d88b0885ce74b4cfe585ebe07d4dd63941e5c028080d194b5740705bd059002b001820339d901393205d0fefc8655dae0ebe1de72cdcb17727b1e9aeb16e2baf614f386c417f2028090dfc04a07d204067ae905fc078801be042ff23ff06c18b7fdff369ae16c820478079aff2e52c2b172bbd56828509a55810280c0fc82aa0207d9049f06b1087c8c029601f302169770d5291999984d354eb5bc0ab3de73cc3bfe87a9d1d31cc13561eb539a1f0280e08d84ddcb01079d288212ba0ee670c41eac03c7050646837a39ad973681553cb75c89c5eaf6b658ba46722b4d459d8262fcfb5a7b0200020e907350595bb23b50388459533ab5617672c752bb97d60454d077d4df9bdcc60002586c51fcfe54f68fda156dd8b947f9e2e661a5d66f05d905a4392fc271b903a92101f3338290d33f3c9cee99203dfb6441ff71fadcfef90646db7dfc250b12e2774602e0fa89b261144441d52471375d5b6fa20bb4657968fa138f0518c8b7b259519fbe4906ea03f509ac2c3da0aa9ca2e23b376bedea8fa8139f8636f1744bb1aabe52c95480a0a33547e6f546be1f3814a2686f3e557231b568096ddb56f0dd4c7e439c0f8976fcc8baa0211dfbd22dd4e5025396b41266b5b15a97fecc75b088124a37ca3350d001a9ae71f96a4f4e204642c92967455403919541186077c85da1c5143f06d551070998ce959544f84ee00ed1f5333b235ff432625f6536f02509462c5c939b62d13522a6d36031935015f92bae5eabae277dfdb22971552f3964b8430b2cdaeaed13cfea9d50a3877aea4d3c5683a65691c82c09879a3102a3349048175be9857f15991126a7ff5a90e3c10f246bc10cf29861702417d4ef83c080621c40f47520f86f58643603293409c80ee891cbd1918436f2633ae71373682516a22513893690f2a108cbd68587ae209e1094612da7739737c0e5f4ac89026de5d97ae2332c4fab46fb2b1cee80eac46a4921a2129821e0e22663ea2e961381acff30021cc08d9b951fb29add0069445630341dcc4f220c0bcfaba36bc843a4502f32aa2128b2c44fe3f8fc968a0a487a7e7044d62f5623d610075dafd28b6b51cb6803591d424cb47d8f6c4b5fe4fa2b1d72393f47ff80f17f35f5495cc5e18449e1d7e637cde9d142baa893f9e8c919662aeb4a148dc39ba64c0b4f9e1a0b122873ddb52d12b144c12dca4cdaa776213449c32c15cbf820262b4ab5e21695b729b49fb29988cb3eb1d57132f0f85b5f838a877c0bf74c698aa3908fb331266062f70fc141ab940aa8d5c917e5d3fe06ef727908e03aaae87cb802d3c05b2fc4de7003bdabd4d8a01ace48f50631da273cb264a003e18bc784d89450a294ee3fc0960c7c89ac2f28170ae19b4f8ce08d91ddbe7b612d12aba3ab2fd214a63371a4400180ebb8b00206e3a268f32718e8eefd5505d7240b5fecca0dfd29f21caf9c11511136ed9576af0b44572f7c1abe14933cd6ea795dea3d26363a2af9c7294995afbd678fbd6f21ca853084594e31e38f957c639f3774ca0098ae0c03f393ffd10068845dabca6b38092e7a1320ce9e5bdca0cf9699c0f2f8f966f7f38927deb609e8891ab2d8006a7bbfd158d4da3abea0c9e9641457b3d3dbcfccec615c70500e8c944d0f79fa63cc3378ac458b313ff74f3697b8e67f9465726693e1f7e6db04e5c0ccd2bc5fb0388f4f404820b23e990323f11366ed30e724b1583960d3120104fe63e01ba2d8b27f1cd6fec494d9c5f42e18431444f8bf0a9c2c3478e11a0b585138ba13b36daab845a342a3f9eb4921180a21ac35bbaff02ff273dac4d4070f8e6c8bbf7f60679151823a483993184ec7034d79165085d513e7114687ab0476f20dc8bbef4ae0d5b5c1a385da1aa7cb2638516d53e0e20be30a9d6568120e1c85929fb798e9883a5f61897ffacd6cc7a8d22fac82adefe00ce8185e3259069ae0bf4b9f79c41e34f387d214e634c0e95c7252e7c933041c5c24af31c94502e14b590de38641573283c6eec64c25595aa8a4b1fdb1479c48facd64e327750394e751124863625bde1c6ebe128d6f0f629107da69bb4dd7b265ebaa1e42030066fcf266840e881a1dc6b671536fe9daa95e212a197e6045923ab725b675240f29e47ca3e571e68a7d3dd34ea3319cb6969ff45fea577303201bc08b55e4d90c762bc4207921465b5293641f75c35ae06e1390f20bc6c6a8f38b7dd9fceb3c0ae5359aa4b1c99cfbb4a7b2aa5299ee4c716da43238657c27b37cce0da988cd055706ebee70cb7786ce63311ddabb11d85800eb9b66d6259aaa34918d06aee109d480ba455879fabaca7c729e5fa7fb5d88b817fe075fbdbfbf6daca28445180b7d9075d533153ef808fc27498b5a47347c378e98a794573a25fd7688f43b5107c52c77b5cb607a1279a041c6b6630d24e64964477873841d901d8842cd3ead0e811af232a6ddd338e6c3ee41c3f35456baed91748b638cf9fb7f952a8ff1150d8f00fc6906e9efc0df05dba6c41d33f62d99b6ce7cdefa0676a8af00f9bb910bdca97680ff886b30cd893a26f2f84f730cdf652b9d795fc044201f8b7da51d04934d5de2ac36fd77e25b06d53ecaf63cf6c9b5068fdaed54f3ff4f60ca8b850e5023949ecb2ce1429e38ff2a54af0d7c645bb2f500a14e4e1d50bcb73d21d100c6254f7a1bd09003dc4be5a81bbc272a7338eaba5668e33d1346f1e7fbe05d00a1587e5a0e2604559698d2e95d98b95398a4a69e307f3ac89ac845579e931a0e5a25d2c2afbea1b4702783bf34df796c03565ff813e1f4483780499931026d098cb3981c2fc42652b9a27ec2837d822979af6cb4c3e7e62e3dd8b1d6e899fe00ad8d04932435d4673bd005150e3b471b0a400400adf37a07aef2f2c4bb263d0b7cd5c17fd3e0eeb90148288a715e1e89a77df25fa0d5a121f79bc3f0df0542012bae2344fcfa9cff7dabd16db391c5a4be01ac526c5ff9dd0f3d7d79972df30e69f5cd3ba87384143cbc48dc2360a47edd5f74dc61d826215aff8d5db2c5ea0614c21ff3154a028bcb733458f066856f7db42bf774a98c8f2e1aba05a0b55b0b957c3c3d68998d67bbaeb979a1c44b1b2b4e1631be2b8055ce12e7ba0c6a500ca786eb8dd9bea11d40fb3ecbf54b6472a47b276a1b75fbce9da5ad73abc1280015a5b3d3844175c21f746921686a568e655fa98d9f97b09e110e464f972e46027580e63139e2a9f0d2aa87607f2b699d8efd1b3247dc5e7e3f8d92d2240fd70d3d1a4ead9ab3b53aca897123d98a100ae02ddfe247ebcdedec736ca4531afb05324487ca52573a0cbac820a91e955209146a9b76a346a74cf255d9809ae945036074fabcf9df30044b1078f2cc34b0803e680fda713899244fcf896b77cefe053a40ac3353d68d13cdaf3fec2eed90d5efb4f32094f38337193b3822489da80569194d7ba635ac1fc1780a3a2722a4c48f35ab75905b6342c0209ff9f41ff40b707caf53520192e9e694f8ea67aa321130cac58c03e5c12a6e267aa357f2350ff3c15f5a8df1f127cf90357d93577858e2789e9f7a96a2b0abc08d46e7faec02bf5680dfc430fd5da3363120285b300232316b3e5c2ab9f2dc145497d8b2780c6d4730020b8b90cad36e822bf0063da46b3e74bf32506df4a9e682c878daca087d29256499c77410719b58ff8d3055c39d0138ccb9de4a07c256e7e9d263b00c84b32303f829d77b281d54f3d25d6854ee418ddcbdd18d01fe8d4f055bc45600f7d2aeb3a702e6e58e57ba09335248c853b3fecd2b814d6ddecaaaf6923f4a0f9425d14be16eeb90dddbd3b2d77aec882d3ec92d9e2b77b8948db6480cff690753a162a0d8896538010276b998519f2cb6fde1e347c8b644a7f5eb0a38f4a60d97af0f901433008cf35a6e5dd57f7a25d34584f395858706be95cf1d186d0a07e8e2308dd3a0099cdc82da858ac155d05cabc527f641a0768d143dc878afe507742e6bd6ec634d2a643480dda1363919b846723e31494ca7ea8f3bc53c6e860a10f355d559b0e25c53beb2c86752ad9f6c109b13b4d2fea48b7ffca7f4c3fa02cd55bae030d032a7f6fd54d5539d1754d96b7c3fc0129ca56676e0ec98235c075ce59c82e76f21ccdaf6177064f7e621f96788abe903e15129e43c44fdbc5f00dc647cc8aa30726afa5b6b76d68b4e1961d29455fc981bd618d5123bac17e20e6841a42c4fc76e1b2e2cade43d7de7a6c324171472af6520b5270ffc7d76f303123b4885ac9a5b899e6177d9982a3113df2d513fce3761291f744f430abc5f09a0fea962a9d4d101e5a88823569617598f4f9bf20b8bb2eccf1b42106e87ce00d2ffd8ed7d5380f4de520bb3ac57b7983fc793e8cbba4ac33c3d033cc7b228006b31d8a22474e6335d13f437da60cb5b9bd33b783391d0eb544f1133ab3d020be3bc80dc28a49d8cd326d51d7ec0b6a85a97fc720260f8f3065b33043d2b38088cf90389913e4a47a172e5ef7e1865f07ccaa1cf9e9f3ebb04bc2912d3b2f9010d135726dc6953fb7ff86d56fd04564b7e0f81f028ede06010a63bb34cce900b617aa8d042413c62de5fc0d084aa4b096f38ac7a421aa85a4fd52f7e143eb30d3ccf0f571cb954135668fc580654d4dd4a1488e19eaef0c0835588aa03da8802a709daa2d7fc469261acb88233c5398e186ca7bf2294c48c14af6f6fb39d770262a5b0aaf79b63841976199445166a4f263d602f78647a7da9ad9d36879e680661ffd55cb3ffa7abaad8978e5af8b789ab1ebd65c75481da5df1d62bb6d1530907e8e8cc2605872b48942a9a77dc89ab55261fdd7631735705d651cafe053b09065e8122cd4ec623c95ee78ac7cf538368a14d7b98192bb13d78d523a071f30dfc0bb9420ed825ee18858745cc64bfc61e48c601687b915f3c3c1f6769aa400f5863f86dd7ef3e25b6edddb0792a6a34e7b3f8b0e787ee7e6a45200377dbf001df910c16e7892856ce70403605ebf63c6fcfb758cab75c1c563db8a451f1ed0d052843814f6056ad04bc60fe8af6e2cac8a10599161d114fe560b538627d3a079d40617fce0aa25e00e9cd2c363a385e4817e7bbf9e456301a9bc8d99751060e502f476b2f6045a648d9a4cfede95604085bdb45676ab3b0700cd5603fade8090d24dcef78dceba6a7bbc8076c595b463f8748acf792761f05a68a542bb4d30f1f9bb9a49242cf5645141c5239a8a0327fd9323bb33fbbe9e8b6a507c166840e57a17997c089a7106305fbf9a9d07d9c551082734bb346626ad213805162940732a8bf9efb90dd25f5288956ce8dfa3318f53d2fe2ab9fc13140e77039f88400797aa0e9cdad12e4664a62ad7ebc0202c119b61522d106004cb709bb678d440234fc82bf8a3102cc9f9735791b6f5833c3924a294d2cf59ce04576e83c3ccf0f405543d2aa29fc5736eb68ff96bc462d5255ff8d0d1cc638cf62469424476f0232e9f70a80e82b34bd79ceecac0230c5a90bac7aff6bc5357f5a7e2aadb8b10176334a3fb64dba1864493717a9429a63b09cf5ff79e861182e0598c62aeacb0c5a14ab04f59bd51c54534e345d0c86c8bfd7c68184099af50cada445c34d9f01b4d87ca0d624311ac195c343a2cd8d04f601ecbef84b0a1bfce4eeb65c2ce3032077101c0905a385780e3a4083eacad62a6e24a9cba1b7a7e4396f353984d6076d4148d6268a334d2298e0295e09797235418e4f201e1e9877b7920cbec0880362b9d7077d8b07869c1f41a609a8da44def977316d8554864a9cea135423d005f3d143e927d3d3aeb0dcb7c76dcd71a28f303c008a44977d0601d870fee6d40a7ea86364d4eaae61d8c70ef0caa3d2737a3b1bd1542ec2ad6af37c6f3f46550d676f66c5237943bef5dfcf49cbfc4798f15dfcc490b3877eafbc2fa62cc4d20dadc058894682c2f42e2ddff62090542ce7c86f3169d86a480357e8ec39d21e08db373cc2934f3c133d89f3ae034b8bbf81eb56d5965170ba5c46f1e9f684100b28198bf2f9c282ecd973c4d180ba99221ab4abbb80ca0777cbc642bd5d0912017fbb1084ba0ce8adcb4287c7017b2eb5eb4205fec3e8f181d65b6f307f149c0a0919515771020d674a1566e1301b1020d0044cd2e3a94de118bb81e38af6640f40ded32d697abcd7e774c0fec5d50226d5b9e26d08f129470973b362d5b8a703d97b09c4ddc2936e548d54238f27ef8cf98bebb4a16c6847d2484c01ba0c6e0f2471408180308570da88c4b94361a7291364e8280cbefff05e47009d8745ec04c81389a14cd56ee27abb39616f035e85b59117df0e8aa64ac0c3e74614c5220774c5bbcb4da1c48f4648657e96d9e16d09b9c382d06a98ec21ded323e405ad08cba8cf3146aa3ccad3cd52f90ee80a3c92cc65d3339ab1a93dde1e858efe450ba7b015c1d9e9ff39c60f97d240c9264e754385de7836023a9defa9714e163e040a3dd2da8900fc9375113e076ec1a418898587f0258e76d40ac735a5ad86710f54b4b0700a2846cc1e69a76ae47d04c208097c88e10c23ee6c3fb91be78b880a13fe3f1a8fb23bfc8e91c785d51798afc44ab07342045a986a827808b924400da51a15222fb7088c3caa5391810c7a3ff3273deb75560bd65bacb59e3a584308a3aa7bd46bb324b96df6f762a4b732332586c54ed5051f9826f1c3c22a42f4025c7fbf2abda24b0023f20d6956422f0a0b5e3805559e9c79a67262f4ef7d970096026e3045ba1c755a7a3d9e1b2ee086286a4164dab44f481d844a45ede5b9048aec41327e1db7ecaf9cafc714fe05a73cc669b45d5b5a02b9a0ff4581f3ad0220abf8ec24484931aa55238985da0255dfd0e4e9c5abb06b53e9b12f005b5f07fcc8ae36d0594787e73c4762907534ba5157baffae1e3e28630185dcb211070545954386bc8452a42ee884faa52043b6966462972249d124daeb43c31db1e508f768671cc4ca3dc9c297941c02e54049979f55954611b88e13f80c8fb727dc0aa6a5f8f13dedcad36d15ca47bf31f9be01454162b99def536ebd718c92830a0c329aedbaf03d843f624c64b8f3c1dd54dd57283bb37fae65eff2265ed6de3d099ed693f69c1717f1640ac6294561af1bd628ea55b8e7c658c0b9e33b0b1968085c4e2e7a093641f80c14bea84f8d2ce4ce8a04152b00e1c8e77a2d388a1b6701bb47794c12ab5bc29cd3640cb8249d0abb89867e106884e993a0e6c0006f930a3661336902c9a8f6fd66f4e5999e33efd32c7c136e11eed9687f628ceabb350801bc81e4125d62f61f91c3ae699451a17170599b9557e39937983fd60e04e50f0dff18db5a440becadbd4ae841eaa6f12225aba48e3c795337b6e549d7b9fd1d7f454eae988dbcbe9d68e005a1cce70a5b4a943022bde50d60a7dc7cef58a40c5119a3858bbd1b905999ebd930af9405864a989c38e7d4d305dac7a56bcd33a2e3e12d2a91e987891aefac0c34a877a79df42b2ee7284256e13d933fc0c85c1e9f5e59d6f7aac2ed82778444572e66700ccf0d698c27edb280d33cd4db5839d87a356dc1e75ca37e0c2d4345368ffd471053bf76f82eb9d605250e88db307b5f546e500f2cb3daeaa292c4d55e746628f8d7d0f0e66bed7b132529c773bbf438348a89cd7c7e9dc0e3262feb7ef4966f632173025b4adc1c74723cbe67cde25abee96478221bedbb0e1c87affcd60755c2b62df5de8bae57a1d733ec9e991a25d2f8c0f60f48b7156d156cf5972a3472da274cd9cd4a7758414b51d19e8c91346b9a1eecd9f81aa14150b7e09f67d61885bf732dff609ef245e94a4a66e34c91fdc88b2262e17a1761e1bc478657cad09fe8621b0a94367dc316843f6b79b8f6364a124117dfbbf9793097007facd3f433f88842a434933d42ac5131872e37d67229903cd4b58b77d29046ccd2fa92881fcdfd2ba933cf0eae8b8b07972546802b150ff3e0e7a2e5422a4ffb2e4531e112d95df8ed28029e9ddd38874cc545a4042f6a4efbe809fca499d0fc974e51568fc66e65d9d0875ab1be983ac8981ec56461880e7582dddadccc76eb50133cac910e23ca3abe4a4c28eef415d4b7e653a22b28598766ac6b979b874bd78488057471731fca505358b8c8df0d536d2638bc55b86e02a518952f92ab9fabd3c2eb3cf141b1a0dabe760bdf4e174be4c62e2cd7092941e646fb148b572305af0e21b8c50c3d3cc5d81f3c64613b474fd26ce82a3fa5ed8bafaa9b718fb46bb4dd1a1673d0f1d9e4271921e81a119e3c0ef48e08f441282f34714f47bb6835070eac5517b2c8be6fc321453b2e33c9c8f60a9c10c46c7442319ad5e6c88704d79bf9ce12808b946f02810ed7c1fa8636b425abc71ff1407d5b6a9bbb2b350efc87630116b8610a43a23bd79c9b5ed2da2551120f52893ed9c8155efe4cff751c3845535fd8f7c37c263687caa001f90ff0127e8fece76d923e13cfe7bc4889f6801a3e3a5218afbc289d0fcbecbc31c8505454c542787d79b3a571cfc66949e2b5096b8f7b646f9bd326dd8be1f4528f50e8f1e499445a8a2c1d9e2c5c866f7c108328556e197c17c13b242382f5cd23d9fb2ed50b009b2b73009d64a3d6a0a7b8eeb1858d622da5def29a8d99f35000810ebbd06b51eb2223b1b3047406897b1866fa2e20c7f51028d143f3fcd36ed946c06e7484d0c4c846c5451f9fb3f6dc4b4f2707b2381e84f4d2655d0e02fd0b4afcb3dbf24a1246906260a92f8fe0f9ead11bb64641c692ff554a032105639834d3ac14da586f39cf617c77f6e422ef0c29099a3d9ccdf04c391f6ca2f1e0091d08230e9106db8a25efecdd792e09e6584497a7e643353853c8b3183861791d17e1046f070d5385086c3510f6879e272ce0dc1363507291148f00c7d20104487ae85fed1cce9da145b75a921dd9734ef4ccb27dd2941829fe8abef9f97db658db36c8a1d3a5bea3cb84bf4882fd874123d96fadaa9d5388c990f6dbe7492d26ffd2862ca17edce11ca46072b049fec609031826a69a01e0523dc6af280c661c48dd8ccdd385f944212110f2c838e485f2276f44c1d9c1229b01fd4957f30eda129978add04f938a1990e542da0bc3b469d7b85d3fedd7c62bf26e4aa4704776e79c22eb906a530bfb7e4e1d2f5f28b477bed36ea585da25e21f4e42c80cf7aebc03780d0b8560da2b2b85def1e4cfb332fcfecf5da35ebe454abf4c287c51268af72c373b46fbc294495b3fd7f882d4c70d521bcdcbd8265c068b234ec6c0960621c81d685c78d86a14c4371b6404caf0c0fbb1c0b4394d063eeaa57878af8fb2b75e55cf59a7db98376bf14ab6c3fe3f425cedb02090678792cefeaffbdc2707c4c40f952b07044ec4f5be1beea0b1d63e907cadd61b64a3a4c9d68fc84948ee6350a3f06f8e37169a389ffc8dcf43cfd1eaf2e568ad2348e74a9959e4637d2887c6d8f579163017b9acd36a8a348aa82c2ac85e86d289953ebefa68f587f08263fa20adc72ae6b03f531e669a177d876bdadffeab5a1f33382dc2bd61fb0a63165ae0d7a2278c58eebf4e6e06bb7b80e3967775d0a4855637913518145a27c18b964eea347ebd29b261c2e4e71c8e91fdfad8621f0c257aaeec6e15e52a26b256f6c1259f8c4a972804d7405dbc94946581415d66219a11f5a8bacaf8b0fdf90b1e3e163b720a042d48d777343573b7fbfc1ecbae6a888f39f5724a0a63a3bf4a489833f2c54a1c3ff8b0a330ce40fd77620c37ee8dbe74f1a822cc7db1a60287c92c8b635c42c6867f633d943e336efb556442f0fad94f159f06498268fd6237180cdab8fc09fee27e9520df97528e0433112d72402ee25d30f394cfdba75cb7d23985b33e23fa425230b47eae7f443dafc7c629d07e9fa167c9144154a5a15723b7abbe94ce5fbceaa018e48fc83c7a02099e18bd147a52521fd9a590b034414e5cc46edf4234325c0b620095fe20b2819ce7e649470a9335231df1ecb52c79366a92f520f6679b1013e09c3520f5c5270b18345d0f6fb24eb25b9c351841767515beebf89d754a2a995cb369e58f20cbf089fb9cfaea1dd6fa9fefc64af1ea86abb871c873a55fff1211aacfdd1c6097d648c4edac7c27f398b0595c1a3dc4a26f1dabb37f5faf2c54b7281596f85222b06ba954c70a587ccc9b6c4fc182234ee11211e66529df9b1e76d792e3b91ffe900bba3096d6d2cfc4628042ab25967eb62626c0c8876cc29a4900f98f0cde6b83c8e9ad2b53e4c458f58f37d36d092ae5fd642dd687245d0827ba24176bc6e47512ebf11124b1cb474b461cc41d0fd22b16bd16f987bdd249e017c03bc63d5d3f5c92e1ae763e2398573884e8ee0bd69d0b563752b5a26bdbf4a4701379b4e379466b69bd6fd551008d4b3705220e90b6b154a46594db1e844b79939b5efe77a4d151314debffe564d084cb92fc02e0ccb619d98d0c4449fc1a8664bb6ac2258ddfdabc0527598b6ff135ef0aa30a359c051863d3f17e38782a1ff4785a255233f31d24a869624be0b3f51965920dfb174a562a37fca65e50093426291f97fbd84c68309455baace6ad50dbdbeb0c686193a71f789ceed87aab46104cd219d8b4d2b8130ea54d7815c1ed3752c0065808b2d8a4d7f8dfbe1888555414459a0c8014381a05682cb9aa6d97e1109c0dd4457aad820a8ec9aa4f2147107376b06f0df25b98f918e7e4ad02868553ee0a16e98a6a509a643dd1a14a92defd5f1cb89f7c3ba55cf31dbf6d60dced23310166bef0e851f9a0b4ed591207d35d726f4d7d35e68aa316c2e57dd74c12ea40054b78fcecd7a666ebc82aca9996c03b4dcf1990e71dc257fe5855dee5fa87420bb9042ffdb6a2055f9707fb509212eb286df7cabda179c937c5d1f0110babf20a9c82b8f1e32be4f8fb45939dd65c5714f6fe68169fb3615a1727f60279ee790843810d25e71d4c8646ab3a739c1f8d8caefe83914af082e9706aab591255130dd0b1396792d32312c39c3c4272c7d5906b7eae43e0d328512df73a81841c010dff41d1231f2894d08c4c9a0f4d9f9c2ca80aa8734e9cdbcfeb1bf495fff718072e9d0b8f014105f196a561322e0e7bf69c0234ea7027cdfcbbd5b8a9b9bbd600700a1c1128154607e556a47cec272897b47957e809ec33eda2be6e23841ae600ddf34cee5c2f2fe59c533f2b463a48dd138ddd3c2ea91e044f517cdc962f2a046daed010f16dd5c9b662dce4ce939121aee37162633309527354be1b37d2a800cbd7969a5eb9f183ab80b3ce111728837895210de4e90049a6e56290c68c9700acabcee68ff2ed187dab66c6754970ab945de1f9b4c12be7ac3a5ce49896cf0749dcea48e3396821fd6a4fed440a03d85f55eb1835c40dd55741274c4e18dc0ea0fd17627d54e1104c53daf6d74c487fb4812a4e439fbd2d013ce75a6b3094043a4d650a311e521441b24f7c838a35956cd412b33c93df117c14b1212330b101e46ddd771045079352f171e94c77d72cda0f91540e50ffd579194a3da11f3e0036798c76291ee5b88f0cffae44bf96232f21943027b361e0cf65c3b3c2c5dd08492d0f04a530aa0b268302ccd01a0d2e1053218e13334f6a26fc872e9a7b62086c7852f7f1086dd18b997c86e0d326b45e2378386c642d7af55e27ef099035038dc369fb3794a22cd690f060036ab9fe4c29ceb40bfddce7d2dc8e528789c20ff3931c28de28ce004f74315a19e17d7215d5d21a374c0d10161fabe3197a6b00c65352899afbae21dd7c46dd2532b6a89be6e26984c55983c0cf7fbd4e843e0962310d75625bbd634e722ecb4123b4b7b6694b81230472e6c0e42aa09160b808a53a1e0462348bdc6e0f053d4f0a66fdc8793b87573e1fb18682043eab12ea035dc6262d1d2930521906204ccda3471116f9b7bf0f1396e90277181eeac8e40e90e3e4a7a1dd3b27f77719e8ad6a73c65c7d55ebde520743c4afd5c86be6630d5c9b165eb3c9f2ff725c2e331b4ba29a586c9beeb345098acf77a15cb2b7fb0c76021529b2ffcf7ac7b899b2aa1ca56034996135163d332b91cbee53cf574d009d4c5088e27040132530da5548c27dfe74c9f087cff25bfdf4584235765dfe0b194c542e5d92d71e423e31e32a47fff8ee7eecdf5281c531715c0c64bef50303f46e5c6b79d84d23f9b9b628227e9f3db9cfef4ff796adc1e43f0c8181575103be69aefb3a0401ad9758908063da6cc63f355aa08b4081433d752f50e9d904091c43a20d5b44fea0bb9f50bca6424f2f6c2482c180dabf927bf9525c9da9ea06d3c71c72c8d49cca2bcc6a0e22f74a9970b44fd376610800a2cfcae2572fff02f3309b27a3b25e46beab327854023e44f776f4b201a0ac4b10f12e53b700610a51a9223a2c8460827488d43ac5c787a7e6b4691e91306642d097544110188d0b5bf6ea9f490ff876f647af3010ab31ae9c8203ac1b6612d24db10dc446ef0f077ea5257a0dd1c13d165769be1743d81a1c6a587842c5c7b4163ded35af33e40aa0c8bbfffa8ae49191323b411c384e58484f05740ab8a952698e7dece7b50f019eba60d16eb9da9614368dfc60ea34dd6c8cb65df197bb5ac55d6a9ecd720a039d8887ce07e84c2e114b757b823a291a3eb1b0e4454cd46bcbff705916556f0c4190d9709a9bf8aeb9ae806748835c76567de0d5356d360cb71bb5c8e93fd60d1f56f124f3cbb821d4f336daa402bd3388afa7be835f82dbb32dffec16d5300fd8e83daa6dcfd3d98f05432806c676fb7ccd7920f1839b33ebf40004b919ec0eaf76caaffee58b830fb0fb74d760067128f34d5d26968919a5d09e646079fd0386aefa1d017689cf87a967bda34547350d9dc02b1be413932e3dedff42531800c8182f4226cef88b5f85572b765b56ba85ca686d015ea4445acfc0e045579f034574572aa65487c7645e3a732645b32c1c934c2b3a1b97294210c592e58f270eac56da4c89745836250cb72ba58cc6aa64ae65fc4ad38d8eed63bc4e214745067a464aafd2caacb0bf0230a33949f9d2b6e6c0be0ee7e9c8f3a9cddb5321160df4a3a1f58ed19dfa4a42db8f0a367cf5ad1c8cc2f2f6ce33b34cc0fa4c505606f2a6d6144b476fc853b97a827a1f92667fa42bbcc8f974218ebf717f705bd7086c65a74b7eb81349bd38f0b742e2feda72bef53d241b827d168816aa84188d0ffa92c9cd22dbd62bae3db1eca4d1b17dc8aeb8bc7335c5b39f79b16debb8bf0d06f61bb69aaeed6b52322165bc0cb8f4d37e18bfb4578e135989938d72aeaa05ab0c624f5c27ecd6a15361baf71dc71d5665d092f8da4cf9eac226dc224a1e0db63ad50f6d1ea87cc4f6625d9763634a15bcc51abc946c419f3a87d5bbff930898b61f8f8a3e77896c0bcd18611bebdde7061e26d195a364182a2d6530f6370ceed88d612163ae8079fd8962d3fbedf752cd7eede36e668f71fc988ac0ce96085c99abc1caacfe81b60c7b06f80b023de2053e88f4558a461f0177322363f70c24f8784ac89b646584e609ffe462522648c9a9c6942b77648826922ba585cc0643573074e511fe4e0b01ee437afc17700b73f5141eb2e022241292517e6215021a767fe8970b39c835677a05e9b6b06c0fb54c43bb75513bfde1d8108cbff30059f70ee3c2376225af98969439110416d493856b6bc6fce476ff4342338f8004ddfa45855c11353530e9adcc434e146d8ed13b976ed8c4ce71c2e2831ba3c30a10ba645892e03883a29575fe61bce6fecc106e297d11b74413eb6df527930d01fbbc6f639a3766d53443d7efc8006cc04cdfdf80cf559fe044c009fd341de505e80104dbc6315f3e9b5d0d5ee3b47c00cced5083d7f872ff9bde4d8ec47cc409c7036bb18be6c8cc1c637277f7ffce7bda4440f47b4e732857033fd0bc56f506d9711ddce1f041d44fa7465a4177a6f51364987f5d5a3dbff09fea327c3e2d02e7e9f7b4527a874a983a0be993fccb1434bb463cf200119b3e7480de8bec280c511875a4d891a65cb1efa12306afc9624b9697f61dcf0e6c5bb175afe489370363e380bd134562a3b16ddcd06daf7f1739c1771ab5314ccf052dafd11bbb68014efcf4c3f38940dc81ad8060d5668369179476ac855b03916184ec69bba799002c2775a67a4cc276e9518d7ba0e0369dafb4f26a9e278f0735a5f04e8d39580644f6d7f30b4d2afccaffe542d134de0a401620fe49f81c892a84a2e0631da408cdd70d912935560c41f770deb6a1b68c6122f972b7fd45a2c4f8e32770dc4d016ad47f69d833201eafb7a9875cc1b670e43a289b4df44fffb48cfd7d23a5690b36bc22aa6aaac2d2cafc95c453f1cf4e8896f44ca0bee532923ba295a4e7a40c619c7678ec078fa2c421de63451d9948b8045702ee4863469db45ec2ec5d7b0602ab82800bbf9d659df1c52dd70d5093e3aaa1c2d7ca221a4e44537a2157ee03cc22295017da266217944852d298fa61e1ac5491fac806f3ff7683c38594920abcfca008ad8e5edfd55bd9165d7312d0cb60cd31564e67c31a887041405c050abc38159e05c6507611228383b6eab2f35429566a779060654e2d7654f69aa20d71d79b97119c99b822e2b19fc421f04081116ea7d8496afb75be96cba7a4b10e29d064ce62da6f694d7bd11725d64a4e0b00de3e57492fc595a272701e58190fea86aeeee467a35a6aa450c6bbaecc3588fd02b70186008b3db2259bfbecf20c3931f6709a7adcbcd7ec523cea110e5d35e57d04b973b753ffe4ded34ad1ed03aa2b84fa66c4ea647cf0d63be5628d861b578ac0d96ec2886a5916f9400d5004cde4518e05ee609a200ba8a744a290cf7f77abb309f9fbe79f4172ec84e0670d12e5709e2bcaa0f47851c59e6a279f363f0c3366ff06cb47295ff387408912020f52c464003419d785393a9fc1f60fcec598a645606e7ce11806a65b45d4ee083ef143e1b58dd4010486f5d578a7fb622da4a9ef16eae08cbbd260da53e5b10e9da6b4f9877ca030e6a094e2f41146bb7f40b31252133cbb212223ca9675d801f4f60a30320a21b1db80307896c77c87201d55c865ef358d5339137dc1e04f07bdcb6f8c96b1c78d1d475cbfdbe37d35f9f132d8241e001c5f6cda0777a3950139444dcbb57f812a1992112b41542ed1e2516653d29c0de9a97411fbfab8f00b43a4e8609a40e8ec351ae3ea8e711d12d76bd7c380b6fefd6d3dc3960e4cd90bef98b6dc266ba391e65da8492b5a079561623a4f9b984971f66f25fc4df3f404054e089dc63b527445f620068cd62bc926bcfd88cf2fb32bfd72e131ddfc59038723b212003e2d0cb05568ea14666838e11e2f071168c153504c2688ee7fa0033ef71dcb63b97b60fe79a3eeb60982cc3b29d1e8b371556019983cb3cafc710c5c0e28676771a724b3ffd0acfe1af9dc100ac74bd257e4922b86596a9afb8d0ba626b8c91ad0bcd0d41e5027122260ba883c706c322a66d74193e6c9602e890386152cc12694a860f438664299c092b3ee7b621e9f8784eab1049251250b330f837d6fa0f2db89107027ce58f0178031f439075da1db3b5dc4717f317c09c30068fd2e87ad0d04ae6ed83a1d2c3725336851bf1fdef627120a0a80d8e27da3030f06e02dd461871640ba007d5d87cc3497fc93831b65f397e8ebd8a480ef1a098e2e4d53f34216411b363f5c4086ac0ccb987f86ea7d4bccc9e51c1e8451c20cff466307b5634d758082c721968c93a2a61dfa46e32ded6f5dd71f9264bad10f7565fad893e6ffbcf56edc9df4f71a0b4a39e4ac8b6ce0a8bbe1d4ea206f6b0f82f60f7a5c849edf9cc016a3d49f1b5bd53bab45ddb261e2929a03b5c83ddb0be51794e327cddbd344e800927ef5a69739c6d27299e54d4f5f2113e4e27a000f2d2421e375fd5b2d47e17ae50f1a47b433261e718d0f039b79f2a9110aafd003915b8f2849fe2d166f2aad027c301d6dcd1a3e8f7ae0de65c99a393ee544dc0e5ee8bdf12dce63ba42eee6a6e40b1d6d14ed46a80fdd0d87ab82b5aaf092070d279d2569d584c67de3ed9041870e7d535e729f03834afe5a85b837bee501b7aee6884941ef9873b5fb79dbef84def1ba2a5c286f1aaaea7c74a6dd1b2fde074ecdc20222ee12ff9c1f60e74cbb94ef3da6b300412687970db60a0c0c5845f5e8b6c11d91c42ed92c2f802d524eabc53019fdadffa2ee197641edf7b95f2262a9d0cdd8b7ae917727acfe53041dc2a6799108a6ae6e09b75c903ceb6ebfaabe2e67e0ed994e9717f5cd56c157c041d75056822d55cd71c106d390a8865124371f2fd86f6b2747dcf8575222b33b483e5350bc96e3bc73307ecf545529b1fa96e085673c9fd354593fb4ca3b7d9153af15453b5e9131e7a96cdac8ae128c5fd4f0703fac1d97994daf6f76474c6ca8882cfa18818186b25f81ae77080f8eead33786937a4a266790b0b82a3352ba9607abe3456835139ee9a573e457102c64c9a6fb9cf8968399b589c4da103aeed9cfba70a334b61027c1f0de0daf2f4aabbbeec9260401c398f18ea1fba4d5a0271edb08818fc6e72335fb4cda3c8305013f9acca09e4f97b1557d044138386e0db5a641214676523ef208f968515dd9a6d23ad60fc6e03356f338f14a0645f462799ec89f2bbba4ccc08501053d9dffbf55ee8e9dfee3bdc696ac5dbcddb8980f875573fff58a6c786bf95645e44a9c28f53b2c4ec8903bbc61355f28c49d3c7e198379b216ef8179eb8b5f306e96000926c71682abb028cfb4556f6eb5f10457cb684f340bff92847241e8a41f066c5b83e453454fddefa89b2cda2a6ab8c9dc0393e9b8ad3eedb8e801d313ac946651fdf0d9c108042e0e64610000bcee5339cf42da7e3bbb7095baa4a6605c470d8cab2e5ff28601464ebeb62ffa94eb413d77c4901edfe8de8a44a842b5f174c31a611edfb47714c9053fbb191007384afbea0f2e001e478ec3e91c0b86866704992a55e06183d04b1af1b74329377bbd91994709c20ac55dd71ae9e1049eac70f4bf3809c1b14e905fb1325eab491029874f16c3ab6b4b2265f983e0adb7a72d6b8e4b75a2c000a655e0ee5a7751d7dd586251ee9223fa12c213fd0e1819199648dcb5e088e505e858a430983c8c5114829f0692bd24dc2ff30e79a67e88c406af1ad8c53c78fd97f5f1aed8fd7cff242ebd72b69a2ba4b820a1b3323ed00d33c409d5e0dc37a12e2e912a8012ec67a2c1ee84937b365f49a60901c6c15e1af75784ade7b5e5aec52b982467fe502dd6295d9068277169a8c1e90bd23241e24ab35fab147ac85ec7802f3998c362ec8471cb3f6a1de8fa98758a03146cef679e759596a6c798e9cba957713d14d4863dedffbcfe73f34280c4735e47d41f26d3bc10358a5630d110892068f4b631f4bd761f0a411ab74d8d9af8bc3f5154824deb5bade7f4c536147c841ee78ef64f5aadae651de0fa8cc5714659f4f7cd1bb3afcc7c3319083854b2eb6754e0862a7655c9ce6d4851561057785b08738c0dc3379cff4f9e994e75521c48bb5315ddbf1293e7d4c133fcc6ccbce864dd7279b87a2881fd4dd0c2edef5ec63c35f8abe7ca929a5c69b7e5e163fff73c91fa529b213925cce5286d9e7de110538e780bda9927d6aad3fea6f42680ff4ec2e17d962b5475a9860123b61b2a3f28489e077cdad59c6b0cf07b50613608a04e236639d073bab8caf33c3b94d15feb1e030994b78009801036237a35f3b0a6153a378709f09b69798cbee6eda044ebf72369a90da41a8d19da6e4d4db7b04687aa345ed900b153ac98266fb7a7d91d0be5c6a2663c0a8c5088937dc323bb1995bcc5885417a432db10eb726a728c1a8cd75e446fc8c607385a199b135ee2c55a5f5fcf1c302b45e2e42f1bf0ccb42abdc5df33d9829330b07e37e8a5226543afac32b9bdb76d964fe4311a3aa6163bc7475f513f06feae33698309a5dbc0f0278a4ad8cd7a5f4ce5b9fd45d89b289f97f76e4a10f6594ad0f6cb733de28766668f703a5791a56ebc9e1074f6aa7c9f1a9aac59c863bb0880ae37646569cb09651cb702de3c4e8127b6877588b466d161bd885a620838b2405b64a0d8f5322e2f36890d31d93e127dbbc774ca0edff38c39b621db651b334a5e0316db6331311fa0e2be29e23e19a9980d27f01854787f8f130c9fff4d36d79bef818b542325a0b10a2f0077e78079d6f9dda8b0489a19f3fd64fbfbf7077d4c132a74b5c3b058b9738d770503874951973716b472fcf0b67ca0731ce9a5c69b642c5d113b3878f10230f9632795ff0b42c61d1b297579e61572a1e21541f2f242496d40c3f4f65f09af6431ec9ceee8d3bd1008d6a1a6474d257fc91ce5409efb4d05af2107a8d8c77c12a96556a8911ee369922450facb2ab37adfeb1fc866d0575402e69d6ababf2b4e521736e6c9b98ff97bb9b3d8c62c2061502096e1933989d538e9ea7e4b6a273697d6227e0fa8e5a466c33240adfc924f2fb18626003bc05f1bc53732d137f81211d3a9c984b02d17583a0a3daf84de5db69ff4ed6864ef80d0b6710fac272241acd9c8d7cccd7dfd833fba59023fd8a0879e38fd10bc326c78fceef22a1b53296b04ae756c2301b173477e47cfd203efb5a813a3efa074fc02880fe33acd21e7043686afe692a80f0d32d8721dea165e6b3cdf4aba92634b08e03638b72c18155d826d8e5bb08d27ffb17a27d336f85b2f2ce9d45ba84480350de9f2e11bc8038e2e16dfb4b42e2a284f1ad76620cfdc492f0eb0a83bb2b714c87fa4383b732d5032c238e8a88321afb788463c9c89fc8ea60e2613d24f2280b52760548e90b9578e8809412349322a3001096c4fd38a964d9e96fc481e5047865d1ca7eb90b3ef78462fc56be3af4fd61feecd79083d169792c2c772ce57d485bacd096d43d671dfb14a923e29f3b69d00b4d86fadc10b008bf36b76caeb0b01539692f1f30d840e70b1f98b6cc8df00db22c4e878a076fa56d1ed66360c76741359c4fad9898c0a6ca8372f38a55c426996fd0c8065a12d609000350467d90cad8457994915280ba2c6ec0855604a78df237f9ed1a0c3cd355249ee0b4228d2cae947d0c2fb810332585b6bda29cdc379183a81d7e13f55d1c58c828285b636143308005944680a4c03734f1d7b885eac76034616a6c475dbf1be5575764e082260031538d5f10313c4c5f415421ac804ef257ac46028220977241834f6340931c9415eec2c5f0eadee6094eeea8babc870f3e686e0e18f9d77da426b3eabb1bbca64ee5fae33090657cd00f0e5bac303b344207f8ba20d23c6d55825ab7ffb1ccd4115411c750f91ad2973124296cf5cf3c1bf132f9f7bb8f736f3d5ac43c59e1330a1c8d5ac0af1bf3c42770eda2a401cedd7788ff698cd2cb9394b4ca6b8a7256c75535c40018ede23efe779091dae50f257cbce72fa8eeab60dc54f26ccc5de3c75653cd1069cb551e5679aab733514ef785371e761eeff3d43d59860bc2210e930c1894f02b5ebfaf1f7b3c1c02c8249e347e878d4f8a3746a8d789ee32acd5dfd1ee4b50126abc6cfcdd796c9b02ea234f0c885f23ba830b39c14a32d2af5fc5022c0cc095b6dd194d2c57186d6ad5f4e583303aa54e2852ea1a0a49cc8ba701f7286fa0c881641f81516dbadf70649ae7cc589028822748a35bf550a9bf216f3c5bd250c846418eda9e0a113812234e03300c46857cf0a7d538e1d0169bf0b82b9ac1401307e658092103965b45ea5793a928d7046734728dce6d40a1caf0a02ca5ca2046f3e16e7e7ac2628390fb3c1ea1a7a70dcb3c5a9a1c2fc7333045be392a3c50f718f353c3f7c38f4609b2249471fe2b1318bcf1fe272c05435f1665ad9ffb305506dfb3a71a54e93113bb30111532afcffdd8a48e76dbfc6f8f785e0ddacff07b1e06f788da22b02502d075e4182a53ff4e383cc647d0be61e138f1567cec70e88c49214b0702c1b047de130541c2b172a431ad3ad8f5472fe8fd2abe056550c4b555dcdeb49a011f8c80b3d4e9adee65f614ab3fff1cece1a67e94a47fd610d2ddab98f37acb5ceb36e9009df0c28064bebb8aed10101120d4ee141984ced0e9e019458c8c7b2189283f45241ef25b1bf58fbbdbe275b675cb9168a82a6ad0f398e8e0c8137e25c87f16d5b26184be7efc9b8724f7e4b1dbad78e1de908440ff361830480124bc41593ba7c520b042ec6f7429ba81c9b575642de156272db077e63a510c74cf761905d285aa1b05e51130a9f66b5bbaa4b2f5b718fca3c190b21191319df320b681e9ba1ebcb44e277b4411518b38eaa6b60eacfee45139f04fc033a8fabb357c3b300a4e633b529639a0d324855788d1334071a2e6cddf40bbf0820d1bd83a7fdd332f9ef1570e1fbc09b23d2b23851b9ea4837eabbc8050e2e4dcf85c9b12eca55fcd11938c6455fb66767f483399eacb088dc925d1c03082e9a6d012c14b300059caa8e24962afc255aecb13ef0377850b230333b8ad40de1c79cae3d4b7c9a42385776c9ca1d353ded768158ea88acdc7a7822e2d10803c202cca74b981151408153d3f7687bd87d418dba65446c38fa1b83399124f4050c17725f5ca40ea26d46d47ad2c51066c9c447fac8b19f70b42b647e2f75c10eff7f9b9d12a6b5a4e28926d44df7d7f06797f00131a60e01641dbcf62533990c7059e56c6eb6a2171b2540dbf79d619a18428501db10c501df8948ccc4a2e10fd891caceaee46f883fac240c0765684076e80dfdc442dbc1bde2450ab1b2f10d1646a5f61f206f554ca191d8a285bc77bd6c2fed5179d446ee1dc36165da5b042a5c324ade7e40e32ccad35e280749c19d11140098e2ec76bee592e23e33d2025eeed9a49024e12f69e8e42465701bddec5fd3d1c7dda9e37af7df82af1e090c9549adf101cb4e770e000a78a2c5bba893079c06ab3987c404cfa6d38b3f9b04574a42ca2d4269a6275c65219b0a0a5861261f78ae1e8305ea501c5212dfe501e1609e36908b70d7a87b248f80b233fd38dfe2f283d25fb8cab3f5afade7b7018e0dcf66f4a48001f848f30aabb5c22d7e517959c000eb0c951f52cd335f5b0d688db31758ea52a44cad6d6e08f6f2c1912a82f3811f7562929691c295a4f00eef551f43e0d54e0e47fe877f7073b48fd34de74c07a69a4a76bc171d8d3eac0532c145a8e219b0138474184f02c08194c7b782c443b3383f1ed5166f8fc4760121e5ac0037dfdc87d4149b9070aa20e096b8c0e34e0fadba6809c46ca3f23709240fcb585374456543128966b6b603347f871bb0e581cc2b44b16973b404c601c3d1c9b02925596ca31fc8687e38d5d67da0be82e0083891f93273d46a0cf0026c348c89e3ba2842a98b6f41f2682869519b0b25e2eafe9fb87b64b5fe7c8c00a7a9fd441a9e46ac2545c288cafad5bb1f0c2f1244b61c8157dc534642c9a801b84c91950ab3b83692cdbe83c9d0dc3be219d18cec906d4ee9fc77402b43470350ccef3b40c3a6f413d5530f81035b2d813e40615832dffa45abdc091a962a040c853ee64fecf9492fdd7eeb27a28b39367247b59aea4c215a39597737ec7f0ab6fc1f36e03c5d3735047c3a89b2a377557bd6d1b858a1e62ecba5b2f615ac026e3cfe4147394c2e3ddb21c4f6b3ef1a28997e77bb535c81f2f08d8f01df3308b170c7149f71d21ca79cf87f4d637764bbba5a6747b0a430ca17b5b767d24d02c331ba5246333cc886b0a5f67286caf3544d5a156716659c3f95064724534305a3cd6fb89a4ce84b55ac4b77b35695f7f460c1a78b8dfb3f6042222a0bced803511ab688c358ff5ec7a538e29329af2236d6d4f8bbfa79e88d246a312d1627093defe8d11381f4244600c46dcec063811086ecf97c4df2b7d82727d1095585043c3dcfa4b1d6f7007a81f605236be657e364091e9df7a24c622d14b371e3b602d22e7f68d43024247020952c5f40f7cce8ecdbe1e1cc766fa37b589bf048e40316303bf71d862fbcb027a59794b9118d9f0ddd426422a753daffd1f418f6e10d84283e23d0b3422536360a959d0e9a1784da2be4f1fe658aaa0e11fbdba7030ad2b9ccff0300500e6e969be3aba514b36873e52216665d8f0c0157c6d85a8e0a4021696557665cb08bc50ec74e5632bccb41174cea6229fb1a8c77f574e9a50b2192148f5964654941d03cd8b059c6f78c46069adf20ede1199990f05bc2680ecc1698335a1b4646dba80f861f246677ca7a51b0cdabb65b4211e4bcc910ff0e4d46493511c2e9184ac3a2c38a185bd63a43aff51f2dbe7121d6e4e6e80d2d08db5314da37c967c00309f359c5f85cb1e97f960937d4aab7f5ea2d2b3ad874054d1d8a1dc2386eab5cd49b271d51056dc325b0599054c39646ed68745e09ce0eec7fc942fea7b4cebea30e292f34699dd12a49ab6cfd04bd674b6df7455df6071fdb59435a67607a0cb714deb4bec5555cbe02bd4e9526da8f65b18e82122d0737f3c5e9e69b5689ad51518e902e139263544d4c77668fed40d088289b8de705bfb595838852cdd64fb6206ccd1fac10ff95cb970f3997fdd013fe4047a5e90a40ae70d31c2d68b87d04276350be3f56b3086606cc62123ee5227f9a574ce501c7941ae460bc31d9bd5c3b286632c220d874007a8a916174398254cbfe0d9e0b639e4f3bf5ce1cc4972b8f98521a8829a170573e872b8395476d4665b229620ab46d13c16d265752ecf07364bd98006182b08eb1a188fb9e07f24e65bed0920af95428e58e0f5ca8a128cfe690a8b5b9d876b2820c9d34978ae603d1c1755d0583505caed3e3e7d67543f315b8f6037f1423a714e57ed79c9740a144c1cc1e05b1744a2262fc441f91f02b9fa0d91edb596ef1ca914bc7952e4ab7d7e9369f0ba29a1221986426192cdfde19e61b62fa230b5c47ef3c3c5f49db4bdaccef0001ed3da09aa134c66f2dbc2f1081a1f0c4d481d8a6c7b073188d82914b7ece99054e45b0862897536fd80cd7b8754c4be2d7ea7a23633d0df589a3c73a71242806017365cf143aabd406f43483b1434d5d7d2945e81c51ace5cb95c85448fb8f0a2d798bcc30110bd466b90033133dc65387001b279dfa5929327a1cb0cba60a02b61cd37152e8bd7aea25cdd5145771af7eba4965e466ee84ba38178dbcb9ea0a109d63ea099fce0474823404573577114d0e9344431bfc5ce6cbede3cacf8e0be2ea04352faca2d515108b1e30b4f42041b5bc02f570936050a6be34c6b4680279c5e111e2ac999c8bf79358234660a0ca3bae27fc4074b442f22222a0cdfb007fd8c686f09c710814ef74de366bc4ed0383be994dc49034434c661b881f0e02fe4acfc10454cb8b11c7d29499e12de3af1e0888ae7d4545ea7c8ea7284700024ab1a82c46cf0344613076c6b81625caa2b3f3ecee1831c6eafff11b988f7003eae8dbd07ced82a935cbf7339d9265122ac7c5aac2343753a69fbb2606677004c5e435e4b66a145a973f779b9a84645832089d5606c30ead48795a2ceaed930daeac47b228ed8fdc96f3805c13d88d6c2507ea5a83ee075de3c15579129b040cf79f3f8105538771d76e6d9ce3c7d367ab6d3a5fe4599dcab321d61b74f75405239406c8664c4913b70f781610ad810cbb98d1bb0455073d501b1bb74a1d5e03405afe90723b03f6927f92a838b0e64c67570dfaa6649dd9e4898c7741e67a0586ed33fab0bdeb706126f6a344d99259b68b4ef231582ad1d32277d167eaf20bf94145c1c23fd88843869a0d2056f38042b196c43649e0ee16a957ce9feb4d07f588e7472b6ac4a4058755e9cc0bfb06cef3d6b2815542dfcdef124f75e7b30f1d8c383ecf9ed225224e6c79f4c8c6421d9485f5ddf512d1beb3a0d6129e45057d8aa4b6d253974d5b3bb4ea51e95bf7f1b66d483ac15323a49bfad39e3dc50bf430c377a964898af69640837aadb8567c55259fee3d2c605d6822c7ec9bb2015eff7ba4203a25715e4c64ebd01c206fbe29710a8334e804f78a5ad4d68dac07cbe15bf4b3d562aeeb0315d8a8f7dbca31f3bf0ae5d6f80d0b0e9a41f9fde6044ecef0ff63e6669c27773eedda8e45a54240e0c18f65a418b8255db68273510e254542ddcc68f3c34e7ea6041beb816070e47c9cd365cf5f1f73246d3d480504275af11e71f3f215b8b572242662611836931514192dab559e71ba3fd82301010844861d90dc8d316e0204eb65eb48270231dafb0f974ca3329b5fbd6c8b62020ab3fc0fe486619647280d731c4eb3ab0a1b7859d92a66ba1f5777d7585d6b0d879abf37fe8d35636bcccbb92c6692a602a12865cb013d31f27673d7e8df3e03b5ecb328c78e4102e3b64cd274f59676643021fc1416932976dc230888bcd50a060a954a12481b4915aa0c6748594004fa1fd64ce42055a24da8af31eb124809025765940cc5575cb0cf67da159ee03f6794e5d3381345c8567037af1e31a704161d5d3a5c44eba8f81e1d69c9c273e44c1b112424e87306d692ce5557478c08de6530d320ee8903dbce454a79432573c75c2233dec2ab221b6945d7ed569c05f9b4f8188ee16234fe8927d32aac416420af253bd2dd3b8636c84a435a45c6002f4c38377704777f5faada0882c2476f1296743c902a974ff85c4a0c054fc502c5f290c51075e72aaf2d2fe614c2529f61b16319cdac208d9d75e32519cc4e0744e732ea9397986add39384328ea628f0cd6bb8b2e6a014e2e434d838bb6ae0d1672145448950b8d90cc56fb60dcd642cd12194c6177c0066de85fc00de384056ebb08e8bfadbe7e6b34e405ee214c37d5e89b741bcd02ee9ab42be954649a0446f388143b6b2c67b8f2e18e0e46ead4b864b6e2b95ac88e245b407e22e3530b84c64811632f3c788cd1383818c1ba57d0d86b72b147806ec7721bd3cf5d210bef6d69551a86d34807d7530e07a4ae536e31f527049d6ba285d09e011d13120078d5f9b5e20e0e5d201ca14fc46c9c2badb0058b31c50622859937cd2e01390cf5b84dad736887e47be0051075048d00920599b2ffc7767f4408cf4d0442d80c3e2d24755f46d0f1c854f8d945f514f8931f40885a2b8de89bb665df66ce3907ae870b26e13524ad3befb04b252e6416fd19201f815c5630c00d1331991d310b71b24dee3e441c0fb078691b93527f4bfb3356d1a5204e384c6c4419114f150d8b173c91d90a31565d8113da7ee6f2437818e3189deb172982118deee1b82805020a189d6438f8f16592cad1abbf916b9a217e8655fbc442df3b7940a1395a0f01335f1d62724e4d569adac056d29174bf3c5c7935d213deff9851e9b68eb1007f80d2cfbf7d6e439ec59ff48563b0b9562762317863e8132742cf3410e70b0a493e2a5860a7f2897abe1a2566936035dada39b02808b11eaa589d5f5786ed0c353f32e14a1a1bcc50288edbf3167db717dc38347f5e9b1ebbb127704d5811028377572104dcaacbb36a7042ef1e26e2570e47b04fb36c982455938d8d7a20064cdf442eafd37bf22766e90f6dcaf3582d616935cac7ce66f07328e3f1aafa082cad930696849b2d4441c951d153b6e1879ef39657fd3fee03450ed00ad4f30daf3166d8dac4b9268dd7c4a0be2ac58788c00a7168d3bfb9eb5d6959fc9294096bcf874c5e40394436c8eefe955c893ca62cdb4c4e41924807de1e4e17c06f0f11a221e17a2e5fde25a56675f300d02d4d8c758251d566cb30666235565b7d0a3f97d87e55b9a1f6525a6944c6d6b685f991e066da52943192f51153dc56960bb2327bb543967a0b108beb6f1aedaa02efed85096a4c1df662798b9a657323069322aa915c82c0b8e914920846c88a7865edaefb105355ba9d408313add2f000e6e423c816da2f51fc07a6587a386adc71daa7777b3c26260ed88c7f6329b903d0115f15365a95cb0907f8858bc1fd7aaf5782161389182bcdc01ea8a7610a0d5d0f19366b4f441c9f5fb967c0f7a41452e5c313842a5f6c007e2754e2859a02fc5d87e7467d96916113673255ad0ba5cd5d529d8fa878382669a93850472b03e70abfb5bfa6a5cb9680f0b6c398ffae391b0ebbde95164896d3705c4df25100f2e42609e655fd615a268aaa432339aea51f23ccf1fa14d05ad26be653cf1300d7ef4c0987d42152a0fce530e809b04d5f0647d86a00c65ceca94adb65f92f00266921382000e0907b9eeaef4bbb3cf859b26b43787d907b184914bde1bfaa0696d5f9aad537953e279d92a201d2bffea6522dfb98905e0bd440d5575f94190417467be4ac2eb642ee5cd88d79b8da95199831bc0bc25087c3c85b68b8fff40eadff7d7f75271e6f0c0034f718cdeafa093db2ae59e827d7cb8154f1f4e7e804171575a41d87f23cc4215fbc49b990cdd9526ea94142de63607c19ea64e2b007161b0bd681eae0f2c12742331d0dbcafae0b1564c13693e7734364c5a038e50b3ca0d6469916f200f7cd08900e6472807fdd6393a41edd5fa0328eec51c53b0ad7e88417c9b71155bfb202b016190c875000f08a780e7b7668f92f4365906802209ac6f4773d0c0979f8ad2eb34370bf96f1031b1cd186ff5b7ff33874e1e308c67c2e2ad8de1aadc83d11601feb155f0878a358dbc178dc0b3bd19290f426022cbe8345515bbfe634256be2f4e4aa1598c73c045c1435a0681ef8b4a26ce705c765ae7d82d9704e20135096d26ec0908615a60e50bdd88b141173f364dd9e0fa3b40aa6528aa335066686e97dd3490af006fa1f43e1c04e027e0a3ea0360803aaab936e02fe39ff42598e8d46289ac8d2ca434aa1fa69d2a0bd32ac38ce430a5121ad4bb2632c42580fcb29a1d0dc8ba5798bb2f26917b0d0ff52ace06f9d03b50a64fb37ab3fbc9d354ac7d1d78935e7906888bb129a87c20075c50461800c19bd23c58d552fe3ca1a626574013609cb049ac0e865682f972cd00aec271f03a2d935b5ffa73cabea19cb81a9dc120d6d878f75f022983d626b52216a69230ffb5da0c330cdae27f3e91dd3514c57c3230fb472b50ef5e79bb18131427f34001e3047b9a5fc4410c6448fe4edd60b2ec82c70297c109eb90ffe56df8e926801d32c5b656ae22bd25c4752371420cea4a3bfb174f33705759cbf246d8bf9cb058da3ee8a38d8dddf23fcfdf0f25ce190c069361819e6d210f6670c312470c9037c48a4a8f323fc38983af4f784ec185d277dbee2c769b63072c05eb43b25d80ee7f8e640d152e92a3f870ca6dcc483f0a6f68d909abaa910d4b1ee437f04040f511793176063894eb30c36d13421fbe11b90fb48b2381b4240214147ccde410e6941aa8aa359f49b12b732d536514b1897738f461be3ce2f102b27d1ac41e5060601d02443e402067818eaf7da156171a458d4a7efe774bc1558b50614217609f6ff7d7109f2912fbdf1faba76ed19d82c2c34e4e3dc45474827467de8cab80d4d2db059602710500b3a5c2f31a24aebdb104f8aea09f5405b0cac8816e16f02e9058576f0ce04289104aa6763f7cc3236e6d776b5b1b16fdbf6b1e64b6a75076b2f0bb491c36f64d3938ffb08821690da64f271253c349ae7a1994e4204730c1efb10bcce4930d44678f3519535b37aaa3986225d1c27c3fe0d980d2e3b13019a89796d0a3730531c5c61252a451df70dc9f4f0e50873a517976343fc89cb0ef276e7a145f2055961359cfd925be4443f14aea6337bdf9d372aab9afc3b4c06146aab5ae731978385b9fedba60c8613ebf509e6c796f2a9ab7cd8b9f94907043361d6e215f5fc29c201af7301274cef05acfe1780c64f79b65d62e84a91e50e34f6876aeb352df01fb889872e29b83e05fa1c8fa7eada9b8bc913ee2a73650131bfc89e51418221a06decc6d2398c02d7db58238eb3ca5fc3e3d79ef9466d03777660dc85b4352b3c80c2ef1bd96f8c302080cd65531733808509d700378f035360364d23a4b7aa140dba3636c3a5e046af1a833a6998481380694ceed4470f456b4610eae98b1d470ee7e2585a399c49986461fae4ca97a43fa83430fdcd003007642e784b565a73d03d817cec344ec81a26b4f842f4d1af3ee49ea93b6d024557f7a50e8bc7207fe1adb413fe154d6497a994d7c60bca3d5ed79c2d8406001763e3f0de86b3a8c3d0466a7bddfc6f6dec849bd9436478b5422f5a90b647011b1b468d0c1e2e6cc63fffe6b6b56109e4702719d4c4a52ccd1f02e399e85e003cc534f64b0b4721ab490d9202d05c128b20298b966044d754c3dd945f309a0da0e37da0bb326ab010187709036da52326ce317716dcc0a2b517fa91eabc1f036271d8242a4ec64a56263472566a365f1a6a3376406e15ec9b9af81c7e1c0c02926ad9372f06a274225d276141407b10fb98341700809aa4f497cfb15c403f0208e837ec162bab609ff2df881e345f61ec03b8d06119a0cbcf19d39d0fac6309c66ebc27ec801ef64d3363108aa0240d77584c937afddfc8215dd07bc1b1fe0daeb268781577132417b90db5c522ee737e1b3f3c9cd01f600433e7271635320a3edf04e2790c9f36e3e3bdfd8d5f7fc1369c416a3772a0738c4578a2c6c9520a21faf5e49488ecc63a9251b6f495afd059c353e95650d40fdcd60bd9ac8cdd0a8673b419b5def3d69a27eccdc4333b4ea592da1642eacfa65219c68f4dd7580cc56705adccfc61469076a9f0bdbca257fe77fa3722472ddb07c91d857fbf20008d8d39bd72ed5f53113996b4fa829c0a1cbed4b3feabcec3c377220ed76c340c8b1ad75c80f60e901941c1f0883aa03e9aa3e81bf239a788fdf1b82c7e59360873ffb1dba43ae5c9ecbee26eb049fb781d36f3396d713b51212fc6394a36580e98a9bf610201a3a8e38c4db4597c4981497a73cfd00ce9095cb6d4955ff83100932e820461de7da9b293f3de9c1473b099f21478335f8b53367c670af5822706cc79743546e9bf8093361719af338a6ac6755d17a25e61f832d72e592318740e5eb513bf005bbdf5d2753d753c89ae66c68250468cab8928614e111f8663080c9567fab81d44dd854757c8ac2f44299f144bf2669513cee0856ae9ad02f9ac0d65a51f43f175c9d224eb5cf4229d5a8b6bddabbe73300ffb20a1794c4fe0bf05adffe270e7e49e3471c4cfb5d619744b6121cbdd99c70b45e60aa48732bbcb06e0ed19742fca2bc3780025c96c6756ecf5f22d3ac71c2ce4ef25803ee57bd20d8cbdfd08f24dc01e2aaf3d3451573abc6375c95b2bb3a2a6110150d38772e70648d5df57ad040f7f2f8012866908cc6922b1e424e1894f2fafe19dac18efda0b734445e2cd736a0ae78c17549e1f8e6a1b37be7930234b75d06c6518d507550eb625106ef26cbd2ab90a62687c4d84439e416a25149d9d91ed98ee540cc6a80e3214ebac4c497a977893ffa61b061869b9d73bbfe43d6ce10a3069de192a9e0cf45e7500034da980497bfde570b8527f7172fc3c02b140a6d4f62bf9060f1c0b01d12f6c37fd5f30ac0627dc9285e354097bd7fa502daaedda0b769e97a3570743a845f2a18c22a88db9c90ccc9d42c6a51555a1e67b0a540c492659ad5a5a0a9beebfa4dc30670eb5d03d4191a2ebc442a45f4bf22f9d36d3f3eaccfe5bb00588edb09ae238c60258ccf86ca3e356ee2cb860b80d7fdf8c82e939e7bb97ae02b6a1ca23f1e65a03e7b7ed8cc7108378ba36d58a9af550867dae21b0363079094abc123803d6dedbb7cc2b0ff42a3c9f8bfd5e7f7cf4ed4a9f36fdce6a6d860f3b9e0c607377ea35d363f61537400dd5067899c745599af81c21641ce49c680dc95f13953f9b385e02c7ffd2b99875b43c365dabfb4665620008384b75c5140fd8e6552fdd1f1fa539de0186b7ff2537890935157ae0c8e78b6053fa737419017aa0987b5966c29126cdd9bcda79f57bda712bad032c4de369b91abae075cb01e6eefad1fd170890f1c6b7f3a1d7664d0391857d7e114f3779bbc264458084032e24f9cf228c862f96b34468ab6e8eb406414e9d640a4aaf274177afd2172705bed8ae917f04a51d2ea48a9018d41bc571e248684fcb2093391ebd7b912a53042390a2d9a4abd6fb6dd44749f5261977423b71da64c7e79fdd6fb5911d6df309827a4beafecfab05ff45da500e35b247dedaba4e9233045521e6dfaa138be10bd73e7c087d5ed774a89651c655b856fdd01ad5c98c7836ddd53545bf709aff017b550693cd7adec89c00699bdc19618cb3091306bb990f39800b66560c26360f65915d036d9030af531d7dc108f099c9977c1463cf63973f3b54179d3f34cc0d8f782667711544301684b1f5d5a59434613a89df992753a1a250062180cca2024107d5ccbfb8915e452d7c16ac2460ca424260522f685a53e528cf7bda999e0b61935a5f7886ac2304d11c186398e2cc94f7ae0b8f08ad5e1295289b6efe640e"}; // TX_AND_ADDR_VIEWKEY_FROM_STRING(tx_hex, addr_56Vbjcz, viewkey_56Vbjcz, // network_type::STAGENET); // GET_KNOWN_OUTPUTS(known_outputs_csv_2_56bCoE); // // the ring members data from the above tx // // // // this hex is obtained using onion explorer runnign with --enbale-as-hex flag // // it is hex, serializied representation of of map of key_images // // with corresponding ring members output_data_t info structure // // we do this so that we just mack all the calls, instead of // // accessing real blockchain for this data. // string ring_member_data_hex {"011673657269616c697a6174696f6e3a3a61726368697665000000000111000000010800000101010301040105010601070600204aa9d101000001070001a06631316433336266616466633330303830393136333966303333323131346662353762373930663263316363373363636538326335363262656338313132376330303030303030303030303030303030666631333030303030303030303030306263306561653562396336616436333837613431313933633436663363316430373136643737643634653232623265303762346263653735363736356132306201a03039663566643065616531656662353732396362636330656464396335316330316536376663626661313066626435326338613631343461343236333637393530303030303030303030303030303030303831343030303030303030303030306263306561653562396336616436333837613431313933633436663363316430373136643737643634653232623265303762346263653735363736356132306201a03536383337333263633563373537623334373738663331396565343239613234363364663936313263623334336461623263303432346433393962316165653130303030303030303030303030303030306331343030303030303030303030306263306561653562396336616436333837613431313933633436663363316430373136643737643634653232623265303762346263653735363736356132306201a03164333966383364366163303731616435316465326132366663326266656163623464343738633264306432383931366535336537613535303263303737313530303030303030303030303030303030306431343030303030303030303030306263306561653562396336616436333837613431313933633436663363316430373136643737643634653232623265303762346263653735363736356132306201a03430316533363332636139643062313463393536656238323135363635366665396437613837626161323132343736343738666536343037653664363331353630303030303030303030303030303030306631343030303030303030303030306263306561653562396336616436333837613431313933633436663363316430373136643737643634653232623265303762346263653735363736356132306201a03031313534633661386161653539373361393137323339383836663836306163663135633230626661643632373963353939613231623233333733643061353230303030303030303030303030303030313931343030303030303030303030306263306561653562396336616436333837613431313933633436663363316430373136643737643634653232623265303762346263653735363736356132306201a038623762623235616132336539656539396564373430333066636262613231383436306463343333326437633166663830343337323434346366316564653461303030303030303030303030303030303265313430303030303030303030303062633065616535623963366164363338376134313139336334366633633164303731366437376436346532326232653037623462636537353637363561323062010800000101010301040105010701080600a007c2da5101070001a03531623763653437633337616132363839356633313230633661376566393837343062326332626537306338396630303734373133613036353966313262356130303030303030303030303030303030303031343030303030303030303030303432333236393938353133306631363635313661356261383631303936643732656363633637616461626134356562333733396130656263363161333230616501a03365623234383835343166363130343036393466643161373433353534366163373864623531653864386539393535643735316665336134383233306530353330303030303030303030303030303030306331343030303030303030303030303432333236393938353133306631363635313661356261383631303936643732656363633637616461626134356562333733396130656263363161333230616501a03864323330666663336464313639313064393034366539356331316538323365343566323839316632356233643836646236643836326237376162343661623930303030303030303030303030303030323331343030303030303030303030303432333236393938353133306631363635313661356261383631303936643732656363633637616461626134356562333733396130656263363161333230616501a06261373733653332636239343263626566373866663933393166333062303438333031313433643133626330323132313133316334646235623734633036643330303030303030303030303030303030326231343030303030303030303030303432333236393938353133306631363635313661356261383631303936643732656363633637616461626134356562333733396130656263363161333230616501a03136306563656530383365363930326631316365383566616262386237633437626331376136383932643937396165353563626332626131373939363564323030303030303030303030303030303030326631343030303030303030303030303432333236393938353133306631363635313661356261383631303936643732656363633637616461626134356562333733396130656263363161333230616501a03362323661646532633131613339663936386663656261396564616131306662643338333966353662396233343165353331623864323737396332393839383930303030303030303030303030303030333631343030303030303030303030303432333236393938353133306631363635313661356261383631303936643732656363633637616461626134356562333733396130656263363161333230616501a065623337383636663032616235666330363135613039633161363438643762356233623437353065336131643838373730663938343532376166306137623033303030303030303030303030303030303337313430303030303030303030303034323332363939383531333066313636353136613562613836313039366437326563636336376164616261343565623337333961306562633631613332306165010800000102010401050106010701080600602225aa3f01070001a06232303433366466353031333766373030333065633934383663646530366230393532366337383933313937393537633335663965393165663265373132336230303030303030303030303030303030666531333030303030303030303030303537643334656637353433626534376237626634393763653461313736653738633664363563643332376636346261373563323764313537623333373132356401a03764646166616338643637353065353936343632376263646333626637373135363538666130363364313430303764386631336433356437373739373262346330303030303030303030303030303030303831343030303030303030303030303537643334656637353433626534376237626634393763653461313736653738633664363563643332376636346261373563323764313537623333373132356401a03463663135313965323265306361613632366638636165663131383234323237666232663438313233313539343231376531653139323636333966626431643830303030303030303030303030303030313331343030303030303030303030303537643334656637353433626534376237626634393763653461313736653738633664363563643332376636346261373563323764313537623333373132356401a03736653630306434613336616436346530383734316336623364653065383066323333653864353130326434306465663161643439393936343861653934343230303030303030303030303030303030313431343030303030303030303030303537643334656637353433626534376237626634393763653461313736653738633664363563643332376636346261373563323764313537623333373132356401a06131313033326436303930616439313834666231396661363432343862313062356632363665616665643135306531653239616266323130623562646262333230303030303030303030303030303030313831343030303030303030303030303537643334656637353433626534376237626634393763653461313736653738633664363563643332376636346261373563323764313537623333373132356401a03539333162323334313636643439393130383730323537353638636564363465396438653431386533313333336337336266666464333538326637306430656230303030303030303030303030303030316331343030303030303030303030303537643334656637353433626534376237626634393763653461313736653738633664363563643332376636346261373563323764313537623333373132356401a036356538323937346461386435356565653838333432326462366432393339396532353139643265633038313763396138303135306638353262383434643338303030303030303030303030303030303261313430303030303030303030303035376433346566373534336265343762376266343937636534613137366537386336643635636433323766363462613735633237643135376233333731323564010800000103010401050106010701080600602225aa3f01070001a06232303433366466353031333766373030333065633934383663646530366230393532366337383933313937393537633335663965393165663265373132336230303030303030303030303030303030666531333030303030303030303030303537643334656637353433626534376237626634393763653461313736653738633664363563643332376636346261373563323764313537623333373132356401a03534353832373634303333316465306532613262323834613663373435363539646431303463383964376639316533373038616237373535316262393662653430303030303030303030303030303030306531343030303030303030303030303537643334656637353433626534376237626634393763653461313736653738633664363563643332376636346261373563323764313537623333373132356401a03463663135313965323265306361613632366638636165663131383234323237666232663438313233313539343231376531653139323636333966626431643830303030303030303030303030303030313331343030303030303030303030303537643334656637353433626534376237626634393763653461313736653738633664363563643332376636346261373563323764313537623333373132356401a03736653630306434613336616436346530383734316336623364653065383066323333653864353130326434306465663161643439393936343861653934343230303030303030303030303030303030313431343030303030303030303030303537643334656637353433626534376237626634393763653461313736653738633664363563643332376636346261373563323764313537623333373132356401a06131313033326436303930616439313834666231396661363432343862313062356632363665616665643135306531653239616266323130623562646262333230303030303030303030303030303030313831343030303030303030303030303537643334656637353433626534376237626634393763653461313736653738633664363563643332376636346261373563323764313537623333373132356401a03539333162323334313636643439393130383730323537353638636564363465396438653431386533313333336337336266666464333538326637306430656230303030303030303030303030303030316331343030303030303030303030303537643334656637353433626534376237626634393763653461313736653738633664363563643332376636346261373563323764313537623333373132356401a0363565383239373464613864353565656538383334323264623664323933393965323531396432656330383137633961383031353066383532623834346433383030303030303030303030303030303032613134303030303030303030303030353764333465663735343362653437623762663439376365346131373665373863366436356364333237663634626137356332376431353762333337313235640108000103010c0120012301240126012a0500282e8cd101070001a03062323530383665633639636333313666656263343361333166636263636138353861343638656233323661393462393238343065663633376431613030666430303030303030303030303030303030323431343030303030303030303030303431353462333436356134333732363731656139653036346137636161363665313462343938366134363638393138616661353739626631656432353036646401a03732646436613330623435366332326365623365353664643338346636633763653263323530633738613630626665646430323765353132313235616336653665333834303030303030303030303030613738343030303030303030303030303431353462333436356134333732363731656139653036346137636161363665313462343938366134363638393138616661353739626631656432353036646401a03439346664646665346537353161613535373036643639636366643532313630613661643232633138663165623935373264623934643766343964346361616366373834303030303030303030303030626238343030303030303030303030303431353462333436356134333732363731656139653036346137636161363665313462343938366134363638393138616661353739626631656432353036646401a03131363739356135326662373831316662373131366464313065353434313035653636386136613938663465353562613638636435346661653836306638303366613834303030303030303030303030626538343030303030303030303030303431353462333436356134333732363731656139653036346137636161363665313462343938366134363638393138616661353739626631656432353036646401a03339626133336263633164386165656138336331633662333062346132316666323663393862363037346434626533313839376133333363623162323931316666623834303030303030303030303030626638343030303030303030303030303431353462333436356134333732363731656139653036346137636161363665313462343938366134363638393138616661353739626631656432353036646401a03264363132363861353661663435336233323364373331383038363338386564356263663466316533623437353962313230376430353331363439303038303666643834303030303030303030303030633138343030303030303030303030303431353462333436356134333732363731656139653036346137636161363665313462343938366134363638393138616661353739626631656432353036646401a03331353632623438353266613866363032373236626338386566373836353634303238633265316461343366303733353732323337353632356166316362306530313835303030303030303030303030633538343030303030303030303030303431353462333436356134333732363731656139653036346137636161363665313462343938366134363638393138616661353739626631656432353036646401080001040135017f018e0194019501be0400ca9a3b01070001a03739653366396662363034376230323766356435626366333234663936313730316130346162633335663536373436383066343530666330326330663165306230303030303030303030303030303030313231343030303030303030303030303863653634383333636563393030636236643561633436666330323337643866323433396333646661323338626166396363393431363661643265383938383701a03761333263336263646362613436353333366136393637393963313838396266373930366631636435393832303966666364383166316465653061623731653563393765303030303030303030303030386437653030303030303030303030303863653634383333636563393030636236643561633436666330323337643866323433396333646661323338626166396363393431363661643265383938383701a03661633063656434303365633162396636373031353239343431303934613261383563353630613164393037363064613630323332623461383531316531383563383831303030303030303030303030386338313030303030303030303030303863653634383333636563393030636236643561633436666330323337643866323433396333646661323338626166396363393431363661643265383938383701a03463396236383632346234396663316632353366643534353935356466653964333866623562336230306636373233626566336139343665336439356238653736323832303030303030303030303030323638323030303030303030303030303863653634383333636563393030636236643561633436666330323337643866323433396333646661323338626166396363393431363661643265383938383701a06361333765326161356466313363643930353962333466386338643032363735396365303837373439663332303962623838306432393530326237333533613066333832303030303030303030303030623738323030303030303030303030303863653634383333636563393030636236643561633436666330323337643866323433396333646661323338626166396363393431363661643265383938383701a03532376366653563343439386662336238313862393232653537333734616639333831623630356135313833643138356531343137393838313464646230393466343832303030303030303030303030623838323030303030303030303030303863653634383333636563393030636236643561633436666330323337643866323433396333646661323338626166396363393431363661643265383938383701a03264323038623339343765656166383630343136393134356335336363663333383138356130303937323865623838626330333466373332626262663961613362653834303030303030303030303030383238343030303030303030303030303863653634383333636563393030636236643561633436666330323337643866323433396333646661323338626166396363393431363661643265383938383701080001050112018a018d01ad01b301c50400e9a43501070001a03532333361303265333634633534303136643662626536383261643533313032643765383732333232626338313166653137663035613963333566656466383230303030303030303030303030303030333531343030303030303030303030303131366165356432396365633732616163353537636231346532636464353533653538386666386238313738323630313939633430636165613231326362363301a03030386335303535666238383532646133663936373663303439386131326335366464663230376636373931623466326261313463656261616236393439646663343764303030303030303030303030383837643030303030303030303030303131366165356432396365633732616163353537636231346532636464353533653538386666386238313738323630313939633430636165613231326362363301a06262346163623835316534383037656139353166356563363037303466646133663066633065333436336266386131316133353265356266646233313137386537343832303030303030303030303030333838323030303030303030303030303131366165356432396365633732616163353537636231346532636464353533653538386666386238313738323630313939633430636165613231326362363301a06333313666373366386165616465656366656461306632643561326464383434366331353734613233356466636436356465313135646432383031303932626239333832303030303030303030303030353738323030303030303030303030303131366165356432396365633732616163353537636231346532636464353533653538386666386238313738323630313939633430636165613231326362363301a03334623364333539313638313235393434643162613934643834633638346433306565323362316337313638323734646665343561346436366436306438343663383833303030303030303030303030386338333030303030303030303030303131366165356432396365633732616163353537636231346532636464353533653538386666386238313738323630313939633430636165613231326362363301a06137363566343162653062323538363931623562623464623361326434653866373730303664393236636332373365303563666664613536646332636365323630363834303030303030303030303030636138333030303030303030303030303131366165356432396365633732616163353537636231346532636464353533653538386666386238313738323630313939633430636165613231326362363301a063626565383638626630376562326361623666346166633333613830626139373836333063323861663361643236656537346566303436313730363435336661626538343030303030303030303030303832383430303030303030303030303031313661653564323963656337326161633535376362313465326364643535336535383866663862383137383236303139396334306361656132313263623633010800010502c20202d203028204020406023d060216070600409452a30301070001a06433636136613531626539323632303437386165663461636231663163323731363966373730306366393939613830313033383665656164383039326362316630303030303030303030303030303030326331343030303030303030303030303431396637633934393130343334306664336365383539343864326566396630646434626233643932663561373832633566373830346237353239613133633601a03039616338386130383935323237613232356232356137316137633865396365656465353563383732376535303136633039656134643336346336333161373766373766303030303030303030303030626237663030303030303030303030303431396637633934393130343334306664336365383539343864326566396630646434626233643932663561373832633566373830346237353239613133633601a06537353438313264363730623031333239623264633035383962616463636130356162623465626466363261376165613664353534313731333532396334643030373831303030303030303030303030636238303030303030303030303030303431396637633934393130343334306664336365383539343864326566396630646434626233643932663561373832633566373830346237353239613133633601a03938613733666366663965356534646466356639316335363566646332643835633132356463336336333630306539646230643336636536353262663163643962373831303030303030303030303030376238313030303030303030303030303431396637633934393130343334306664336365383539343864326566396630646434626233643932663561373832633566373830346237353239613133633601a03734623636643030376136613062353766633532643533353364346332376231366166393737373831356661626138633136316564626538343737373036356233393833303030303030303030303030666438323030303030303030303030303431396637633934393130343334306664336365383539343864326566396630646434626233643932663561373832633566373830346237353239613133633601a06466613931333462333965383231383538646136663132663535653065383030656332393266626334303132396463303237343733353836306462353433346137323833303030303030303030303030333638333030303030303030303030303431396637633934393130343334306664336365383539343864326566396630646434626233643932663561373832633566373830346237353239613133633601a06337313836623937366161313065363737303062353939323732373234383138623361656266303465613365616438616430373465633037383863666531353234623834303030303030303030303030306638343030303030303030303030303431396637633934393130343334306664336365383539343864326566396630646434626233643932663561373832633566373830346237353239613133633601080002ee0102620602400702c6070229080256090262090400286bee01070001a03534363536653433613663613163643034373635363866613161346465396665306639393130626634303734336333613238396431663461613637373061613930303030303030303030303030303030333731343030303030303030303030306461336163623030616232643864636361636563386637373539323163343065323662316666626563613965623765363537323536663539363866323334316301a03235613035643861313831356265323934613335623266626435316262306637643836626436623463626533623036386537653763343064343163653931386432323366303030303030303030303030653633653030303030303030303030306461336163623030616232643864636361636563386637373539323163343065323662316666626563613965623765363537323536663539363866323334316301a03631343134376334623062623661613261613161353032616636656332333234373034336232333038383661376533636563383165663664636264613833656238353438303030303030303030303030343934383030303030303030303030306461336163623030616232643864636361636563386637373539323163343065323662316666626563613965623765363537323536663539363866323334316301a03435356637336231303633353234353139666163633739353335346535376531346132346536643464356635396433313736666334363863386436393238633035303464303030303030303030303030313434643030303030303030303030306461336163623030616232643864636361636563386637373539323163343065323662316666626563613965623765363537323536663539363866323334316301a03839363839623739613662383263376233323334333839376466383533303431356132666563343634366563383531616635386139383465386534386138353566383531303030303030303030303030626335313030303030303030303030306461336163623030616232643864636361636563386637373539323163343065323662316666626563613965623765363537323536663539363866323334316301a06664633631306631326634346463633338303936383533646562633438303534626432313231303331373434393434613331356165663432633131373435343464613564303030303030303030303030396535643030303030303030303030306461336163623030616232643864636361636563386637373539323163343065323662316666626563613965623765363537323536663539363866323334316301a038643531306634623936366530333937303463663761313437643137313731343834373731303835316234376364343734633335616139323139346662323066653635643030303030303030303030306161356430303030303030303030303064613361636230306162326438646363616365633866373735393231633430653236623166666265636139656237653635373235366635393638663233343163010800024002025c0202780402fc0402110a02850d02a90d0500205fa01201070001a06132383735333331303464653734666235333962366432653433346164666566363138653033336364616637356235623236336434623635666666323932616466663032303030303030303030303030633330323030303030303030303030303561636366643136323237396135316338623362643564333637396539313839363761323634656130363364333764666635653334353765633330376434353701a06561386530323230386332656238666636653333383636366563626139316263656666653361626339363863353561326162636639633636623238656665366130303030303030303030303030303030323831343030303030303030303030303561636366643136323237396135316338623362643564333637396539313839363761323634656130363364333764666635653334353765633330376434353701a06639363934613834373166363534653935366361623730373331623632623336626338633336366631316162326633393862373962613066363864363632323133343161303030303030303030303030663831393030303030303030303030303561636366643136323237396135316338623362643564333637396539313839363761323634656130363364333764666635653334353765633330376434353701a06661616338663564326566613835643238373531323665366238353066633962653962333835343064636537376433623166363761393930393638353335333964643266303030303030303030303030613132663030303030303030303030303561636366643136323237396135316338623362643564333637396539313839363761323634656130363364333764666635653334353765633330376434353701a03265303739613135643632383663333664326162653861626565613765306161613233656132376538623366653139643631613761333833636262393339396139613566303030303030303030303030356535663030303030303030303030303561636366643136323237396135316338623362643564333637396539313839363761323634656130363364333764666635653334353765633330376434353701a06261663364656363323232363164663634356233643331613639653038306432356461316564346330336630343033386632363263356639376339643661396639323738303030303030303030303030353637383030303030303030303030303561636366643136323237396135316338623362643564333637396539313839363761323634656130363364333764666635653334353765633330376434353701a03036393164623964663531613138626630383765306264323065663338646361336263396636373062376432643135343635376231336237343832373161343262363738303030303030303030303030376137383030303030303030303030303561636366643136323237396135316338623362643564333637396539313839363761323634656130363364333764666635653334353765633330376434353701080002520202580202d20202bb0502b709023f0a027d0c0500c817a80401070001a03530646436323038623330393231303336326662643631613631663539646138643263333132303332626264613230333635626565306561323731366437376431303131303030303030303030303030643431303030303030303030303030303039626165643961336334346232323238356130616561343134386361376465396265613936336366363936323362363833343435633061313061353836373701a03937353130336338386634303266353336356564333466303963303935663665333163646235613730383264613966656334353432396562633236373364306230303030303030303030303030303030303231343030303030303030303030303039626165643961336334346232323238356130616561343134386361376465396265613936336366363936323362363833343435633061313061353836373701a03363653262363437663932666364656238306438646336303666383265633838326331356361633537303438663235306237616664636334363732343364393461323236303030303030303030303030363632363030303030303030303030303039626165643961336334346232323238356130616561343134386361376465396265613936336366363936323362363833343435633061313061353836373701a03934353661346432396539383762323662323432616634393965343566353237643631383039343338353961336637633264633535303965333831626232626263333365303030303030303030303030383733653030303030303030303030303039626165643961336334346232323238356130616561343134386361376465396265613936336366363936323362363833343435633061313061353836373701a06337373535663237383139333063313535343930643366356538333833626630306236616563643130313866376566663063613163666661666135643361383938633664303030303030303030303030353036643030303030303030303030303039626165643961336334346232323238356130616561343134386361376465396265613936336366363936323362363833343435633061313061353836373701a06162323038396432383165653432383636613634323436323935396338626631306433333839623661333830366562393839313762353435633036333361616131343665303030303030303030303030643836643030303030303030303030303039626165643961336334346232323238356130616561343134386361376465396265613936336366363936323362363833343435633061313061353836373701a034323334326437323735303937636230363435616337666266376234646634353763383364313537363739313661333834363265613833333361663262326532343838333030303030303030303030303063383330303030303030303030303030396261656439613363343462323232383561306165613431343863613764653962656139363363663639363233623638333434356330613130613538363737010800025302023f0802720902d909029d0a020c0c02390d05005847f80d01070001a03064666235633766386435343137336632323661613464366234353566373939313261353630313562616662663934336532666661623832333035383164646130303030303030303030303030303030666331333030303030303030303030303636633261303039363566396266636262313165613033636631643633316230306538613165663761363062316265346135616330393233306266383137336601a06130363063353936643538326135666461656264626366383064636265396534353334646331316537663136336364303531323435363736646435643231393132303464303030303030303030303030653434633030303030303030303030303636633261303039363566396266636262313165613033636631643633316230306538613165663761363062316265346135616330393233306266383137336601a03537303334323734336233363139643737666231633264393666356238313636333237343762343464383036323931386466343432613665656239623963373762643633303030303030303030303030383136333030303030303030303030303636633261303039363566396266636262313165613033636631643633316230306538613165663761363062316265346135616330393233306266383137336601a03638363666666238363836373933666565656536666436643035303435383664303235363862383739313965663966323532646136316230383363623530326432343634303030303030303030303030653836333030303030303030303030303636633261303039363566396266636262313165613033636631643633316230306538613165663761363062316265346135616330393233306266383137336601a06537393363386535323566336233373434383238383765666164636536376265323462393236336130626465376566303961636337313331313335346235656365383634303030303030303030303030616336343030303030303030303030303636633261303039363566396266636262313165613033636631643633316230306538613165663761363062316265346135616330393233306266383137336601a03464396635343465313934336637643030323063643536633165613333363935656131366536653731326332326435653234333661346532356463656133356465313762303030303030303030303030613537623030303030303030303030303636633261303039363566396266636262313165613033636631643633316230306538613165663761363062316265346135616330393233306266383137336601a065316464363163303030333832616665353962356134626333383533623036366466306564646437323139636230353731393831306637356662323633656332306537643030303030303030303030306432376330303030303030303030303036366332613030393635663962666362623131656130336366316436333162303065386131656637613630623162653461356163303932333062663831373366010800025502021a04021f0502120602000702140c02460c0500743ba40b01070001a03637376232393932343461643130376530323634333463363564353538613265336561343633623637386261646564356639346664646661643931653536663330303030303030303030303030303030323031343030303030303030303030303663386530653461363334663835396133316162326637613738633063346135393338636237376630333335353061343764376533313831623662323665633001a03536633664353764643762386134396536323630336637326334303630306337336663336633356535623561383231663461353535653732663033363634336465333230303030303030303030303030613732303030303030303030303030303663386530653461363334663835396133316162326637613738633063346135393338636237376630333335353061343764376533313831623662323665633001a06665616562336635613631333364303765366330323763616464393563623935396136653264353265656361343163663137343638336532313736336466376331363337303030303030303030303030646133363030303030303030303030303663386530653461363334663835396133316162326637613738633063346135393338636237376630333335353061343764376533313831623662323665633001a03134353862306337343766316563653532616562616235646439343165633538353364373934303739353262343531646636376164623235623935336362363230393338303030303030303030303030636433373030303030303030303030303663386530653461363334663835396133316162326637613738633063346135393338636237376630333335353061343764376533313831623662323665633001a03035313562383735393132353563626563613634666666303933623831373764346564326434613439666631326339663163653932643530366239353035376666373338303030303030303030303030626233383030303030303030303030303663386530653461363334663835396133316162326637613738633063346135393338636237376630333335353061343764376533313831623662323665633001a03566383333366230613865383561616437313263383036623239373832323634376638306132366434386337363361373239303838636337313337353630663438343831303030303030303030303030343838313030303030303030303030303663386530653461363334663835396133316162326637613738633063346135393338636237376630333335353061343764376533313831623662323665633001a03362353437303461353035653331333438373634303432393138663061663063303539383465656434343163313436636365373935643535373861663361336462363831303030303030303030303030376138313030303030303030303030303663386530653461363334663835396133316162326637613738633063346135393338636237376630333335353061343764376533313831623662323665633001080002590202780502a90902250a02310b02c70b023a0d0500205fa01201070001a03966646537613263633534633865666332633461616561333137636232366166393139363664623739323565303364663366643066306163373338356431353930303030303030303030303030303030666131333030303030303030303030303561636366643136323237396135316338623362643564333637396539313839363761323634656130363364333764666635653334353765633330376434353701a06230376365303637303430343832346365663437326638613736326134616635393732616138373065343338366166326263303738343836316531313234653435393330303030303030303030303030316433303030303030303030303030303561636366643136323237396135316338623362643564333637396539313839363761323634656130363364333764666635653334353765633330376434353701a03233623932306234333466623833663263323765373164343466376330396136333763336237316661343463313532356638336633313564626664353032343433323566303030303030303030303030663635653030303030303030303030303561636366643136323237396135316338623362643564333637396539313839363761323634656130363364333764666635653334353765633330376434353701a03735623732663137323232663435376137333662656432316630306562663937643433393930633339323666646163326133653338306261653732626137303661653566303030303030303030303030373235663030303030303030303030303561636366643136323237396135316338623362643564333637396539313839363761323634656130363364333764666635653334353765633330376434353701a06437373439326237613335646232373332636438663736623431373262373165653462306636323436613933643334306166336261646234656664386333356462613630303030303030303030303030376536303030303030303030303030303561636366643136323237396135316338623362643564333637396539313839363761323634656130363364333764666635653334353765633330376434353701a06330386637666566636163643866363238316533366265623666393864393563363639376136376338623863653630353864386237623263343662346565303935303631303030303030303030303030313436313030303030303030303030303561636366643136323237396135316338623362643564333637396539313839363761323634656130363364333764666635653334353765633330376434353701a036613138623933333037386137646362376363663361366530643839376433346536373837343330623961393932316231636161353730663530656161346362343737383030303030303030303030303062373830303030303030303030303035616363666431363232373961353163386233626435643336373965393138393637613236346561303633643337646666356533343537656333303764343537010800021d14021f1d02592402bf5c02036c02af6d02767006007083d05d0601070001a03039383264353737656235613633303935303764343265656266373764356566386165346234393566643862396564396161353362366231393637356438636330303030303030303030303030303030316331343030303030303030303030303539613033613331353361393934643732333237653464393234323164336533323931623166613162323430646534346239326437663632656330313238663101a06639643433613838313636303638653537343838343266336634616536633536323733636633643137366631346136633334346663656438313439613131306335363164303030303030303030303030316131643030303030303030303030303539613033613331353361393934643732333237653464393234323164336533323931623166613162323430646534346239326437663632656330313238663101a03139313838623939613266393265303561326565623464366637303966373439306133643239626238643131663365316338396231656333663166386438353739303234303030303030303030303030353432343030303030303030303030303539613033613331353361393934643732333237653464393234323164336533323931623166613162323430646534346239326437663632656330313238663101a06239623237393639366161636165653936623661313132626235346436623563343531643832366433623539346233613137393633333332656466383134636266363563303030303030303030303030626135633030303030303030303030303539613033613331353361393934643732333237653464393234323164336533323931623166613162323430646534346239326437663632656330313238663101a03838393331636432373730613864653064313933333835313866626332346338313731353634323465343564623137626538373331663836376638633939366133613663303030303030303030303030666536623030303030303030303030303539613033613331353361393934643732333237653464393234323164336533323931623166613162323430646534346239326437663632656330313238663101a03665313563303837363432363265646564346166393766353963613364616261393039353530343839343764643531386365373437636433623838333063373065363664303030303030303030303030616136643030303030303030303030303539613033613331353361393934643732333237653464393234323164336533323931623166613162323430646534346239326437663632656330313238663101a06262303534336230633135633265616564393439353334303032353832653438373130323863326338653738373736643765666161646537373236393364363261643730303030303030303030303030373137303030303030303030303030303539613033613331353361393934643732333237653464393234323164336533323931623166613162323430646534346239326437663632656330313238663101080002ab79037301010350030103660b0103730d0103230e01036f10010001070001a06466643134343331636132636437313364346334636431356432373266633365366562393031646563386138623833663935633463383833326532666361313062376665303030303030303030303030376266653030303030303030303030306539663231386533633030653965386139653866663836646639653166383530376162316133383133613634616536633839643437633266316461346265333501a06265383664626331666663643761323435363739373966623665653230303734366432646361366562313734313934666263306431326435636265663031366137663836303130303030303030303030343338363031303030303030303030303233393337346431346531633066313333663065323133643863613531326666373938663839306366653266613361623634306531336365613464646565643501a06637303435326465373764643535666363643437306535633134626465393766303066356230333465396431623633643635303463363433363935623633663035633838303130303030303030303030323038383031303030303030303030306463333535336230323332376266383131643361613930316561623338616636303264383132663132643633393230383234383839343539656664326365353801a06439386137313631343465346231623636653432376464343633633164386562326233323334613463316563393262393730303662336630363836383333366137303930303130303030303030303030333439303031303030303030303030303161633364303739316238353435376438333331303733663039336661636433303964376661393131303939363439316537356537666364343032653630653101a03466613363643261373065376165323238623136643664623038396161396236353630636136633833343838386330343035326463333236616531646339393537623932303130303030303030303030336639323031303030303030303030303639373938353636613539383733663434313864643236346230316630653139623563653238343564646162653434346439396564333733393733663064376101a03239363665316234313863313264643562623265306131363230323732383063303562343032343231396535643034333430356565306136383030313337653332623933303130303030303030303030656639323031303030303030303030303335383666323135353632666633373064386336633666353266336134346139363533313336666465383633343131633432326439633333336438616333646601a03130386131653239336265643034396462633434643934393530323037393665663763336563356361356266643637633165613663373261323434313335306630303030303030303030303030303030333839353031303030303030303030303136323565393163656231626636333535643838323563636532316562623634356436303137313030313331326531663466303132626132643430316166396101080002a2dc0252f50387030103f30601038d0c01038f0d0103fb11010001070001a06139663337343430633338343131393166356235313137633064393335376638626561653931336333313238376262353333393035396637653231663739643261653631303130303030303030303030373236313031303030303030303030303235363763346664363936616166363461383632383764653830396462666637346336636237323335663730656637303266336564386462383365643736633101a06539366135626231363231353132646535333430653863343139653861636631633230626263396164333932626533666632333231383066393864393163373335653761303130303030303030303030323237613031303030303030303030303534613732386534316335303361356263306231313437643962646132633034616137373630306264323465663765356539336162633964333434376464373201a06137643437373834363537353862313566386161373131656338633739633164636361666162646635666231333066343765636137653435383935306237663239333838303130303030303030303030353738383031303030303030303030306635366437666262313163353734626561323331633433333735633038643062663936363137353638663764643438653739623162646632656438393233353301a03730323437323638663332363133373732363730346235326265326637623962623463656136363864663738633030616537663363313062386135646336363766663862303130303030303030303030633338623031303030303030303030303066626562303936383066356661336262316264373166333035306436636463383762396637363032636466316234643561336263346532366439633437373201a06639366161656632386565306233323933363431643663303766336230346338623163393032666165616262396235633566613139336563353235303937356239373931303130303030303030303030356239313031303030303030303030303834333638333366663266393435393231323931386561346431376532636164646535653634333236366665383433636563333631323238343666656363333401a06635353538346161343731303264666534363532363966373464656133653536613932656632376233313531663237363964383033393535666131636230333039373932303130303030303030303030356239323031303030303030303030303066643837316261323036363434356238306434373733666461313131636461356130393033643632306138643332303136353337326136383865616335643701a031313136383432653861303465643631326437346236626664643337623933303835316637383131306630643338633033313661313361333534656436356338303030303030303030303030303030306332393630313030303030303030303037383136656334346537623561626230383336306264346533346637313432313335313831646130303765623861353166393432616333636539356664643562"}; // GET_RING_MEMBER_OUTPUTS(ring_member_data_hex); // MOCK_MCORE_GET_OUTPUT_KEY(); // std::cout << "\n\n" << std::endl; // auto identifier = make_identifier(tx, // make_unique<Output>(&address, &viewkey), // make_unique<Input>(&address, &viewkey, &known_outputs, // mcore.get()), // make_unique<LegacyPaymentID>(&address, &viewkey), // make_unique<IntegratedPaymentID>(&address, &viewkey)); // identifier.identify(); // ASSERT_EQ(identifier.get<Output>()->get().size(), 1); // std::cout << "\n\n" << std::endl; //} }
102,980
92,983
// boost thread_clock.cpp -----------------------------------------------------------// // Copyright Beman Dawes 1994, 2006, 2008 // Copyright Vicente J. Botet Escriba 2009-2011 // Copyright Christopher Brown 2013 // Distributed under the Boost Software License, Version 1.0. // See http://www.boost.org/LICENSE_1_0.txt // See http://www.boost.org/libs/chrono for documentation. //--------------------------------------------------------------------------------------// #include <boost/chrono/config.hpp> #include <boost/chrono/thread_clock.hpp> #include <cassert> #include <boost/assert.hpp> # include <pthread.h> # include <mach/thread_act.h> namespace boost { namespace chrono { thread_clock::time_point thread_clock::now( ) BOOST_NOEXCEPT { // get the thread port (borrowing pthread's reference) mach_port_t port = pthread_mach_thread_np(pthread_self()); // get the thread info thread_basic_info_data_t info; mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT; if ( thread_info(port, THREAD_BASIC_INFO, (thread_info_t)&info, &count) != KERN_SUCCESS ) { BOOST_ASSERT(0 && "Boost::Chrono - Internal Error"); return time_point(); } // convert to nanoseconds duration user = duration( static_cast<thread_clock::rep>( info.user_time.seconds ) * 1000000000 + static_cast<thread_clock::rep>(info.user_time.microseconds ) * 1000); duration system = duration( static_cast<thread_clock::rep>( info.system_time.seconds ) * 1000000000 + static_cast<thread_clock::rep>( info.system_time.microseconds ) * 1000); return time_point( user + system ); } #if !defined BOOST_CHRONO_DONT_PROVIDE_HYBRID_ERROR_HANDLING thread_clock::time_point thread_clock::now( system::error_code & ec ) { // get the thread port (borrowing pthread's reference) mach_port_t port = pthread_mach_thread_np(pthread_self()); // get the thread info thread_basic_info_data_t info; mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT; if ( thread_info(port, THREAD_BASIC_INFO, (thread_info_t)&info, &count) != KERN_SUCCESS ) { if (BOOST_CHRONO_IS_THROWS(ec)) { boost::throw_exception( system::system_error( EINVAL, BOOST_CHRONO_SYSTEM_CATEGORY, "chrono::thread_clock" )); } else { ec.assign( errno, BOOST_CHRONO_SYSTEM_CATEGORY ); return time_point(); } } if (!BOOST_CHRONO_IS_THROWS(ec)) { ec.clear(); } // convert to nanoseconds duration user = duration( static_cast<thread_clock::rep>( info.user_time.seconds ) * 1000000000 + static_cast<thread_clock::rep>(info.user_time.microseconds ) * 1000); duration system = duration( static_cast<thread_clock::rep>( info.system_time.seconds ) * 1000000000 + static_cast<thread_clock::rep>( info.system_time.microseconds ) * 1000); return time_point( user + system ); } #endif } }
3,482
1,150
#include <catch.hpp> #include <filesystem> #include <set> #include <pddl/AST.h> #include <pddl/Parse.h> namespace fs = std::filesystem; const pddl::Context::WarningCallback ignoreWarnings = [](const auto &, const auto &){}; const auto pddlInstanceBasePath = fs::path("data") / "pddl-instances"; const std::set<std::filesystem::path> unsupportedDomains = { // “:functions” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "depots-numeric-automatic" / "domain.pddl", // “:functions” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "depots-numeric-hand-coded" / "domain.pddl", // “:functions” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "depots-time-automatic" / "domain.pddl", // “:functions” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "depots-time-hand-coded" / "domain.pddl", // “:durative-action” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "depots-time-simple-automatic" / "domain.pddl", // “:durative-action” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "depots-time-simple-hand-coded" / "domain.pddl", // “:functions” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "driverlog-numeric-automatic" / "domain.pddl", // “:functions” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "driverlog-numeric-hand-coded" / "domain.pddl", // “:functions” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "driverlog-numeric-hard-automatic" / "domain.pddl", // “:functions” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "driverlog-numeric-hard-hand-coded" / "domain.pddl", // “:functions” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "driverlog-time-automatic" / "domain.pddl", // “:functions” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "driverlog-time-hand-coded" / "domain.pddl", // “:durative-action” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "driverlog-time-simple-automatic" / "domain.pddl", // “:durative-action” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "driverlog-time-simple-hand-coded" / "domain.pddl", // “:functions” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "rovers-numeric-automatic" / "domain.pddl", // “:functions” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "rovers-numeric-hand-coded" / "domain.pddl", // “:functions” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "rovers-time-automatic" / "domain.pddl", // “:functions” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "rovers-time-hand-coded" / "domain.pddl", // “:durative-action” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "rovers-time-simple-automatic" / "domain.pddl", // “:durative-action” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "rovers-time-simple-hand-coded" / "domain.pddl", // “:functions” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "satellite-complex-automatic" / "domain.pddl", // “:functions” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "satellite-complex-hand-coded" / "domain.pddl", // “:functions” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "satellite-numeric-automatic" / "domain.pddl", // “:functions” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "satellite-numeric-hand-coded" / "domain.pddl", // “:functions” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "satellite-numeric-hard-automatic" / "domain.pddl", // “:functions” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "satellite-time-automatic" / "domain.pddl", // “:functions” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "satellite-time-hand-coded" / "domain.pddl", // “:durative-action” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "satellite-time-simple-automatic" / "domain.pddl", // “:durative-action” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "satellite-time-simple-hand-coded" / "domain.pddl", // “:functions” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "settlers-numeric-automatic" / "domain.pddl", // “:functions” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "umtranslog-2-numeric-hand-coded" / "domain.pddl", // “:functions” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "zenotravel-numeric-automatic" / "domain.pddl", // “:functions” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "zenotravel-numeric-hand-coded" / "domain.pddl", // “either” expressions unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "zenotravel-strips-automatic" / "domain.pddl", // “either” expressions unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "zenotravel-strips-hand-coded" / "domain.pddl", // “:functions” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "zenotravel-time-automatic" / "domain.pddl", // “:functions” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "zenotravel-time-hand-coded" / "domain.pddl", // “:durative-action” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "zenotravel-time-simple-automatic" / "domain.pddl", // “:durative-action” sections unsupported pddlInstanceBasePath / "ipc-2002" / "domains" / "zenotravel-time-simple-hand-coded" / "domain.pddl", }; const std::set<std::filesystem::path> unsupportedInstances = { }; //////////////////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("[parser success] All official PDDL domains are parsed without errors", "[parser success]") { for (const auto &competitionDirectory : fs::directory_iterator(pddlInstanceBasePath)) { if (!fs::is_directory(competitionDirectory)) continue; for (const auto &domainDirectory : fs::directory_iterator(competitionDirectory.path() / "domains")) { if (!fs::is_directory(domainDirectory)) continue; const auto domainFile = domainDirectory.path() / "domain.pddl"; if (unsupportedDomains.find(domainFile) != unsupportedDomains.cend()) continue; const auto testSectionName = competitionDirectory.path().stem().string() + ", " + domainDirectory.path().stem().string(); SECTION("domain [" + testSectionName + "]") { pddl::Tokenizer tokenizer; tokenizer.read(domainFile); pddl::Context context(std::move(tokenizer), ignoreWarnings, pddl::Mode::Compatibility); CHECK_NOTHROW(pddl::parseDescription(context)); } } } } //////////////////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("[parser success] The first instance for all official PDDL domains is parsed without errors", "[parser success]") { for (const auto &competitionDirectory : fs::directory_iterator(pddlInstanceBasePath)) { if (!fs::is_directory(competitionDirectory)) continue; for (const auto &domainDirectory : fs::directory_iterator(competitionDirectory.path() / "domains")) { if (!fs::is_directory(domainDirectory)) continue; const auto domainFile = domainDirectory.path() / "domain.pddl"; const auto instanceFile = domainDirectory.path() / "instances" / "instance-1.pddl"; if (unsupportedDomains.find(domainFile) != unsupportedDomains.cend() || unsupportedInstances.find(instanceFile) != unsupportedInstances.cend()) { continue; } const auto testSectionName = competitionDirectory.path().stem().string() + ", " + domainDirectory.path().stem().string() + ", " + instanceFile.stem().string(); SECTION("instance [" + testSectionName + "]") { pddl::Tokenizer tokenizer; tokenizer.read(domainFile); tokenizer.read(instanceFile); pddl::Context context(std::move(tokenizer), ignoreWarnings, pddl::Mode::Compatibility); CHECK_NOTHROW(pddl::parseDescription(context)); } } } }
8,253
3,159
/*++ Copyright (c) Microsoft Corporation All Rights Reserved Module Name: hw.cpp Abstract: Implementation of Base Audio Driver HW class. Base Audio Driver HW has an array for storing mixer and volume settings for the topology. --*/ #include "definitions.h" #include "hw.h" //============================================================================= // CBaseAudioDriverHW //============================================================================= //============================================================================= #pragma code_seg("PAGE") CBaseAudioDriverHW::CBaseAudioDriverHW() : m_ulMux(0), m_bDevSpecific(FALSE), m_iDevSpecific(0), m_uiDevSpecific(0) /*++ Routine Description: Constructor for BaseAudioDriverHW. Arguments: Return Value: void --*/ { PAGED_CODE(); MixerReset(); } // BaseAudioDriverHW #pragma code_seg() //============================================================================= BOOL CBaseAudioDriverHW::bGetDevSpecific() /*++ Routine Description: Gets the HW (!) Device Specific info Arguments: N/A Return Value: True or False (in this example). --*/ { return m_bDevSpecific; } // bGetDevSpecific //============================================================================= void CBaseAudioDriverHW::bSetDevSpecific ( _In_ BOOL bDevSpecific ) /*++ Routine Description: Sets the HW (!) Device Specific info Arguments: fDevSpecific - true or false for this example. Return Value: void --*/ { m_bDevSpecific = bDevSpecific; } // bSetDevSpecific //============================================================================= INT CBaseAudioDriverHW::iGetDevSpecific() /*++ Routine Description: Gets the HW (!) Device Specific info Arguments: N/A Return Value: int (in this example). --*/ { return m_iDevSpecific; } // iGetDevSpecific //============================================================================= void CBaseAudioDriverHW::iSetDevSpecific ( _In_ INT iDevSpecific ) /*++ Routine Description: Sets the HW (!) Device Specific info Arguments: fDevSpecific - true or false for this example. Return Value: void --*/ { m_iDevSpecific = iDevSpecific; } // iSetDevSpecific //============================================================================= UINT CBaseAudioDriverHW::uiGetDevSpecific() /*++ Routine Description: Gets the HW (!) Device Specific info Arguments: N/A Return Value: UINT (in this example). --*/ { return m_uiDevSpecific; } // uiGetDevSpecific //============================================================================= void CBaseAudioDriverHW::uiSetDevSpecific ( _In_ UINT uiDevSpecific ) /*++ Routine Description: Sets the HW (!) Device Specific info Arguments: uiDevSpecific - int for this example. Return Value: void --*/ { m_uiDevSpecific = uiDevSpecific; } // uiSetDevSpecific //============================================================================= BOOL CBaseAudioDriverHW::GetMixerMute ( _In_ ULONG ulNode, _In_ ULONG ulChannel ) /*++ Routine Description: Gets the HW (!) mute levels for Base Audio Driver Arguments: ulNode - topology node id ulChannel - which channel are we reading? Return Value: mute setting --*/ { UNREFERENCED_PARAMETER(ulChannel); if (ulNode < MAX_TOPOLOGY_NODES) { return m_MuteControls[ulNode]; } return 0; } // GetMixerMute //============================================================================= ULONG CBaseAudioDriverHW::GetMixerMux() /*++ Routine Description: Return the current mux selection Arguments: Return Value: ULONG --*/ { return m_ulMux; } // GetMixerMux //============================================================================= LONG CBaseAudioDriverHW::GetMixerVolume ( _In_ ULONG ulNode, _In_ ULONG ulChannel ) /*++ Routine Description: Gets the HW (!) volume for Base Audio Driver. Arguments: ulNode - topology node id ulChannel - which channel are we reading? Return Value: LONG - volume level --*/ { UNREFERENCED_PARAMETER(ulChannel); if (ulNode < MAX_TOPOLOGY_NODES) { return m_VolumeControls[ulNode]; } return 0; } // GetMixerVolume //============================================================================= LONG CBaseAudioDriverHW::GetMixerPeakMeter ( _In_ ULONG ulNode, _In_ ULONG ulChannel ) /*++ Routine Description: Gets the HW (!) peak meter for Base Audio Driver. Arguments: ulNode - topology node id ulChannel - which channel are we reading? Return Value: LONG - sample peak meter level --*/ { UNREFERENCED_PARAMETER(ulChannel); if (ulNode < MAX_TOPOLOGY_NODES) { return m_PeakMeterControls[ulNode]; } return 0; } // GetMixerVolume //============================================================================= #pragma code_seg("PAGE") void CBaseAudioDriverHW::MixerReset() /*++ Routine Description: Resets the mixer registers. Arguments: Return Value: void --*/ { PAGED_CODE(); RtlFillMemory(m_VolumeControls, sizeof(LONG) * MAX_TOPOLOGY_NODES, 0xFF); // Endpoints are not muted by default. RtlZeroMemory(m_MuteControls, sizeof(BOOL) * MAX_TOPOLOGY_NODES); for (ULONG i=0; i<MAX_TOPOLOGY_NODES; ++i) { m_PeakMeterControls[i] = PEAKMETER_SIGNED_MAXIMUM/2; } // BUGBUG change this depending on the topology m_ulMux = 2; } // MixerReset #pragma code_seg() //============================================================================= void CBaseAudioDriverHW::SetMixerMute ( _In_ ULONG ulNode, _In_ ULONG ulChannel, _In_ BOOL fMute ) /*++ Routine Description: Sets the HW (!) mute levels for Base Audio Driver Arguments: ulNode - topology node id ulChannel - which channel are we setting? fMute - mute flag Return Value: void --*/ { UNREFERENCED_PARAMETER(ulChannel); if (ulNode < MAX_TOPOLOGY_NODES) { m_MuteControls[ulNode] = fMute; } } // SetMixerMute //============================================================================= void CBaseAudioDriverHW::SetMixerMux ( _In_ ULONG ulNode ) /*++ Routine Description: Sets the HW (!) mux selection Arguments: ulNode - topology node id Return Value: void --*/ { m_ulMux = ulNode; } // SetMixMux //============================================================================= void CBaseAudioDriverHW::SetMixerVolume ( _In_ ULONG ulNode, _In_ ULONG ulChannel, _In_ LONG lVolume ) /*++ Routine Description: Sets the HW (!) volume for Base Audio Driver. Arguments: ulNode - topology node id ulChannel - which channel are we setting? lVolume - volume level Return Value: void --*/ { UNREFERENCED_PARAMETER(ulChannel); if (ulNode < MAX_TOPOLOGY_NODES) { m_VolumeControls[ulNode] = lVolume; } } // SetMixerVolume
7,368
2,402
//===--- SwiftRemoteMirror.cpp - C wrapper for Reflection API -------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "swift/SwiftRemoteMirror/Platform.h" #include "swift/SwiftRemoteMirror/SwiftRemoteMirror.h" #define SWIFT_CLASS_IS_SWIFT_MASK swift_reflection_classIsSwiftMask extern "C" { SWIFT_REMOTE_MIRROR_LINKAGE unsigned long long swift_reflection_classIsSwiftMask = 2; } #include "swift/Demangling/Demangler.h" #include "swift/Reflection/ReflectionContext.h" #include "swift/Reflection/TypeLowering.h" #include "swift/Remote/CMemoryReader.h" #include "swift/Runtime/Unreachable.h" #if defined(__APPLE__) && defined(__MACH__) #include <TargetConditionals.h> #endif using namespace swift; using namespace swift::reflection; using namespace swift::remote; using Runtime = External<RuntimeTarget<sizeof(uintptr_t)>>; using NativeReflectionContext = swift::reflection::ReflectionContext<Runtime>; struct SwiftReflectionContext { NativeReflectionContext *nativeContext; std::vector<std::function<void()>> freeFuncs; std::vector<std::tuple<swift_addr_t, swift_addr_t>> dataSegments; std::string lastString; SwiftReflectionContext(MemoryReaderImpl impl) { auto Reader = std::make_shared<CMemoryReader>(impl); nativeContext = new NativeReflectionContext(Reader); } ~SwiftReflectionContext() { delete nativeContext; for (auto f : freeFuncs) f(); } }; uint16_t swift_reflection_getSupportedMetadataVersion() { return SWIFT_REFLECTION_METADATA_VERSION; } template <uint8_t WordSize> static int minimalDataLayoutQueryFunction(void *ReaderContext, DataLayoutQueryType type, void *inBuffer, void *outBuffer) { // TODO: The following should be set based on the target. // This code sets it to match the platform this code was compiled for. #if defined(__APPLE__) && __APPLE__ auto applePlatform = true; #else auto applePlatform = false; #endif #if defined(__APPLE__) && __APPLE__ && ((defined(TARGET_OS_IOS) && TARGET_OS_IOS) || (defined(TARGET_OS_IOS) && TARGET_OS_WATCH) || (defined(TARGET_OS_TV) && TARGET_OS_TV)) auto iosDerivedPlatform = true; #else auto iosDerivedPlatform = false; #endif if (type == DLQ_GetPointerSize || type == DLQ_GetSizeSize) { auto result = static_cast<uint8_t *>(outBuffer); *result = WordSize; return 1; } if (type == DLQ_GetObjCReservedLowBits) { auto result = static_cast<uint8_t *>(outBuffer); if (applePlatform && !iosDerivedPlatform && WordSize == 8) { // Obj-C reserves low bit on 64-bit macOS only. // Other Apple platforms don't reserve this bit (even when // running on x86_64-based simulators). *result = 1; } else { *result = 0; } return 1; } if (type == DLQ_GetLeastValidPointerValue) { auto result = static_cast<uint64_t *>(outBuffer); if (applePlatform && WordSize == 8) { // Swift reserves the first 4GiB on all 64-bit Apple platforms *result = 0x100000000; } else { // Swift reserves the first 4KiB everywhere else *result = 0x1000; } return 1; } return 0; } // Caveat: This basically only works correctly if running on the same // host as the target. Otherwise, you'll need to use // swift_reflection_createReflectionContextWithDataLayout() below // with an appropriate data layout query function that understands // the target environment. SwiftReflectionContextRef swift_reflection_createReflectionContext(void *ReaderContext, uint8_t PointerSize, FreeBytesFunction Free, ReadBytesFunction ReadBytes, GetStringLengthFunction GetStringLength, GetSymbolAddressFunction GetSymbolAddress) { assert((PointerSize == 4 || PointerSize == 8) && "We only support 32-bit and 64-bit."); assert(PointerSize == sizeof(uintptr_t) && "We currently only support the pointer size this file was compiled with."); auto *DataLayout = PointerSize == 4 ? minimalDataLayoutQueryFunction<4> : minimalDataLayoutQueryFunction<8>; MemoryReaderImpl ReaderImpl { ReaderContext, DataLayout, Free, ReadBytes, GetStringLength, GetSymbolAddress }; return new SwiftReflectionContext(ReaderImpl); } SwiftReflectionContextRef swift_reflection_createReflectionContextWithDataLayout(void *ReaderContext, QueryDataLayoutFunction DataLayout, FreeBytesFunction Free, ReadBytesFunction ReadBytes, GetStringLengthFunction GetStringLength, GetSymbolAddressFunction GetSymbolAddress) { MemoryReaderImpl ReaderImpl { ReaderContext, DataLayout, Free, ReadBytes, GetStringLength, GetSymbolAddress }; return new SwiftReflectionContext(ReaderImpl); } void swift_reflection_destroyReflectionContext(SwiftReflectionContextRef ContextRef) { delete ContextRef; } template<typename Iterator> ReflectionSection<Iterator> sectionFromInfo(const swift_reflection_info_t &Info, const swift_reflection_section_pair_t &Section) { auto RemoteSectionStart = (uint64_t)(uintptr_t)Section.section.Begin - Info.LocalStartAddress + Info.RemoteStartAddress; auto Start = RemoteRef<void>(RemoteSectionStart, Section.section.Begin); return ReflectionSection<Iterator>(Start, (uintptr_t)Section.section.End - (uintptr_t)Section.section.Begin); } void swift_reflection_addReflectionInfo(SwiftReflectionContextRef ContextRef, swift_reflection_info_t Info) { auto Context = ContextRef->nativeContext; // The `offset` fields must be zero. if (Info.field.offset != 0 || Info.associated_types.offset != 0 || Info.builtin_types.offset != 0 || Info.capture.offset != 0 || Info.type_references.offset != 0 || Info.reflection_strings.offset != 0) { fprintf(stderr, "reserved field in swift_reflection_info_t is not zero\n"); abort(); } ReflectionInfo ContextInfo{ sectionFromInfo<FieldDescriptorIterator>(Info, Info.field), sectionFromInfo<AssociatedTypeIterator>(Info, Info.associated_types), sectionFromInfo<BuiltinTypeDescriptorIterator>(Info, Info.builtin_types), sectionFromInfo<CaptureDescriptorIterator>(Info, Info.capture), sectionFromInfo<const void *>(Info, Info.type_references), sectionFromInfo<const void *>(Info, Info.reflection_strings)}; Context->addReflectionInfo(ContextInfo); } int swift_reflection_addImage(SwiftReflectionContextRef ContextRef, swift_addr_t imageStart) { auto Context = ContextRef->nativeContext; return Context->addImage(RemoteAddress(imageStart)); } int swift_reflection_readIsaMask(SwiftReflectionContextRef ContextRef, uintptr_t *outIsaMask) { auto Context = ContextRef->nativeContext; auto isaMask = Context->readIsaMask(); if (isaMask) { *outIsaMask = *isaMask; return true; } *outIsaMask = 0; return false; } swift_typeref_t swift_reflection_typeRefForMetadata(SwiftReflectionContextRef ContextRef, uintptr_t Metadata) { auto Context = ContextRef->nativeContext; auto TR = Context->readTypeFromMetadata(Metadata); return reinterpret_cast<swift_typeref_t>(TR); } int swift_reflection_ownsObject(SwiftReflectionContextRef ContextRef, uintptr_t Object) { auto Context = ContextRef->nativeContext; return Context->ownsObject(RemoteAddress(Object)); } int swift_reflection_ownsAddress(SwiftReflectionContextRef ContextRef, uintptr_t Address) { auto Context = ContextRef->nativeContext; return Context->ownsAddress(RemoteAddress(Address)); } uintptr_t swift_reflection_metadataForObject(SwiftReflectionContextRef ContextRef, uintptr_t Object) { auto Context = ContextRef->nativeContext; auto MetadataAddress = Context->readMetadataFromInstance(Object); if (!MetadataAddress) return 0; return *MetadataAddress; } swift_typeref_t swift_reflection_typeRefForInstance(SwiftReflectionContextRef ContextRef, uintptr_t Object) { auto Context = ContextRef->nativeContext; auto MetadataAddress = Context->readMetadataFromInstance(Object); if (!MetadataAddress) return 0; auto TR = Context->readTypeFromMetadata(*MetadataAddress); return reinterpret_cast<swift_typeref_t>(TR); } swift_typeref_t swift_reflection_typeRefForMangledTypeName(SwiftReflectionContextRef ContextRef, const char *MangledTypeName, uint64_t Length) { auto Context = ContextRef->nativeContext; auto TR = Context->readTypeFromMangledName(MangledTypeName, Length); return reinterpret_cast<swift_typeref_t>(TR); } char * swift_reflection_copyDemangledNameForTypeRef( SwiftReflectionContextRef ContextRef, swift_typeref_t OpaqueTypeRef) { auto TR = reinterpret_cast<const TypeRef *>(OpaqueTypeRef); Demangle::Demangler Dem; auto Name = nodeToString(TR->getDemangling(Dem)); return strdup(Name.c_str()); } SWIFT_REMOTE_MIRROR_LINKAGE char * swift_reflection_copyDemangledNameForProtocolDescriptor( SwiftReflectionContextRef ContextRef, swift_reflection_ptr_t Proto) { auto Context = ContextRef->nativeContext; Demangle::Demangler Dem; auto Demangling = Context->readDemanglingForContextDescriptor(Proto, Dem); auto Name = nodeToString(Demangling); return strdup(Name.c_str()); } swift_typeref_t swift_reflection_genericArgumentOfTypeRef(swift_typeref_t OpaqueTypeRef, unsigned Index) { auto TR = reinterpret_cast<const TypeRef *>(OpaqueTypeRef); if (auto BG = dyn_cast<BoundGenericTypeRef>(TR)) { auto &Params = BG->getGenericParams(); assert(Index < Params.size()); return reinterpret_cast<swift_typeref_t>(Params[Index]); } return 0; } unsigned swift_reflection_genericArgumentCountOfTypeRef(swift_typeref_t OpaqueTypeRef) { auto TR = reinterpret_cast<const TypeRef *>(OpaqueTypeRef); if (auto BG = dyn_cast<BoundGenericTypeRef>(TR)) { auto &Params = BG->getGenericParams(); return Params.size(); } return 0; } swift_layout_kind_t getTypeInfoKind(const TypeInfo &TI) { switch (TI.getKind()) { case TypeInfoKind::Invalid: { return SWIFT_UNKNOWN; } case TypeInfoKind::Builtin: { auto &BuiltinTI = cast<BuiltinTypeInfo>(TI); if (BuiltinTI.getMangledTypeName() == "Bp") return SWIFT_RAW_POINTER; return SWIFT_BUILTIN; } case TypeInfoKind::Record: { auto &RecordTI = cast<RecordTypeInfo>(TI); switch (RecordTI.getRecordKind()) { case RecordKind::Invalid: return SWIFT_UNKNOWN; case RecordKind::Tuple: return SWIFT_TUPLE; case RecordKind::Struct: return SWIFT_STRUCT; case RecordKind::ThickFunction: return SWIFT_THICK_FUNCTION; case RecordKind::OpaqueExistential: return SWIFT_OPAQUE_EXISTENTIAL; case RecordKind::ClassExistential: return SWIFT_CLASS_EXISTENTIAL; case RecordKind::ErrorExistential: return SWIFT_ERROR_EXISTENTIAL; case RecordKind::ExistentialMetatype: return SWIFT_EXISTENTIAL_METATYPE; case RecordKind::ClassInstance: return SWIFT_CLASS_INSTANCE; case RecordKind::ClosureContext: return SWIFT_CLOSURE_CONTEXT; } } case TypeInfoKind::Enum: { auto &EnumTI = cast<EnumTypeInfo>(TI); switch (EnumTI.getEnumKind()) { case EnumKind::NoPayloadEnum: return SWIFT_NO_PAYLOAD_ENUM; case EnumKind::SinglePayloadEnum: return SWIFT_SINGLE_PAYLOAD_ENUM; case EnumKind::MultiPayloadEnum: return SWIFT_MULTI_PAYLOAD_ENUM; } } case TypeInfoKind::Reference: { auto &ReferenceTI = cast<ReferenceTypeInfo>(TI); switch (ReferenceTI.getReferenceKind()) { case ReferenceKind::Strong: return SWIFT_STRONG_REFERENCE; #define REF_STORAGE(Name, name, NAME) \ case ReferenceKind::Name: return SWIFT_##NAME##_REFERENCE; #include "swift/AST/ReferenceStorage.def" } } } swift_runtime_unreachable("Unhandled TypeInfoKind in switch"); } static swift_typeinfo_t convertTypeInfo(const TypeInfo *TI) { if (TI == nullptr) { return { SWIFT_UNKNOWN, 0, 0, 0, 0 }; } unsigned NumFields = 0; if (auto *RecordTI = dyn_cast<EnumTypeInfo>(TI)) { NumFields = RecordTI->getNumCases(); } else if (auto *RecordTI = dyn_cast<RecordTypeInfo>(TI)) { NumFields = RecordTI->getNumFields(); } return { getTypeInfoKind(*TI), TI->getSize(), TI->getAlignment(), TI->getStride(), NumFields }; } static swift_childinfo_t convertChild(const TypeInfo *TI, unsigned Index) { const FieldInfo *FieldInfo; if (auto *EnumTI = dyn_cast<EnumTypeInfo>(TI)) { FieldInfo = &(EnumTI->getCases()[Index]); } else if (auto *RecordTI = dyn_cast<RecordTypeInfo>(TI)) { FieldInfo = &(RecordTI->getFields()[Index]); } else { assert(false && "convertChild(TI): TI must be record or enum typeinfo"); } return { FieldInfo->Name.c_str(), FieldInfo->Offset, getTypeInfoKind(FieldInfo->TI), reinterpret_cast<swift_typeref_t>(FieldInfo->TR), }; } static const char *returnableCString(SwiftReflectionContextRef ContextRef, llvm::Optional<std::string> String) { if (String) { ContextRef->lastString = *String; return ContextRef->lastString.c_str(); } return nullptr; } swift_typeinfo_t swift_reflection_infoForTypeRef(SwiftReflectionContextRef ContextRef, swift_typeref_t OpaqueTypeRef) { auto Context = ContextRef->nativeContext; auto TR = reinterpret_cast<const TypeRef *>(OpaqueTypeRef); auto TI = Context->getTypeInfo(TR); return convertTypeInfo(TI); } swift_childinfo_t swift_reflection_childOfTypeRef(SwiftReflectionContextRef ContextRef, swift_typeref_t OpaqueTypeRef, unsigned Index) { auto Context = ContextRef->nativeContext; auto TR = reinterpret_cast<const TypeRef *>(OpaqueTypeRef); auto *TI = Context->getTypeInfo(TR); return convertChild(TI, Index); } swift_typeinfo_t swift_reflection_infoForMetadata(SwiftReflectionContextRef ContextRef, uintptr_t Metadata) { auto Context = ContextRef->nativeContext; auto *TI = Context->getMetadataTypeInfo(Metadata); return convertTypeInfo(TI); } swift_childinfo_t swift_reflection_childOfMetadata(SwiftReflectionContextRef ContextRef, uintptr_t Metadata, unsigned Index) { auto Context = ContextRef->nativeContext; auto *TI = Context->getMetadataTypeInfo(Metadata); return convertChild(TI, Index); } swift_typeinfo_t swift_reflection_infoForInstance(SwiftReflectionContextRef ContextRef, uintptr_t Object) { auto Context = ContextRef->nativeContext; auto *TI = Context->getInstanceTypeInfo(Object); return convertTypeInfo(TI); } swift_childinfo_t swift_reflection_childOfInstance(SwiftReflectionContextRef ContextRef, uintptr_t Object, unsigned Index) { auto Context = ContextRef->nativeContext; auto *TI = Context->getInstanceTypeInfo(Object); return convertChild(TI, Index); } int swift_reflection_projectExistential(SwiftReflectionContextRef ContextRef, swift_addr_t ExistentialAddress, swift_typeref_t ExistentialTypeRef, swift_typeref_t *InstanceTypeRef, swift_addr_t *StartOfInstanceData) { auto Context = ContextRef->nativeContext; auto ExistentialTR = reinterpret_cast<const TypeRef *>(ExistentialTypeRef); auto RemoteExistentialAddress = RemoteAddress(ExistentialAddress); const TypeRef *InstanceTR = nullptr; RemoteAddress RemoteStartOfInstanceData(nullptr); auto Success = Context->projectExistential(RemoteExistentialAddress, ExistentialTR, &InstanceTR, &RemoteStartOfInstanceData); if (Success) { *InstanceTypeRef = reinterpret_cast<swift_typeref_t>(InstanceTR); *StartOfInstanceData = RemoteStartOfInstanceData.getAddressData(); } return Success; } int swift_reflection_projectEnumValue(SwiftReflectionContextRef ContextRef, swift_addr_t EnumAddress, swift_typeref_t EnumTypeRef, int *CaseIndex) { auto Context = ContextRef->nativeContext; auto EnumTR = reinterpret_cast<const TypeRef *>(EnumTypeRef); auto RemoteEnumAddress = RemoteAddress(EnumAddress); if (!Context->projectEnumValue(RemoteEnumAddress, EnumTR, CaseIndex)) { return false; } auto TI = Context->getTypeInfo(EnumTR); auto *RecordTI = dyn_cast<EnumTypeInfo>(TI); assert(RecordTI != nullptr); if (static_cast<size_t>(*CaseIndex) >= RecordTI->getNumCases()) { return false; } return true; } void swift_reflection_dumpTypeRef(swift_typeref_t OpaqueTypeRef) { auto TR = reinterpret_cast<const TypeRef *>(OpaqueTypeRef); if (TR == nullptr) { fprintf(stdout, "<null type reference>\n"); } else { TR->dump(stdout); } } void swift_reflection_dumpInfoForTypeRef(SwiftReflectionContextRef ContextRef, swift_typeref_t OpaqueTypeRef) { auto Context = ContextRef->nativeContext; auto TR = reinterpret_cast<const TypeRef *>(OpaqueTypeRef); auto TI = Context->getTypeInfo(TR); if (TI == nullptr) { fprintf(stdout, "<null type info>\n"); } else { TI->dump(stdout); Demangle::Demangler Dem; std::string MangledName = mangleNode(TR->getDemangling(Dem)); fprintf(stdout, "Mangled name: %s%s\n", MANGLING_PREFIX_STR, MangledName.c_str()); char *DemangledName = swift_reflection_copyDemangledNameForTypeRef(ContextRef, OpaqueTypeRef); fprintf(stdout, "Demangled name: %s\n", DemangledName); free(DemangledName); #ifndef NDEBUG assert(mangleNode(TR->getDemangling(Dem)) == MangledName && "round-trip diff"); #endif } } void swift_reflection_dumpInfoForMetadata(SwiftReflectionContextRef ContextRef, uintptr_t Metadata) { auto Context = ContextRef->nativeContext; auto TI = Context->getMetadataTypeInfo(Metadata); if (TI == nullptr) { fprintf(stdout, "<null type info>\n"); } else { TI->dump(stdout); } } void swift_reflection_dumpInfoForInstance(SwiftReflectionContextRef ContextRef, uintptr_t Object) { auto Context = ContextRef->nativeContext; auto TI = Context->getInstanceTypeInfo(Object); if (TI == nullptr) { fprintf(stdout, "%s", "<null type info>\n"); } else { TI->dump(stdout); } } size_t swift_reflection_demangle(const char *MangledName, size_t Length, char *OutDemangledName, size_t MaxLength) { if (MangledName == nullptr || Length == 0) return 0; std::string Mangled(MangledName, Length); auto Demangled = Demangle::demangleTypeAsString(Mangled); strncpy(OutDemangledName, Demangled.c_str(), MaxLength); return Demangled.size(); } const char *swift_reflection_iterateConformanceCache( SwiftReflectionContextRef ContextRef, void (*Call)(swift_reflection_ptr_t Type, swift_reflection_ptr_t Proto, void *ContextPtr), void *ContextPtr) { auto Context = ContextRef->nativeContext; auto Error = Context->iterateConformances([&](auto Type, auto Proto) { Call(Type, Proto, ContextPtr); }); return returnableCString(ContextRef, Error); } const char *swift_reflection_iterateMetadataAllocations( SwiftReflectionContextRef ContextRef, void (*Call)(swift_metadata_allocation_t Allocation, void *ContextPtr), void *ContextPtr) { auto Context = ContextRef->nativeContext; auto Error = Context->iterateMetadataAllocations([&](auto Allocation) { swift_metadata_allocation CAllocation; CAllocation.Tag = Allocation.Tag; CAllocation.Ptr = Allocation.Ptr; CAllocation.Size = Allocation.Size; Call(CAllocation, ContextPtr); }); return returnableCString(ContextRef, Error); } swift_reflection_ptr_t swift_reflection_allocationMetadataPointer( SwiftReflectionContextRef ContextRef, swift_metadata_allocation_t Allocation) { auto Context = ContextRef->nativeContext; MetadataAllocation<Runtime> NativeAllocation; NativeAllocation.Tag = Allocation.Tag; NativeAllocation.Ptr = Allocation.Ptr; NativeAllocation.Size = Allocation.Size; return Context->allocationMetadataPointer(NativeAllocation); } const char *swift_reflection_metadataAllocationTagName( SwiftReflectionContextRef ContextRef, swift_metadata_allocation_tag_t Tag) { auto Context = ContextRef->nativeContext; auto Result = Context->metadataAllocationTagName(Tag); return returnableCString(ContextRef, Result); } const char *swift_reflection_iterateMetadataAllocationBacktraces( SwiftReflectionContextRef ContextRef, swift_metadataAllocationBacktraceIterator Call, void *ContextPtr) { auto Context = ContextRef->nativeContext; auto Error = Context->iterateMetadataAllocationBacktraces( [&](auto AllocationPtr, auto Count, auto Ptrs) { // Ptrs is an array of StoredPointer, but the callback expects an array // of swift_reflection_ptr_t. Those may are not always the same type. // (For example, swift_reflection_ptr_t can be 64-bit on 32-bit systems, // while StoredPointer is always the pointer size of the target system.) // Convert the array to an array of swift_reflection_ptr_t. std::vector<swift_reflection_ptr_t> ConvertedPtrs{&Ptrs[0], &Ptrs[Count]}; Call(AllocationPtr, Count, ConvertedPtrs.data(), ContextPtr); }); return returnableCString(ContextRef, Error); }
23,023
7,037
// -*- C++ -*- // Copyright 2006-2007 Deutsches Forschungszentrum fuer Kuenstliche Intelligenz // or its licensors, as applicable. // // You may not use this file except under the terms of the accompanying license. // // Licensed under the Apache License, Version 2.0 (the "License"); you // may not use this file except in compliance with the License. You may // obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Project: // File: // Purpose: // Responsible: tmb // Reviewer: // Primary Repository: // Web Sites: www.iupr.org, www.dfki.de, www.ocropus.org #define __warn_unused_result__ __far__ #include <cctype> #include <sys/types.h> #include <sys/stat.h> #include <glob.h> #include <unistd.h> #include "colib/colib.h" #include "iulib/iulib.h" #include "ocropus.h" #include "glinerec.h" #include "bookstore.h" namespace ocropus { void hocr_dump_preamble(FILE *output) { fprintf(output, "<!DOCTYPE html\n"); fprintf(output, " PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\n"); fprintf(output, " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"); } void hocr_dump_head(FILE *output) { fprintf(output, "<head>\n"); fprintf(output, "<meta name=\"ocr-capabilities\" content=\"ocr_line ocr_page\" />\n"); fprintf(output, "<meta name=\"ocr-langs\" content=\"en\" />\n"); fprintf(output, "<meta name=\"ocr-scripts\" content=\"Latn\" />\n"); fprintf(output, "<meta name=\"ocr-microformats\" content=\"\" />\n"); fprintf(output, "<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" />"); fprintf(output, "<title>OCR Output</title>\n"); fprintf(output, "</head>\n"); } void hocr_dump_line(FILE *output,IBookStore &bookstore, RegionExtractor &r, int page, int line, int h) { fprintf(output, "<span class=\"ocr_line\""); if(line > 0 && line < r.length()) { fprintf(output, " title=\"bbox %d %d %d %d\"", r.x0(line), h - 1 - r.y0(line), r.x1(line), h - 1 - r.y1(line)); } fprintf(output, ">\n"); ustrg s; if (file_exists(bookstore.path(page,line,0,"txt"))) { fgetsUTF8(s, stdio(bookstore.path(page,line,0,"txt"), "r")); fwriteUTF8(s, output); } fprintf(output, "</span>"); } void hocr_dump_page(FILE *output, IBookStore & bookstore, int page) { strg pattern; intarray page_seg; //bookstore.getPageSegmentation(page_seg, page); if (!bookstore.getPage(page_seg, page, "pseg")) { if(page>0) debugf("warn","%d: page not found\n",page); return; } int h = page_seg.dim(1); RegionExtractor regions; regions.setPageLines(page_seg); rectarray bboxes; fprintf(output, "<div class=\"ocr_page\">\n"); int nlines = bookstore.linesOnPage(page); for(int i=0;i<nlines;i++) { int line = bookstore.getLineId(page,i); hocr_dump_line(output, bookstore, regions, page, line, h); } fprintf(output, "</div>\n"); } int main_buildhtml(int argc,char **argv) { param_string cbookstore("bookstore","SmartBookStore","storage abstraction for book"); if(argc!=2) throw "usage: ... dir"; autodel<IBookStore> bookstore; make_component(bookstore,cbookstore); bookstore->setPrefix(argv[1]); FILE *output = stdout; hocr_dump_preamble(output); fprintf(output, "<html>\n"); hocr_dump_head(output); fprintf(output, "<body>\n"); int npages = bookstore->numberOfPages(); for(int page=0;page<npages;page++) { hocr_dump_page(output, *bookstore, page); } fprintf(output, "</body>\n"); fprintf(output, "</html>\n"); return 0; } int main_cleanhtml(int argc,char **argv) { throw Unimplemented(); } }
4,401
1,483
#include "core.h" #include "eldritchmusic.h" #include "isoundinstance.h" #include "eldritchframework.h" EldritchMusic::EldritchMusic() : m_MusicInstance( NULL ) { IAudioSystem* const pAudioSystem = EldritchFramework::GetInstance()->GetAudioSystem(); ASSERT( pAudioSystem ); SInstanceDeleteCallback Callback; Callback.m_Callback = InstanceDeleteCallback; Callback.m_Void = this; pAudioSystem->RegisterInstanceDeleteCallback( Callback ); } EldritchMusic::~EldritchMusic() { IAudioSystem* const pAudioSystem = EldritchFramework::GetInstance()->GetAudioSystem(); ASSERT( pAudioSystem ); if( m_MusicInstance ) { pAudioSystem->RemoveSoundInstance( m_MusicInstance ); } SInstanceDeleteCallback Callback; Callback.m_Callback = InstanceDeleteCallback; Callback.m_Void = this; pAudioSystem->UnregisterInstanceDeleteCallback( Callback ); } void EldritchMusic::PlayMusic( const SimpleString& MusicSoundDef ) { StopMusic(); if( MusicSoundDef == "" ) { return; } IAudioSystem* const pAudioSystem = EldritchFramework::GetInstance()->GetAudioSystem(); ASSERT( pAudioSystem ); m_MusicInstance = pAudioSystem->CreateSoundInstance( MusicSoundDef ); ASSERT( m_MusicInstance ); m_MusicInstance->Tick(); m_MusicInstance->Play(); } void EldritchMusic::StopMusic() { if( m_MusicInstance ) { m_MusicInstance->Stop(); } } /*static*/ void EldritchMusic::InstanceDeleteCallback( void* pVoid, ISoundInstance* pInstance ) { EldritchMusic* pMusic = static_cast<EldritchMusic*>( pVoid ); ASSERT( pMusic ); pMusic->OnInstanceDeleted( pInstance ); } void EldritchMusic::OnInstanceDeleted( ISoundInstance* const pInstance ) { if( pInstance == m_MusicInstance ) { m_MusicInstance = NULL; } }
1,713
599
/* * SoX native format demuxer * Copyright (c) 2009 Daniel Verkamp <daniel@drv.nu> * * Based on libSoX sox-fmt.c * Copyright (c) 2008 robs@users.sourceforge.net * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * SoX native format demuxer * @author Daniel Verkamp * @see http://wiki.multimedia.cx/index.php?title=SoX_native_intermediate_format */ #include "XMFFmpeg/libavutil/intreadwrite.h" #include "XMFFmpeg/libavutil/intfloat.h" #include "XMFFmpeg/libavutil/dict.h" #include "internal.h" #include "pcm.h" #include "sox.h" static int sox_probe(AVProbeData *p) { if (AV_RL32(p->buf) == SOX_TAG || AV_RB32(p->buf) == SOX_TAG) return AVPROBE_SCORE_MAX; return 0; } static int sox_read_header(AVFormatContext *s, AVFormatParameters *ap) { AVIOContext *pb = s->pb; unsigned header_size, comment_size; double sample_rate, sample_rate_frac; AVStream *st; st = avformat_new_stream(s, NULL); if (!st) return AVERROR(ENOMEM); st->codec->codec_type = AVMEDIA_TYPE_AUDIO; if (avio_rl32(pb) == SOX_TAG) { st->codec->codec_id = CODEC_ID_PCM_S32LE; header_size = avio_rl32(pb); avio_skip(pb, 8); /* sample count */ sample_rate = av_int2double(avio_rl64(pb)); st->codec->channels = avio_rl32(pb); comment_size = avio_rl32(pb); } else { st->codec->codec_id = CODEC_ID_PCM_S32BE; header_size = avio_rb32(pb); avio_skip(pb, 8); /* sample count */ sample_rate = av_int2double(avio_rb64(pb)); st->codec->channels = avio_rb32(pb); comment_size = avio_rb32(pb); } if (comment_size > 0xFFFFFFFFU - SOX_FIXED_HDR - 4U) { av_log(s, AV_LOG_ERROR, "invalid comment size (%u)\n", comment_size); return -1; } if (sample_rate <= 0 || sample_rate > INT_MAX) { av_log(s, AV_LOG_ERROR, "invalid sample rate (%f)\n", sample_rate); return -1; } sample_rate_frac = sample_rate - floor(sample_rate); if (sample_rate_frac) av_log(s, AV_LOG_WARNING, "truncating fractional part of sample rate (%f)\n", sample_rate_frac); if ((header_size + 4) & 7 || header_size < SOX_FIXED_HDR + comment_size || st->codec->channels > 65535) /* Reserve top 16 bits */ { av_log(s, AV_LOG_ERROR, "invalid header\n"); return -1; } if (comment_size && comment_size < UINT_MAX) { char *comment = (char *)av_malloc(comment_size+1); if(!comment) return AVERROR(ENOMEM); if (avio_read(pb, (unsigned char *)comment, comment_size) != comment_size) { av_freep(&comment); return AVERROR(EIO); } comment[comment_size] = 0; av_dict_set(&s->metadata, "comment", comment, AV_DICT_DONT_STRDUP_VAL); } avio_skip(pb, header_size - SOX_FIXED_HDR - comment_size); st->codec->sample_rate = sample_rate; st->codec->bits_per_coded_sample = 32; st->codec->bit_rate = st->codec->sample_rate * st->codec->bits_per_coded_sample * st->codec->channels; st->codec->block_align = st->codec->bits_per_coded_sample * st->codec->channels / 8; avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate); return 0; } #define SOX_SAMPLES 1024 static int sox_read_packet(AVFormatContext *s, AVPacket *pkt) { int ret, size; if (url_feof(s->pb)) return AVERROR_EOF; size = SOX_SAMPLES*s->streams[0]->codec->block_align; ret = av_get_packet(s->pb, pkt, size); if (ret < 0) return AVERROR(EIO); pkt->stream_index = 0; pkt->size = ret; return 0; } AVInputFormat ff_sox_demuxer = { /*.name = */ "sox", /*.long_name = */ NULL_IF_CONFIG_SMALL("SoX native format"), /*.priv_data_size = */ 0, /*.read_probe = */ sox_probe, /*.read_header = */ sox_read_header, /*.read_packet = */ sox_read_packet, /*.read_close = */ 0, /*.read_seek = */ pcm_read_seek, };
5,004
1,860
#ifndef SIMPLE_WEB_CLIENT_WS_HPP #define SIMPLE_WEB_CLIENT_WS_HPP #include "asio_compatibility.hpp" #include "crypto.hpp" #include "mutex.hpp" #include "utility.hpp" #include <array> #include <atomic> #include <iostream> #include <limits> #include <list> #include <random> namespace SimpleWeb { template <class socket_type> class SocketClient; template <class socket_type> class SocketClientBase { public: class InMessage : public std::istream { friend class SocketClientBase<socket_type>; friend class SocketClient<socket_type>; friend class Connection; public: unsigned char fin_rsv_opcode; std::size_t size() noexcept { return length; } /// Convenience function to return std::string. std::string string() noexcept { return std::string(asio::buffers_begin(streambuf.data()), asio::buffers_end(streambuf.data())); } private: InMessage() noexcept : std::istream(&streambuf), length(0) {} InMessage(unsigned char fin_rsv_opcode, std::size_t length) noexcept : std::istream(&streambuf), fin_rsv_opcode(fin_rsv_opcode), length(length) {} std::size_t length; asio::streambuf streambuf; }; /// The buffer is consumed during send operations. class OutMessage : public std::iostream { friend class SocketClientBase<socket_type>; asio::streambuf streambuf; public: OutMessage() noexcept : std::iostream(&streambuf) {} OutMessage(std::size_t capacity) noexcept : std::iostream(&streambuf) { streambuf.prepare(capacity); } /// Returns the size of the buffer std::size_t size() const noexcept { return streambuf.size(); } }; class Connection : public std::enable_shared_from_this<Connection> { friend class SocketClientBase<socket_type>; friend class SocketClient<socket_type>; public: std::string http_version, status_code; CaseInsensitiveMultimap header; private: template <typename... Args> Connection(std::shared_ptr<ScopeRunner> handler_runner_, long timeout_idle, Args &&...args) noexcept : handler_runner(std::move(handler_runner_)), socket(new socket_type(std::forward<Args>(args)...)), timeout_idle(timeout_idle), close_sent(false) {} std::shared_ptr<ScopeRunner> handler_runner; std::unique_ptr<socket_type> socket; // Socket must be unique_ptr since asio::ssl::stream<asio::ip::tcp::socket> is not movable std::shared_ptr<InMessage> in_message; std::shared_ptr<InMessage> fragmented_in_message; long timeout_idle; Mutex timer_mutex; std::unique_ptr<asio::steady_timer> timer GUARDED_BY(timer_mutex); std::atomic<bool> close_sent; asio::ip::tcp::endpoint endpoint; // The endpoint is read in SocketClient::upgrade and must be stored so that it can be read reliably in all handlers, including on_error void set_timeout(long seconds = -1) noexcept { bool use_timeout_idle = false; if(seconds == -1) { use_timeout_idle = true; seconds = timeout_idle; } LockGuard lock(timer_mutex); if(seconds == 0) { timer = nullptr; return; } timer = make_steady_timer(*socket, std::chrono::seconds(seconds)); std::weak_ptr<Connection> connection_weak(this->shared_from_this()); // To avoid keeping Connection instance alive longer than needed timer->async_wait([connection_weak, use_timeout_idle](const error_code &ec) { if(!ec) { if(auto connection = connection_weak.lock()) { if(use_timeout_idle) { if(connection->close_sent) connection->close(); else connection->send_close(1000, "idle timeout"); // 1000=normal closure } else connection->close(); } } }); } void cancel_timeout() noexcept { LockGuard lock(timer_mutex); if(timer) { try { timer->cancel(); } catch(...) { } } } class OutData { public: OutData(std::shared_ptr<OutMessage> out_message_, std::function<void(const error_code)> &&callback_) noexcept : out_message(std::move(out_message_)), callback(std::move(callback_)) {} std::shared_ptr<OutMessage> out_message; std::function<void(const error_code)> callback; }; Mutex send_queue_mutex; std::list<OutData> send_queue GUARDED_BY(send_queue_mutex); void send_from_queue() REQUIRES(send_queue_mutex) { auto self = this->shared_from_this(); set_timeout(); asio::async_write(*self->socket, send_queue.begin()->out_message->streambuf, [self](const error_code &ec, std::size_t /*bytes_transferred*/) { self->set_timeout(); // Set timeout for next send auto lock = self->handler_runner->continue_lock(); if(!lock) return; { LockGuard lock(self->send_queue_mutex); if(!ec) { auto it = self->send_queue.begin(); auto callback = std::move(it->callback); self->send_queue.erase(it); if(self->send_queue.size() > 0) self->send_from_queue(); lock.unlock(); if(callback) callback(ec); } else { // All handlers in the queue is called with ec: std::vector<std::function<void(const error_code &)>> callbacks; for(auto &out_data : self->send_queue) { if(out_data.callback) callbacks.emplace_back(std::move(out_data.callback)); } self->send_queue.clear(); lock.unlock(); for(auto &callback : callbacks) callback(ec); } } }); } public: /// fin_rsv_opcode: 129=one fragment, text, 130=one fragment, binary, 136=close connection. /// See http://tools.ietf.org/html/rfc6455#section-5.2 for more information. void send(const std::shared_ptr<OutMessage> &out_message, std::function<void(const error_code &)> callback = nullptr, unsigned char fin_rsv_opcode = 129) { // Create mask std::array<unsigned char, 4> mask; std::uniform_int_distribution<unsigned short> dist(0, 255); std::random_device rd; for(std::size_t c = 0; c < 4; c++) mask[c] = static_cast<unsigned char>(dist(rd)); std::size_t length = out_message->size(); std::size_t max_additional_bytes = 14; // ws protocol adds at most 14 bytes auto out_header_and_message = std::make_shared<OutMessage>(length + max_additional_bytes); out_header_and_message->put(static_cast<char>(fin_rsv_opcode)); // Masked (first length byte>=128) if(length >= 126) { std::size_t num_bytes; if(length > 0xffff) { num_bytes = 8; out_header_and_message->put(static_cast<char>(127 + 128)); } else { num_bytes = 2; out_header_and_message->put(static_cast<char>(126 + 128)); } for(std::size_t c = num_bytes - 1; c != static_cast<std::size_t>(-1); c--) out_header_and_message->put((static_cast<unsigned long long>(length) >> (8 * c)) % 256); } else out_header_and_message->put(static_cast<char>(length + 128)); for(std::size_t c = 0; c < 4; c++) out_header_and_message->put(static_cast<char>(mask[c])); for(std::size_t c = 0; c < length; c++) out_header_and_message->put(out_message->get() ^ mask[c % 4]); LockGuard lock(send_queue_mutex); send_queue.emplace_back(std::move(out_header_and_message), std::move(callback)); if(send_queue.size() == 1) send_from_queue(); } /// Convenience function for sending a string. /// fin_rsv_opcode: 129=one fragment, text, 130=one fragment, binary, 136=close connection. /// See http://tools.ietf.org/html/rfc6455#section-5.2 for more information. void send(string_view out_message_str, std::function<void(const error_code &)> callback = nullptr, unsigned char fin_rsv_opcode = 129) { auto out_message = std::make_shared<OutMessage>(); out_message->write(out_message_str.data(), static_cast<std::streamsize>(out_message_str.size())); send(out_message, std::move(callback), fin_rsv_opcode); } void send_close(int status, const std::string &reason = "", std::function<void(const error_code &)> callback = nullptr) { // Send close only once (in case close is initiated by client) if(close_sent) return; close_sent = true; auto out_message = std::make_shared<OutMessage>(); out_message->put(status >> 8); out_message->put(status % 256); *out_message << reason; // fin_rsv_opcode=136: message close send(out_message, std::move(callback), 136); } /// Force close connection. Use `send_close()` instead for standard compliant connection close. void close() noexcept { error_code ec; socket->lowest_layer().shutdown(asio::ip::tcp::socket::shutdown_both, ec); socket->lowest_layer().cancel(ec); } const asio::ip::tcp::endpoint &remote_endpoint() const noexcept { return endpoint; } }; class Config { friend class SocketClientBase<socket_type>; private: Config() noexcept {} public: /// Timeout on request handling. Defaults to no timeout. long timeout_request = 0; /// Idle timeout. Defaults to no timeout. long timeout_idle = 0; /// Maximum size of incoming messages. Defaults to architecture maximum. /// Exceeding this limit will result in a message_size error code and the connection will be closed. std::size_t max_message_size = (std::numeric_limits<std::size_t>::max)(); /// Additional header fields to send when performing WebSocket upgrade. /// Use this variable to for instance set Sec-WebSocket-Protocol. CaseInsensitiveMultimap header; /// Set proxy server (server:port) std::string proxy_server; /// Set proxy authorization (username:password) std::string proxy_auth; }; /// Set before calling start(). Config config; std::function<void(std::shared_ptr<Connection>)> on_open; std::function<void(std::shared_ptr<Connection>, std::shared_ptr<InMessage>)> on_message; std::function<void(std::shared_ptr<Connection>, int, const std::string &)> on_close; std::function<void(std::shared_ptr<Connection>, const error_code &)> on_error; std::function<void(std::shared_ptr<Connection>)> on_ping; std::function<void(std::shared_ptr<Connection>)> on_pong; /// Start the client. /// If io_service is not set, an internal io_service is created instead. /// The callback parameter is called while the client is connecting to the server. void start(std::function<void()> callback = nullptr) { { std::lock_guard<std::mutex> lock(start_stop_mutex); if(!io_service) { io_service = std::make_shared<io_context>(); internal_io_service = true; } if(io_service->stopped()) restart(*io_service); connect(); if(callback) post(*io_service, std::move(callback)); } if(internal_io_service) io_service->run(); } /// Stop client, and close current connection void stop() noexcept { std::lock_guard<std::mutex> lock(start_stop_mutex); { LockGuard lock(connection_mutex); if(connection) connection->close(); } if(internal_io_service) io_service->stop(); } virtual ~SocketClientBase() noexcept { handler_runner->stop(); stop(); } /// If you have your own io_context, store its pointer here before running start(). std::shared_ptr<io_context> io_service; protected: std::mutex start_stop_mutex; bool internal_io_service = false; std::string host; unsigned short port; unsigned short default_port; std::string path; Mutex connection_mutex; std::shared_ptr<Connection> connection GUARDED_BY(connection_mutex); std::shared_ptr<ScopeRunner> handler_runner; SocketClientBase(const std::string &host_port_path, unsigned short default_port) noexcept : default_port(default_port), handler_runner(new ScopeRunner()) { auto host_port_end = host_port_path.find('/'); auto host_port = parse_host_port(host_port_path.substr(0, host_port_end), default_port); host = std::move(host_port.first); port = host_port.second; if(host_port_end != std::string::npos) path = host_port_path.substr(host_port_end); else path = "/"; } std::pair<std::string, unsigned short> parse_host_port(const std::string &host_port, unsigned short default_port) const noexcept { std::string host, port; host.reserve(host_port.size()); bool parse_port = false; int square_count = 0; // To parse IPv6 addresses for(auto chr : host_port) { if(chr == '[') ++square_count; else if(chr == ']') --square_count; else if(square_count == 0 && chr == ':') parse_port = true; else if(!parse_port) host += chr; else port += chr; } if(port.empty()) return {std::move(host), default_port}; else { try { return {std::move(host), static_cast<unsigned short>(std::stoul(port))}; } catch(...) { return {std::move(host), default_port}; } } } virtual void connect() = 0; void upgrade(const std::shared_ptr<Connection> &connection) { auto corrected_path = path; if(!config.proxy_server.empty() && std::is_same<socket_type, asio::ip::tcp::socket>::value) corrected_path = "http://" + host + ':' + std::to_string(port) + corrected_path; auto streambuf = std::make_shared<asio::streambuf>(); std::ostream ostream(streambuf.get()); ostream << "GET " << corrected_path << " HTTP/1.1\r\n"; ostream << "Host: " << host; if(port != default_port) ostream << ':' << std::to_string(port); ostream << "\r\n"; ostream << "Upgrade: websocket\r\n"; ostream << "Connection: Upgrade\r\n"; // Make random 16-byte nonce std::string nonce; nonce.reserve(16); std::uniform_int_distribution<unsigned short> dist(0, 255); std::random_device rd; for(std::size_t c = 0; c < 16; c++) nonce += static_cast<char>(dist(rd)); auto nonce_base64 = std::make_shared<std::string>(Crypto::Base64::encode(nonce)); ostream << "Sec-WebSocket-Key: " << *nonce_base64 << "\r\n"; ostream << "Sec-WebSocket-Version: 13\r\n"; for(auto &header_field : config.header) ostream << header_field.first << ": " << header_field.second << "\r\n"; ostream << "\r\n"; try { connection->endpoint = connection->socket->lowest_layer().remote_endpoint(); } catch(...) { } connection->in_message = std::shared_ptr<InMessage>(new InMessage()); connection->set_timeout(config.timeout_request); asio::async_write(*connection->socket, *streambuf, [this, connection, streambuf, nonce_base64](const error_code &ec, std::size_t /*bytes_transferred*/) { connection->cancel_timeout(); auto lock = connection->handler_runner->continue_lock(); if(!lock) return; if(!ec) { connection->set_timeout(this->config.timeout_request); asio::async_read_until(*connection->socket, connection->in_message->streambuf, "\r\n\r\n", [this, connection, nonce_base64](const error_code &ec, std::size_t bytes_transferred) { connection->cancel_timeout(); auto lock = connection->handler_runner->continue_lock(); if(!lock) return; if(!ec) { // connection->in_message->streambuf.size() is not necessarily the same as bytes_transferred, from Boost-docs: // "After a successful async_read_until operation, the streambuf may contain additional data beyond the delimiter" // The chosen solution is to extract lines from the stream directly when parsing the header. What is left of the // streambuf (maybe some bytes of a message) is appended to in the next async_read-function std::size_t num_additional_bytes = connection->in_message->streambuf.size() - bytes_transferred; if(!ResponseMessage::parse(*connection->in_message, connection->http_version, connection->status_code, connection->header)) { this->connection_error(connection, make_error_code::make_error_code(errc::protocol_error)); return; } if(connection->status_code.compare(0, 4, "101 ") != 0) { this->connection_error(connection, make_error_code::make_error_code(errc::permission_denied)); return; } auto header_it = connection->header.find("Sec-WebSocket-Accept"); static auto ws_magic_string = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; if(header_it != connection->header.end() && Crypto::Base64::decode(header_it->second) == Crypto::sha1(*nonce_base64 + ws_magic_string)) { this->connection_open(connection); read_message(connection, num_additional_bytes); } else this->connection_error(connection, make_error_code::make_error_code(errc::protocol_error)); } else this->connection_error(connection, ec); }); } else this->connection_error(connection, ec); }); } void read_message(const std::shared_ptr<Connection> &connection, std::size_t num_additional_bytes) { connection->set_timeout(); asio::async_read(*connection->socket, connection->in_message->streambuf, asio::transfer_exactly(num_additional_bytes > 2 ? 0 : 2 - num_additional_bytes), [this, connection, num_additional_bytes](const error_code &ec, std::size_t bytes_transferred) { connection->cancel_timeout(); auto lock = connection->handler_runner->continue_lock(); if(!lock) return; if(!ec) { if(bytes_transferred == 0 && connection->in_message->streambuf.size() == 0) { // TODO: This might happen on server at least, might also happen here this->read_message(connection, 0); return; } auto updated_num_additional_bytes = num_additional_bytes > 2 ? num_additional_bytes - 2 : 0; std::array<unsigned char, 2> first_bytes; connection->in_message->read(reinterpret_cast<char *>(&first_bytes[0]), 2); connection->in_message->fin_rsv_opcode = first_bytes[0]; // Close connection if masked message from server (protocol error) if(first_bytes[1] >= 128) { const std::string reason("message from server masked"); connection->send_close(1002, reason); this->connection_close(connection, 1002, reason); return; } std::size_t length = (first_bytes[1] & 127); if(length == 126) { // 2 next bytes is the size of content connection->set_timeout(); asio::async_read(*connection->socket, connection->in_message->streambuf, asio::transfer_exactly(updated_num_additional_bytes > 2 ? 0 : 2 - updated_num_additional_bytes), [this, connection, updated_num_additional_bytes](const error_code &ec, std::size_t /*bytes_transferred*/) { connection->cancel_timeout(); auto lock = connection->handler_runner->continue_lock(); if(!lock) return; if(!ec) { std::array<unsigned char, 2> length_bytes; connection->in_message->read(reinterpret_cast<char *>(&length_bytes[0]), 2); std::size_t length = 0; std::size_t num_bytes = 2; for(std::size_t c = 0; c < num_bytes; c++) length += static_cast<std::size_t>(length_bytes[c]) << (8 * (num_bytes - 1 - c)); connection->in_message->length = length; this->read_message_content(connection, updated_num_additional_bytes > 2 ? updated_num_additional_bytes - 2 : 0); } else this->connection_error(connection, ec); }); } else if(length == 127) { // 8 next bytes is the size of content connection->set_timeout(); asio::async_read(*connection->socket, connection->in_message->streambuf, asio::transfer_exactly(updated_num_additional_bytes > 8 ? 0 : 8 - updated_num_additional_bytes), [this, connection, updated_num_additional_bytes](const error_code &ec, std::size_t /*bytes_transferred*/) { connection->cancel_timeout(); auto lock = connection->handler_runner->continue_lock(); if(!lock) return; if(!ec) { std::array<unsigned char, 8> length_bytes; connection->in_message->read(reinterpret_cast<char *>(&length_bytes[0]), 8); std::size_t length = 0; std::size_t num_bytes = 8; for(std::size_t c = 0; c < num_bytes; c++) length += static_cast<std::size_t>(length_bytes[c]) << (8 * (num_bytes - 1 - c)); connection->in_message->length = length; this->read_message_content(connection, updated_num_additional_bytes > 8 ? updated_num_additional_bytes - 8 : 0); } else this->connection_error(connection, ec); }); } else { connection->in_message->length = length; this->read_message_content(connection, updated_num_additional_bytes); } } else this->connection_error(connection, ec); }); } void read_message_content(const std::shared_ptr<Connection> &connection, std::size_t num_additional_bytes) { if(connection->in_message->length + (connection->fragmented_in_message ? connection->fragmented_in_message->length : 0) > config.max_message_size) { connection_error(connection, make_error_code::make_error_code(errc::message_size)); const int status = 1009; const std::string reason = "message too big"; connection->send_close(status, reason); connection_close(connection, status, reason); return; } connection->set_timeout(); asio::async_read(*connection->socket, connection->in_message->streambuf, asio::transfer_exactly(num_additional_bytes > connection->in_message->length ? 0 : connection->in_message->length - num_additional_bytes), [this, connection, num_additional_bytes](const error_code &ec, std::size_t /*bytes_transferred*/) { connection->cancel_timeout(); auto lock = connection->handler_runner->continue_lock(); if(!lock) return; if(!ec) { auto updated_num_additional_bytes = num_additional_bytes > connection->in_message->length ? num_additional_bytes - connection->in_message->length : 0; std::shared_ptr<InMessage> next_in_message; if(updated_num_additional_bytes > 0) { // Extract bytes that are not extra bytes in buffer (only happen when several messages are sent in upgrade response) next_in_message = connection->in_message; connection->in_message = std::shared_ptr<InMessage>(new InMessage(next_in_message->fin_rsv_opcode, next_in_message->length)); // Move leftover next_in_message to connection->in_message auto &source = next_in_message->streambuf; auto &target = connection->in_message->streambuf; target.commit(asio::buffer_copy(target.prepare(next_in_message->length), source.data(), next_in_message->length)); source.consume(next_in_message->length); } else next_in_message = std::shared_ptr<InMessage>(new InMessage()); // If connection close if((connection->in_message->fin_rsv_opcode & 0x0f) == 8) { int status = 0; if(connection->in_message->length >= 2) { unsigned char byte1 = connection->in_message->get(); unsigned char byte2 = connection->in_message->get(); status = (static_cast<int>(byte1) << 8) + byte2; } auto reason = connection->in_message->string(); connection->send_close(status, reason); this->connection_close(connection, status, reason); } // If ping else if((connection->in_message->fin_rsv_opcode & 0x0f) == 9) { // Send pong auto out_message = std::make_shared<OutMessage>(); *out_message << connection->in_message->string(); connection->send(out_message, nullptr, connection->in_message->fin_rsv_opcode + 1); if(this->on_ping) this->on_ping(connection); // Next message connection->in_message = next_in_message; this->read_message(connection, updated_num_additional_bytes); } // If pong else if((connection->in_message->fin_rsv_opcode & 0x0f) == 10) { if(this->on_pong) this->on_pong(connection); // Next message connection->in_message = next_in_message; this->read_message(connection, updated_num_additional_bytes); } // If fragmented message and not final fragment else if((connection->in_message->fin_rsv_opcode & 0x80) == 0) { if(!connection->fragmented_in_message) { connection->fragmented_in_message = connection->in_message; connection->fragmented_in_message->fin_rsv_opcode |= 0x80; } else { connection->fragmented_in_message->length += connection->in_message->length; // Move connection->in_message to connection->fragmented_in_message auto &source = connection->in_message->streambuf; auto &target = connection->fragmented_in_message->streambuf; target.commit(asio::buffer_copy(target.prepare(source.size()), source.data())); source.consume(source.size()); } // Next message connection->in_message = next_in_message; this->read_message(connection, updated_num_additional_bytes); } else { if(this->on_message) { if(connection->fragmented_in_message) { connection->fragmented_in_message->length += connection->in_message->length; // Move connection->in_message to connection->fragmented_in_message auto &source = connection->in_message->streambuf; auto &target = connection->fragmented_in_message->streambuf; target.commit(asio::buffer_copy(target.prepare(source.size()), source.data())); source.consume(source.size()); this->on_message(connection, connection->fragmented_in_message); } else this->on_message(connection, connection->in_message); } // Next message connection->in_message = next_in_message; // Only reset fragmented_message for non-control frames (control frames can be in between a fragmented message) connection->fragmented_in_message = nullptr; this->read_message(connection, updated_num_additional_bytes); } } else this->connection_error(connection, ec); }); } void connection_open(const std::shared_ptr<Connection> &connection) const { if(on_open) on_open(connection); } void connection_close(const std::shared_ptr<Connection> &connection, int status, const std::string &reason) const { if(on_close) on_close(connection, status, reason); } void connection_error(const std::shared_ptr<Connection> &connection, const error_code &ec) const { if(on_error) on_error(connection, ec); } }; template <class socket_type> class SocketClient : public SocketClientBase<socket_type> {}; using WS = asio::ip::tcp::socket; template <> class SocketClient<WS> : public SocketClientBase<WS> { public: SocketClient(const std::string &server_port_path) noexcept : SocketClientBase<WS>::SocketClientBase(server_port_path, 80){}; protected: void connect() override { LockGuard lock(connection_mutex); auto connection = this->connection = std::shared_ptr<Connection>(new Connection(handler_runner, config.timeout_idle, *io_service)); lock.unlock(); std::pair<std::string, std::string> host_port; if(config.proxy_server.empty()) host_port = {host, std::to_string(port)}; else { auto proxy_host_port = parse_host_port(config.proxy_server, 8080); host_port = {proxy_host_port.first, std::to_string(proxy_host_port.second)}; } auto resolver = std::make_shared<asio::ip::tcp::resolver>(*io_service); connection->set_timeout(config.timeout_request); async_resolve(*resolver, host_port, [this, connection, resolver](const error_code &ec, resolver_results results) { connection->cancel_timeout(); auto lock = connection->handler_runner->continue_lock(); if(!lock) return; if(!ec) { connection->set_timeout(this->config.timeout_request); asio::async_connect(*connection->socket, results, [this, connection, resolver](const error_code &ec, async_connect_endpoint /*endpoint*/) { connection->cancel_timeout(); auto lock = connection->handler_runner->continue_lock(); if(!lock) return; if(!ec) { asio::ip::tcp::no_delay option(true); connection->socket->set_option(option); this->upgrade(connection); } else this->connection_error(connection, ec); }); } else this->connection_error(connection, ec); }); } }; } // namespace SimpleWeb #endif /* SIMPLE_WEB_CLIENT_WS_HPP */
31,039
9,132
// Copyright (c) 2010, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // This code writes out minidump files: // http://msdn.microsoft.com/en-us/library/ms680378(VS.85,loband).aspx // // Minidumps are a Microsoft format which Breakpad uses for recording crash // dumps. This code has to run in a compromised environment (the address space // may have received SIGSEGV), thus the following rules apply: // * You may not enter the dynamic linker. This means that we cannot call // any symbols in a shared library (inc libc). Because of this we replace // libc functions in linux_libc_support.h. // * You may not call syscalls via the libc wrappers. This rule is a subset // of the first rule but it bears repeating. We have direct wrappers // around the system calls in linux_syscall_support.h. // * You may not malloc. There's an alternative allocator in memory.h and // a canonical instance in the LinuxDumper object. We use the placement // new form to allocate objects and we don't delete them. #include "client/linux/handler/minidump_descriptor.h" #include "client/linux/minidump_writer/minidump_writer.h" #include "client/minidump_file_writer-inl.h" #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <link.h> #include <stdio.h> #if defined(__ANDROID__) #include <sys/system_properties.h> #endif #include <sys/types.h> #include <sys/ucontext.h> #include <sys/user.h> #include <sys/utsname.h> #include <time.h> #include <unistd.h> #include <algorithm> #include "client/linux/dump_writer_common/thread_info.h" #include "client/linux/dump_writer_common/ucontext_reader.h" #include "client/linux/handler/exception_handler.h" #include "client/linux/minidump_writer/cpu_set.h" #include "client/linux/minidump_writer/line_reader.h" #include "client/linux/minidump_writer/linux_dumper.h" #include "client/linux/minidump_writer/linux_ptrace_dumper.h" #include "client/linux/minidump_writer/proc_cpuinfo_reader.h" #include "client/minidump_file_writer.h" #include "common/linux/linux_libc_support.h" #include "common/minidump_type_helper.h" #include "google_breakpad/common/minidump_format.h" #include "third_party/lss/linux_syscall_support.h" namespace { using google_breakpad::AppMemoryList; using google_breakpad::ExceptionHandler; using google_breakpad::CpuSet; using google_breakpad::LineReader; using google_breakpad::LinuxDumper; using google_breakpad::LinuxPtraceDumper; using google_breakpad::MDTypeHelper; using google_breakpad::MappingEntry; using google_breakpad::MappingInfo; using google_breakpad::MappingList; using google_breakpad::MinidumpFileWriter; using google_breakpad::PageAllocator; using google_breakpad::ProcCpuInfoReader; using google_breakpad::RawContextCPU; using google_breakpad::ThreadInfo; using google_breakpad::TypedMDRVA; using google_breakpad::UContextReader; using google_breakpad::UntypedMDRVA; using google_breakpad::wasteful_vector; typedef MDTypeHelper<sizeof(void*)>::MDRawDebug MDRawDebug; typedef MDTypeHelper<sizeof(void*)>::MDRawLinkMap MDRawLinkMap; class MinidumpWriter { public: // The following kLimit* constants are for when minidump_size_limit_ is set // and the minidump size might exceed it. // // Estimate for how big each thread's stack will be (in bytes). static const unsigned kLimitAverageThreadStackLength = 8 * 1024; // Number of threads whose stack size we don't want to limit. These base // threads will simply be the first N threads returned by the dumper (although // the crashing thread will never be limited). Threads beyond this count are // the extra threads. static const unsigned kLimitBaseThreadCount = 20; // Maximum stack size to dump for any extra thread (in bytes). static const unsigned kLimitMaxExtraThreadStackLen = 2 * 1024; // Make sure this number of additional bytes can fit in the minidump // (exclude the stack data). static const unsigned kLimitMinidumpFudgeFactor = 64 * 1024; MinidumpWriter(const char* minidump_path, int minidump_fd, const ExceptionHandler::CrashContext* context, const MappingList& mappings, const AppMemoryList& appmem, LinuxDumper* dumper) : fd_(minidump_fd), path_(minidump_path), ucontext_(context ? &context->context : NULL), #if !defined(__ARM_EABI__) && !defined(__mips__) float_state_(context ? &context->float_state : NULL), #endif dumper_(dumper), minidump_size_limit_(-1), memory_blocks_(dumper_->allocator()), mapping_list_(mappings), app_memory_list_(appmem) { // Assert there should be either a valid fd or a valid path, not both. assert(fd_ != -1 || minidump_path); assert(fd_ == -1 || !minidump_path); } bool Init() { if (!dumper_->Init()) return false; if (fd_ != -1) minidump_writer_.SetFile(fd_); else if (!minidump_writer_.Open(path_)) return false; return dumper_->ThreadsSuspend() && dumper_->LateInit(); } ~MinidumpWriter() { // Don't close the file descriptor when it's been provided explicitly. // Callers might still need to use it. if (fd_ == -1) minidump_writer_.Close(); dumper_->ThreadsResume(); } bool Dump() { // A minidump file contains a number of tagged streams. This is the number // of stream which we write. unsigned kNumWriters = 13; TypedMDRVA<MDRawHeader> header(&minidump_writer_); TypedMDRVA<MDRawDirectory> dir(&minidump_writer_); if (!header.Allocate()) return false; if (!dir.AllocateArray(kNumWriters)) return false; my_memset(header.get(), 0, sizeof(MDRawHeader)); header.get()->signature = MD_HEADER_SIGNATURE; header.get()->version = MD_HEADER_VERSION; header.get()->time_date_stamp = time(NULL); header.get()->stream_count = kNumWriters; header.get()->stream_directory_rva = dir.position(); unsigned dir_index = 0; MDRawDirectory dirent; if (!WriteThreadListStream(&dirent)) return false; dir.CopyIndex(dir_index++, &dirent); if (!WriteMappings(&dirent)) return false; dir.CopyIndex(dir_index++, &dirent); if (!WriteAppMemory()) return false; if (!WriteMemoryListStream(&dirent)) return false; dir.CopyIndex(dir_index++, &dirent); if (!WriteExceptionStream(&dirent)) return false; dir.CopyIndex(dir_index++, &dirent); if (!WriteSystemInfoStream(&dirent)) return false; dir.CopyIndex(dir_index++, &dirent); dirent.stream_type = MD_LINUX_CPU_INFO; if (!WriteFile(&dirent.location, "/proc/cpuinfo")) NullifyDirectoryEntry(&dirent); dir.CopyIndex(dir_index++, &dirent); dirent.stream_type = MD_LINUX_PROC_STATUS; if (!WriteProcFile(&dirent.location, GetCrashThread(), "status")) NullifyDirectoryEntry(&dirent); dir.CopyIndex(dir_index++, &dirent); dirent.stream_type = MD_LINUX_LSB_RELEASE; if (!WriteFile(&dirent.location, "/etc/lsb-release")) NullifyDirectoryEntry(&dirent); dir.CopyIndex(dir_index++, &dirent); dirent.stream_type = MD_LINUX_CMD_LINE; if (!WriteProcFile(&dirent.location, GetCrashThread(), "cmdline")) NullifyDirectoryEntry(&dirent); dir.CopyIndex(dir_index++, &dirent); dirent.stream_type = MD_LINUX_ENVIRON; if (!WriteProcFile(&dirent.location, GetCrashThread(), "environ")) NullifyDirectoryEntry(&dirent); dir.CopyIndex(dir_index++, &dirent); dirent.stream_type = MD_LINUX_AUXV; if (!WriteProcFile(&dirent.location, GetCrashThread(), "auxv")) NullifyDirectoryEntry(&dirent); dir.CopyIndex(dir_index++, &dirent); dirent.stream_type = MD_LINUX_MAPS; if (!WriteProcFile(&dirent.location, GetCrashThread(), "maps")) NullifyDirectoryEntry(&dirent); dir.CopyIndex(dir_index++, &dirent); dirent.stream_type = MD_LINUX_DSO_DEBUG; if (!WriteDSODebugStream(&dirent)) NullifyDirectoryEntry(&dirent); dir.CopyIndex(dir_index++, &dirent); // If you add more directory entries, don't forget to update kNumWriters, // above. dumper_->ThreadsResume(); return true; } bool FillThreadStack(MDRawThread* thread, uintptr_t stack_pointer, int max_stack_len, uint8_t** stack_copy) { *stack_copy = NULL; const void* stack; size_t stack_len; if (dumper_->GetStackInfo(&stack, &stack_len, stack_pointer)) { UntypedMDRVA memory(&minidump_writer_); if (max_stack_len >= 0 && stack_len > static_cast<unsigned int>(max_stack_len)) { stack_len = max_stack_len; } if (!memory.Allocate(stack_len)) return false; *stack_copy = reinterpret_cast<uint8_t*>(Alloc(stack_len)); dumper_->CopyFromProcess(*stack_copy, thread->thread_id, stack, stack_len); memory.Copy(*stack_copy, stack_len); thread->stack.start_of_memory_range = reinterpret_cast<uintptr_t>(stack); thread->stack.memory = memory.location(); memory_blocks_.push_back(thread->stack); } else { thread->stack.start_of_memory_range = stack_pointer; thread->stack.memory.data_size = 0; thread->stack.memory.rva = minidump_writer_.position(); } return true; } // Write information about the threads. bool WriteThreadListStream(MDRawDirectory* dirent) { const unsigned num_threads = dumper_->threads().size(); TypedMDRVA<uint32_t> list(&minidump_writer_); if (!list.AllocateObjectAndArray(num_threads, sizeof(MDRawThread))) return false; dirent->stream_type = MD_THREAD_LIST_STREAM; dirent->location = list.location(); *list.get() = num_threads; // If there's a minidump size limit, check if it might be exceeded. Since // most of the space is filled with stack data, just check against that. // If this expects to exceed the limit, set extra_thread_stack_len such // that any thread beyond the first kLimitBaseThreadCount threads will // have only kLimitMaxExtraThreadStackLen bytes dumped. int extra_thread_stack_len = -1; // default to no maximum if (minidump_size_limit_ >= 0) { const unsigned estimated_total_stack_size = num_threads * kLimitAverageThreadStackLength; const off_t estimated_minidump_size = minidump_writer_.position() + estimated_total_stack_size + kLimitMinidumpFudgeFactor; if (estimated_minidump_size > minidump_size_limit_) extra_thread_stack_len = kLimitMaxExtraThreadStackLen; } for (unsigned i = 0; i < num_threads; ++i) { MDRawThread thread; my_memset(&thread, 0, sizeof(thread)); thread.thread_id = dumper_->threads()[i]; // We have a different source of information for the crashing thread. If // we used the actual state of the thread we would find it running in the // signal handler with the alternative stack, which would be deeply // unhelpful. if (static_cast<pid_t>(thread.thread_id) == GetCrashThread() && ucontext_ && !dumper_->IsPostMortem()) { uint8_t* stack_copy; const uintptr_t stack_ptr = UContextReader::GetStackPointer(ucontext_); if (!FillThreadStack(&thread, stack_ptr, -1, &stack_copy)) return false; // Copy 256 bytes around crashing instruction pointer to minidump. const size_t kIPMemorySize = 256; uint64_t ip = UContextReader::GetInstructionPointer(ucontext_); // Bound it to the upper and lower bounds of the memory map // it's contained within. If it's not in mapped memory, // don't bother trying to write it. bool ip_is_mapped = false; MDMemoryDescriptor ip_memory_d; for (unsigned j = 0; j < dumper_->mappings().size(); ++j) { const MappingInfo& mapping = *dumper_->mappings()[j]; if (ip >= mapping.start_addr && ip < mapping.start_addr + mapping.size) { ip_is_mapped = true; // Try to get 128 bytes before and after the IP, but // settle for whatever's available. ip_memory_d.start_of_memory_range = std::max(mapping.start_addr, uintptr_t(ip - (kIPMemorySize / 2))); uintptr_t end_of_range = std::min(uintptr_t(ip + (kIPMemorySize / 2)), uintptr_t(mapping.start_addr + mapping.size)); ip_memory_d.memory.data_size = end_of_range - ip_memory_d.start_of_memory_range; break; } } if (ip_is_mapped) { UntypedMDRVA ip_memory(&minidump_writer_); if (!ip_memory.Allocate(ip_memory_d.memory.data_size)) return false; uint8_t* memory_copy = reinterpret_cast<uint8_t*>(Alloc(ip_memory_d.memory.data_size)); dumper_->CopyFromProcess( memory_copy, thread.thread_id, reinterpret_cast<void*>(ip_memory_d.start_of_memory_range), ip_memory_d.memory.data_size); ip_memory.Copy(memory_copy, ip_memory_d.memory.data_size); ip_memory_d.memory = ip_memory.location(); memory_blocks_.push_back(ip_memory_d); } TypedMDRVA<RawContextCPU> cpu(&minidump_writer_); if (!cpu.Allocate()) return false; my_memset(cpu.get(), 0, sizeof(RawContextCPU)); #if !defined(__ARM_EABI__) && !defined(__mips__) UContextReader::FillCPUContext(cpu.get(), ucontext_, float_state_); #else UContextReader::FillCPUContext(cpu.get(), ucontext_); #endif thread.thread_context = cpu.location(); crashing_thread_context_ = cpu.location(); } else { ThreadInfo info; if (!dumper_->GetThreadInfoByIndex(i, &info)) return false; uint8_t* stack_copy; int max_stack_len = -1; // default to no maximum for this thread if (minidump_size_limit_ >= 0 && i >= kLimitBaseThreadCount) max_stack_len = extra_thread_stack_len; if (!FillThreadStack(&thread, info.stack_pointer, max_stack_len, &stack_copy)) return false; TypedMDRVA<RawContextCPU> cpu(&minidump_writer_); if (!cpu.Allocate()) return false; my_memset(cpu.get(), 0, sizeof(RawContextCPU)); info.FillCPUContext(cpu.get()); thread.thread_context = cpu.location(); if (dumper_->threads()[i] == GetCrashThread()) { crashing_thread_context_ = cpu.location(); if (!dumper_->IsPostMortem()) { // This is the crashing thread of a live process, but // no context was provided, so set the crash address // while the instruction pointer is already here. dumper_->set_crash_address(info.GetInstructionPointer()); } } } list.CopyIndexAfterObject(i, &thread, sizeof(thread)); } return true; } // Write application-provided memory regions. bool WriteAppMemory() { for (AppMemoryList::const_iterator iter = app_memory_list_.begin(); iter != app_memory_list_.end(); ++iter) { uint8_t* data_copy = reinterpret_cast<uint8_t*>(dumper_->allocator()->Alloc(iter->length)); dumper_->CopyFromProcess(data_copy, GetCrashThread(), iter->ptr, iter->length); UntypedMDRVA memory(&minidump_writer_); if (!memory.Allocate(iter->length)) { return false; } memory.Copy(data_copy, iter->length); MDMemoryDescriptor desc; desc.start_of_memory_range = reinterpret_cast<uintptr_t>(iter->ptr); desc.memory = memory.location(); memory_blocks_.push_back(desc); } return true; } static bool ShouldIncludeMapping(const MappingInfo& mapping) { if (mapping.name[0] == 0 || // only want modules with filenames. // Only want to include one mapping per shared lib. // Avoid filtering executable mappings. (mapping.offset != 0 && !mapping.exec) || mapping.size < 4096) { // too small to get a signature for. return false; } return true; } // If there is caller-provided information about this mapping // in the mapping_list_ list, return true. Otherwise, return false. bool HaveMappingInfo(const MappingInfo& mapping) { for (MappingList::const_iterator iter = mapping_list_.begin(); iter != mapping_list_.end(); ++iter) { // Ignore any mappings that are wholly contained within // mappings in the mapping_info_ list. if (mapping.start_addr >= iter->first.start_addr && (mapping.start_addr + mapping.size) <= (iter->first.start_addr + iter->first.size)) { return true; } } return false; } // Write information about the mappings in effect. Because we are using the // minidump format, the information about the mappings is pretty limited. // Because of this, we also include the full, unparsed, /proc/$x/maps file in // another stream in the file. bool WriteMappings(MDRawDirectory* dirent) { const unsigned num_mappings = dumper_->mappings().size(); unsigned num_output_mappings = mapping_list_.size(); for (unsigned i = 0; i < dumper_->mappings().size(); ++i) { const MappingInfo& mapping = *dumper_->mappings()[i]; if (ShouldIncludeMapping(mapping) && !HaveMappingInfo(mapping)) num_output_mappings++; } TypedMDRVA<uint32_t> list(&minidump_writer_); if (num_output_mappings) { if (!list.AllocateObjectAndArray(num_output_mappings, MD_MODULE_SIZE)) return false; } else { // Still create the module list stream, although it will have zero // modules. if (!list.Allocate()) return false; } dirent->stream_type = MD_MODULE_LIST_STREAM; dirent->location = list.location(); *list.get() = num_output_mappings; // First write all the mappings from the dumper unsigned int j = 0; for (unsigned i = 0; i < num_mappings; ++i) { const MappingInfo& mapping = *dumper_->mappings()[i]; if (!ShouldIncludeMapping(mapping) || HaveMappingInfo(mapping)) continue; MDRawModule mod; if (!FillRawModule(mapping, true, i, mod, NULL)) return false; list.CopyIndexAfterObject(j++, &mod, MD_MODULE_SIZE); } // Next write all the mappings provided by the caller for (MappingList::const_iterator iter = mapping_list_.begin(); iter != mapping_list_.end(); ++iter) { MDRawModule mod; if (!FillRawModule(iter->first, false, 0, mod, iter->second)) return false; list.CopyIndexAfterObject(j++, &mod, MD_MODULE_SIZE); } return true; } // Fill the MDRawModule |mod| with information about the provided // |mapping|. If |identifier| is non-NULL, use it instead of calculating // a file ID from the mapping. bool FillRawModule(const MappingInfo& mapping, bool member, unsigned int mapping_id, MDRawModule& mod, const uint8_t* identifier) { my_memset(&mod, 0, MD_MODULE_SIZE); mod.base_of_image = mapping.start_addr; mod.size_of_image = mapping.size; uint8_t cv_buf[MDCVInfoPDB70_minsize + NAME_MAX]; uint8_t* cv_ptr = cv_buf; const uint32_t cv_signature = MD_CVINFOPDB70_SIGNATURE; my_memcpy(cv_ptr, &cv_signature, sizeof(cv_signature)); cv_ptr += sizeof(cv_signature); uint8_t* signature = cv_ptr; cv_ptr += sizeof(MDGUID); if (identifier) { // GUID was provided by caller. my_memcpy(signature, identifier, sizeof(MDGUID)); } else { // Note: ElfFileIdentifierForMapping() can manipulate the |mapping.name|. dumper_->ElfFileIdentifierForMapping(mapping, member, mapping_id, signature); } my_memset(cv_ptr, 0, sizeof(uint32_t)); // Set age to 0 on Linux. cv_ptr += sizeof(uint32_t); char file_name[NAME_MAX]; char file_path[NAME_MAX]; LinuxDumper::GetMappingEffectiveNameAndPath( mapping, file_path, sizeof(file_path), file_name, sizeof(file_name)); const size_t file_name_len = my_strlen(file_name); UntypedMDRVA cv(&minidump_writer_); if (!cv.Allocate(MDCVInfoPDB70_minsize + file_name_len + 1)) return false; // Write pdb_file_name my_memcpy(cv_ptr, file_name, file_name_len + 1); cv.Copy(cv_buf, MDCVInfoPDB70_minsize + file_name_len + 1); mod.cv_record = cv.location(); MDLocationDescriptor ld; if (!minidump_writer_.WriteString(file_path, my_strlen(file_path), &ld)) return false; mod.module_name_rva = ld.rva; return true; } bool WriteMemoryListStream(MDRawDirectory* dirent) { TypedMDRVA<uint32_t> list(&minidump_writer_); if (memory_blocks_.size()) { if (!list.AllocateObjectAndArray(memory_blocks_.size(), sizeof(MDMemoryDescriptor))) return false; } else { // Still create the memory list stream, although it will have zero // memory blocks. if (!list.Allocate()) return false; } dirent->stream_type = MD_MEMORY_LIST_STREAM; dirent->location = list.location(); *list.get() = memory_blocks_.size(); for (size_t i = 0; i < memory_blocks_.size(); ++i) { list.CopyIndexAfterObject(i, &memory_blocks_[i], sizeof(MDMemoryDescriptor)); } return true; } bool WriteExceptionStream(MDRawDirectory* dirent) { TypedMDRVA<MDRawExceptionStream> exc(&minidump_writer_); if (!exc.Allocate()) return false; my_memset(exc.get(), 0, sizeof(MDRawExceptionStream)); dirent->stream_type = MD_EXCEPTION_STREAM; dirent->location = exc.location(); exc.get()->thread_id = GetCrashThread(); exc.get()->exception_record.exception_code = dumper_->crash_signal(); exc.get()->exception_record.exception_address = dumper_->crash_address(); exc.get()->thread_context = crashing_thread_context_; return true; } bool WriteSystemInfoStream(MDRawDirectory* dirent) { TypedMDRVA<MDRawSystemInfo> si(&minidump_writer_); if (!si.Allocate()) return false; my_memset(si.get(), 0, sizeof(MDRawSystemInfo)); dirent->stream_type = MD_SYSTEM_INFO_STREAM; dirent->location = si.location(); WriteCPUInformation(si.get()); WriteOSInformation(si.get()); return true; } bool WriteDSODebugStream(MDRawDirectory* dirent) { ElfW(Phdr)* phdr = reinterpret_cast<ElfW(Phdr) *>(dumper_->auxv()[AT_PHDR]); char* base; int phnum = dumper_->auxv()[AT_PHNUM]; if (!phnum || !phdr) return false; // Assume the program base is at the beginning of the same page as the PHDR base = reinterpret_cast<char *>(reinterpret_cast<uintptr_t>(phdr) & ~0xfff); // Search for the program PT_DYNAMIC segment ElfW(Addr) dyn_addr = 0; for (; phnum >= 0; phnum--, phdr++) { ElfW(Phdr) ph; if (!dumper_->CopyFromProcess(&ph, GetCrashThread(), phdr, sizeof(ph))) return false; // Adjust base address with the virtual address of the PT_LOAD segment // corresponding to offset 0 if (ph.p_type == PT_LOAD && ph.p_offset == 0) { base -= ph.p_vaddr; } if (ph.p_type == PT_DYNAMIC) { dyn_addr = ph.p_vaddr; } } if (!dyn_addr) return false; ElfW(Dyn) *dynamic = reinterpret_cast<ElfW(Dyn) *>(dyn_addr + base); // The dynamic linker makes information available that helps gdb find all // DSOs loaded into the program. If this information is indeed available, // dump it to a MD_LINUX_DSO_DEBUG stream. struct r_debug* r_debug = NULL; uint32_t dynamic_length = 0; for (int i = 0; ; ++i) { ElfW(Dyn) dyn; dynamic_length += sizeof(dyn); if (!dumper_->CopyFromProcess(&dyn, GetCrashThread(), dynamic + i, sizeof(dyn))) { return false; } #ifdef __mips__ if (dyn.d_tag == DT_MIPS_RLD_MAP) { r_debug = reinterpret_cast<struct r_debug*>(dyn.d_un.d_ptr); continue; } #else if (dyn.d_tag == DT_DEBUG) { r_debug = reinterpret_cast<struct r_debug*>(dyn.d_un.d_ptr); continue; } #endif else if (dyn.d_tag == DT_NULL) { break; } } // The "r_map" field of that r_debug struct contains a linked list of all // loaded DSOs. // Our list of DSOs potentially is different from the ones in the crashing // process. So, we have to be careful to never dereference pointers // directly. Instead, we use CopyFromProcess() everywhere. // See <link.h> for a more detailed discussion of the how the dynamic // loader communicates with debuggers. // Count the number of loaded DSOs int dso_count = 0; struct r_debug debug_entry; if (!dumper_->CopyFromProcess(&debug_entry, GetCrashThread(), r_debug, sizeof(debug_entry))) { return false; } for (struct link_map* ptr = debug_entry.r_map; ptr; ) { struct link_map map; if (!dumper_->CopyFromProcess(&map, GetCrashThread(), ptr, sizeof(map))) return false; ptr = map.l_next; dso_count++; } MDRVA linkmap_rva = minidump_writer_.kInvalidMDRVA; if (dso_count > 0) { // If we have at least one DSO, create an array of MDRawLinkMap // entries in the minidump file. TypedMDRVA<MDRawLinkMap> linkmap(&minidump_writer_); if (!linkmap.AllocateArray(dso_count)) return false; linkmap_rva = linkmap.location().rva; int idx = 0; // Iterate over DSOs and write their information to mini dump for (struct link_map* ptr = debug_entry.r_map; ptr; ) { struct link_map map; if (!dumper_->CopyFromProcess(&map, GetCrashThread(), ptr, sizeof(map))) return false; ptr = map.l_next; char filename[257] = { 0 }; if (map.l_name) { dumper_->CopyFromProcess(filename, GetCrashThread(), map.l_name, sizeof(filename) - 1); } MDLocationDescriptor location; if (!minidump_writer_.WriteString(filename, 0, &location)) return false; MDRawLinkMap entry; entry.name = location.rva; entry.addr = map.l_addr; entry.ld = reinterpret_cast<uintptr_t>(map.l_ld); linkmap.CopyIndex(idx++, &entry); } } // Write MD_LINUX_DSO_DEBUG record TypedMDRVA<MDRawDebug> debug(&minidump_writer_); if (!debug.AllocateObjectAndArray(1, dynamic_length)) return false; my_memset(debug.get(), 0, sizeof(MDRawDebug)); dirent->stream_type = MD_LINUX_DSO_DEBUG; dirent->location = debug.location(); debug.get()->version = debug_entry.r_version; debug.get()->map = linkmap_rva; debug.get()->dso_count = dso_count; debug.get()->brk = debug_entry.r_brk; debug.get()->ldbase = debug_entry.r_ldbase; debug.get()->dynamic = reinterpret_cast<uintptr_t>(dynamic); wasteful_vector<char> dso_debug_data(dumper_->allocator(), dynamic_length); // The passed-in size to the constructor (above) is only a hint. // Must call .resize() to do actual initialization of the elements. dso_debug_data.resize(dynamic_length); dumper_->CopyFromProcess(&dso_debug_data[0], GetCrashThread(), dynamic, dynamic_length); debug.CopyIndexAfterObject(0, &dso_debug_data[0], dynamic_length); return true; } void set_minidump_size_limit(off_t limit) { minidump_size_limit_ = limit; } private: void* Alloc(unsigned bytes) { return dumper_->allocator()->Alloc(bytes); } pid_t GetCrashThread() const { return dumper_->crash_thread(); } void NullifyDirectoryEntry(MDRawDirectory* dirent) { dirent->stream_type = 0; dirent->location.data_size = 0; dirent->location.rva = 0; } #if defined(__i386__) || defined(__x86_64__) || defined(__mips__) bool WriteCPUInformation(MDRawSystemInfo* sys_info) { char vendor_id[sizeof(sys_info->cpu.x86_cpu_info.vendor_id) + 1] = {0}; static const char vendor_id_name[] = "vendor_id"; struct CpuInfoEntry { const char* info_name; int value; bool found; } cpu_info_table[] = { { "processor", -1, false }, #if defined(__i386__) || defined(__x86_64__) { "model", 0, false }, { "stepping", 0, false }, { "cpu family", 0, false }, #endif }; // processor_architecture should always be set, do this first sys_info->processor_architecture = #if defined(__mips__) MD_CPU_ARCHITECTURE_MIPS; #elif defined(__i386__) MD_CPU_ARCHITECTURE_X86; #else MD_CPU_ARCHITECTURE_AMD64; #endif const int fd = sys_open("/proc/cpuinfo", O_RDONLY, 0); if (fd < 0) return false; { PageAllocator allocator; ProcCpuInfoReader* const reader = new(allocator) ProcCpuInfoReader(fd); const char* field; while (reader->GetNextField(&field)) { for (size_t i = 0; i < sizeof(cpu_info_table) / sizeof(cpu_info_table[0]); i++) { CpuInfoEntry* entry = &cpu_info_table[i]; if (i > 0 && entry->found) { // except for the 'processor' field, ignore repeated values. continue; } if (!my_strcmp(field, entry->info_name)) { size_t value_len; const char* value = reader->GetValueAndLen(&value_len); if (value_len == 0) continue; uintptr_t val; if (my_read_decimal_ptr(&val, value) == value) continue; entry->value = static_cast<int>(val); entry->found = true; } } // special case for vendor_id if (!my_strcmp(field, vendor_id_name)) { size_t value_len; const char* value = reader->GetValueAndLen(&value_len); if (value_len > 0) my_strlcpy(vendor_id, value, sizeof(vendor_id)); } } sys_close(fd); } // make sure we got everything we wanted for (size_t i = 0; i < sizeof(cpu_info_table) / sizeof(cpu_info_table[0]); i++) { if (!cpu_info_table[i].found) { return false; } } // cpu_info_table[0] holds the last cpu id listed in /proc/cpuinfo, // assuming this is the highest id, change it to the number of CPUs // by adding one. cpu_info_table[0].value++; sys_info->number_of_processors = cpu_info_table[0].value; #if defined(__i386__) || defined(__x86_64__) sys_info->processor_level = cpu_info_table[3].value; sys_info->processor_revision = cpu_info_table[1].value << 8 | cpu_info_table[2].value; #endif if (vendor_id[0] != '\0') { my_memcpy(sys_info->cpu.x86_cpu_info.vendor_id, vendor_id, sizeof(sys_info->cpu.x86_cpu_info.vendor_id)); } return true; } #elif defined(__arm__) || defined(__aarch64__) bool WriteCPUInformation(MDRawSystemInfo* sys_info) { // The CPUID value is broken up in several entries in /proc/cpuinfo. // This table is used to rebuild it from the entries. const struct CpuIdEntry { const char* field; char format; char bit_lshift; char bit_length; } cpu_id_entries[] = { { "CPU implementer", 'x', 24, 8 }, { "CPU variant", 'x', 20, 4 }, { "CPU part", 'x', 4, 12 }, { "CPU revision", 'd', 0, 4 }, }; // The ELF hwcaps are listed in the "Features" entry as textual tags. // This table is used to rebuild them. const struct CpuFeaturesEntry { const char* tag; uint32_t hwcaps; } cpu_features_entries[] = { #if defined(__arm__) { "swp", MD_CPU_ARM_ELF_HWCAP_SWP }, { "half", MD_CPU_ARM_ELF_HWCAP_HALF }, { "thumb", MD_CPU_ARM_ELF_HWCAP_THUMB }, { "26bit", MD_CPU_ARM_ELF_HWCAP_26BIT }, { "fastmult", MD_CPU_ARM_ELF_HWCAP_FAST_MULT }, { "fpa", MD_CPU_ARM_ELF_HWCAP_FPA }, { "vfp", MD_CPU_ARM_ELF_HWCAP_VFP }, { "edsp", MD_CPU_ARM_ELF_HWCAP_EDSP }, { "java", MD_CPU_ARM_ELF_HWCAP_JAVA }, { "iwmmxt", MD_CPU_ARM_ELF_HWCAP_IWMMXT }, { "crunch", MD_CPU_ARM_ELF_HWCAP_CRUNCH }, { "thumbee", MD_CPU_ARM_ELF_HWCAP_THUMBEE }, { "neon", MD_CPU_ARM_ELF_HWCAP_NEON }, { "vfpv3", MD_CPU_ARM_ELF_HWCAP_VFPv3 }, { "vfpv3d16", MD_CPU_ARM_ELF_HWCAP_VFPv3D16 }, { "tls", MD_CPU_ARM_ELF_HWCAP_TLS }, { "vfpv4", MD_CPU_ARM_ELF_HWCAP_VFPv4 }, { "idiva", MD_CPU_ARM_ELF_HWCAP_IDIVA }, { "idivt", MD_CPU_ARM_ELF_HWCAP_IDIVT }, { "idiv", MD_CPU_ARM_ELF_HWCAP_IDIVA | MD_CPU_ARM_ELF_HWCAP_IDIVT }, #elif defined(__aarch64__) // No hwcaps on aarch64. #endif }; // processor_architecture should always be set, do this first sys_info->processor_architecture = #if defined(__aarch64__) MD_CPU_ARCHITECTURE_ARM64; #else MD_CPU_ARCHITECTURE_ARM; #endif // /proc/cpuinfo is not readable under various sandboxed environments // (e.g. Android services with the android:isolatedProcess attribute) // prepare for this by setting default values now, which will be // returned when this happens. // // Note: Bogus values are used to distinguish between failures (to // read /sys and /proc files) and really badly configured kernels. sys_info->number_of_processors = 0; sys_info->processor_level = 1U; // There is no ARMv1 sys_info->processor_revision = 42; sys_info->cpu.arm_cpu_info.cpuid = 0; sys_info->cpu.arm_cpu_info.elf_hwcaps = 0; // Counting the number of CPUs involves parsing two sysfs files, // because the content of /proc/cpuinfo will only mirror the number // of 'online' cores, and thus will vary with time. // See http://www.kernel.org/doc/Documentation/cputopology.txt { CpuSet cpus_present; CpuSet cpus_possible; int fd = sys_open("/sys/devices/system/cpu/present", O_RDONLY, 0); if (fd >= 0) { cpus_present.ParseSysFile(fd); sys_close(fd); fd = sys_open("/sys/devices/system/cpu/possible", O_RDONLY, 0); if (fd >= 0) { cpus_possible.ParseSysFile(fd); sys_close(fd); cpus_present.IntersectWith(cpus_possible); int cpu_count = cpus_present.GetCount(); if (cpu_count > 255) cpu_count = 255; sys_info->number_of_processors = static_cast<uint8_t>(cpu_count); } } } // Parse /proc/cpuinfo to reconstruct the CPUID value, as well // as the ELF hwcaps field. For the latter, it would be easier to // read /proc/self/auxv but unfortunately, this file is not always // readable from regular Android applications on later versions // (>= 4.1) of the Android platform. const int fd = sys_open("/proc/cpuinfo", O_RDONLY, 0); if (fd < 0) { // Do not return false here to allow the minidump generation // to happen properly. return true; } { PageAllocator allocator; ProcCpuInfoReader* const reader = new(allocator) ProcCpuInfoReader(fd); const char* field; while (reader->GetNextField(&field)) { for (size_t i = 0; i < sizeof(cpu_id_entries)/sizeof(cpu_id_entries[0]); ++i) { const CpuIdEntry* entry = &cpu_id_entries[i]; if (my_strcmp(entry->field, field) != 0) continue; uintptr_t result = 0; const char* value = reader->GetValue(); const char* p = value; if (value[0] == '0' && value[1] == 'x') { p = my_read_hex_ptr(&result, value+2); } else if (entry->format == 'x') { p = my_read_hex_ptr(&result, value); } else { p = my_read_decimal_ptr(&result, value); } if (p == value) continue; result &= (1U << entry->bit_length)-1; result <<= entry->bit_lshift; sys_info->cpu.arm_cpu_info.cpuid |= static_cast<uint32_t>(result); } #if defined(__arm__) // Get the architecture version from the "Processor" field. // Note that it is also available in the "CPU architecture" field, // however, some existing kernels are misconfigured and will report // invalid values here (e.g. 6, while the CPU is ARMv7-A based). // The "Processor" field doesn't have this issue. if (!my_strcmp(field, "Processor")) { size_t value_len; const char* value = reader->GetValueAndLen(&value_len); // Expected format: <text> (v<level><endian>) // Where <text> is some text like "ARMv7 Processor rev 2" // and <level> is a decimal corresponding to the ARM // architecture number. <endian> is either 'l' or 'b' // and corresponds to the endianess, it is ignored here. while (value_len > 0 && my_isspace(value[value_len-1])) value_len--; size_t nn = value_len; while (nn > 0 && value[nn-1] != '(') nn--; if (nn > 0 && value[nn] == 'v') { uintptr_t arch_level = 5; my_read_decimal_ptr(&arch_level, value + nn + 1); sys_info->processor_level = static_cast<uint16_t>(arch_level); } } #elif defined(__aarch64__) // The aarch64 architecture does not provide the architecture level // in the Processor field, so we instead check the "CPU architecture" // field. if (!my_strcmp(field, "CPU architecture")) { uintptr_t arch_level = 0; const char* value = reader->GetValue(); const char* p = value; p = my_read_decimal_ptr(&arch_level, value); if (p == value) continue; sys_info->processor_level = static_cast<uint16_t>(arch_level); } #endif // Rebuild the ELF hwcaps from the 'Features' field. if (!my_strcmp(field, "Features")) { size_t value_len; const char* value = reader->GetValueAndLen(&value_len); // Parse each space-separated tag. while (value_len > 0) { const char* tag = value; size_t tag_len = value_len; const char* p = my_strchr(tag, ' '); if (p != NULL) { tag_len = static_cast<size_t>(p - tag); value += tag_len + 1; value_len -= tag_len + 1; } else { tag_len = strlen(tag); value_len = 0; } for (size_t i = 0; i < sizeof(cpu_features_entries)/ sizeof(cpu_features_entries[0]); ++i) { const CpuFeaturesEntry* entry = &cpu_features_entries[i]; if (tag_len == strlen(entry->tag) && !memcmp(tag, entry->tag, tag_len)) { sys_info->cpu.arm_cpu_info.elf_hwcaps |= entry->hwcaps; break; } } } } } sys_close(fd); } return true; } #else # error "Unsupported CPU" #endif bool WriteFile(MDLocationDescriptor* result, const char* filename) { const int fd = sys_open(filename, O_RDONLY, 0); if (fd < 0) return false; // We can't stat the files because several of the files that we want to // read are kernel seqfiles, which always have a length of zero. So we have // to read as much as we can into a buffer. static const unsigned kBufSize = 1024 - 2*sizeof(void*); struct Buffers { Buffers* next; size_t len; uint8_t data[kBufSize]; } *buffers = reinterpret_cast<Buffers*>(Alloc(sizeof(Buffers))); buffers->next = NULL; buffers->len = 0; size_t total = 0; for (Buffers* bufptr = buffers;;) { ssize_t r; do { r = sys_read(fd, &bufptr->data[bufptr->len], kBufSize - bufptr->len); } while (r == -1 && errno == EINTR); if (r < 1) break; total += r; bufptr->len += r; if (bufptr->len == kBufSize) { bufptr->next = reinterpret_cast<Buffers*>(Alloc(sizeof(Buffers))); bufptr = bufptr->next; bufptr->next = NULL; bufptr->len = 0; } } sys_close(fd); if (!total) return false; UntypedMDRVA memory(&minidump_writer_); if (!memory.Allocate(total)) return false; for (MDRVA pos = memory.position(); buffers; buffers = buffers->next) { // Check for special case of a zero-length buffer. This should only // occur if a file's size happens to be a multiple of the buffer's // size, in which case the final sys_read() will have resulted in // zero bytes being read after the final buffer was just allocated. if (buffers->len == 0) { // This can only occur with final buffer. assert(buffers->next == NULL); continue; } memory.Copy(pos, &buffers->data, buffers->len); pos += buffers->len; } *result = memory.location(); return true; } bool WriteOSInformation(MDRawSystemInfo* sys_info) { #if defined(__ANDROID__) sys_info->platform_id = MD_OS_ANDROID; #else sys_info->platform_id = MD_OS_LINUX; #endif struct utsname uts; if (uname(&uts)) return false; static const size_t buf_len = 512; char buf[buf_len] = {0}; size_t space_left = buf_len - 1; const char* info_table[] = { uts.sysname, uts.release, uts.version, uts.machine, NULL }; bool first_item = true; for (const char** cur_info = info_table; *cur_info; cur_info++) { static const char separator[] = " "; size_t separator_len = sizeof(separator) - 1; size_t info_len = my_strlen(*cur_info); if (info_len == 0) continue; if (space_left < info_len + (first_item ? 0 : separator_len)) break; if (!first_item) { my_strlcat(buf, separator, sizeof(buf)); space_left -= separator_len; } first_item = false; my_strlcat(buf, *cur_info, sizeof(buf)); space_left -= info_len; } MDLocationDescriptor location; if (!minidump_writer_.WriteString(buf, 0, &location)) return false; sys_info->csd_version_rva = location.rva; return true; } bool WriteProcFile(MDLocationDescriptor* result, pid_t pid, const char* filename) { char buf[NAME_MAX]; if (!dumper_->BuildProcPath(buf, pid, filename)) return false; return WriteFile(result, buf); } // Only one of the 2 member variables below should be set to a valid value. const int fd_; // File descriptor where the minidum should be written. const char* path_; // Path to the file where the minidum should be written. const struct ucontext* const ucontext_; // also from the signal handler #if !defined(__ARM_EABI__) && !defined(__mips__) const google_breakpad::fpstate_t* const float_state_; // ditto #endif LinuxDumper* dumper_; MinidumpFileWriter minidump_writer_; off_t minidump_size_limit_; MDLocationDescriptor crashing_thread_context_; // Blocks of memory written to the dump. These are all currently // written while writing the thread list stream, but saved here // so a memory list stream can be written afterwards. wasteful_vector<MDMemoryDescriptor> memory_blocks_; // Additional information about some mappings provided by the caller. const MappingList& mapping_list_; // Additional memory regions to be included in the dump, // provided by the caller. const AppMemoryList& app_memory_list_; }; bool WriteMinidumpImpl(const char* minidump_path, int minidump_fd, off_t minidump_size_limit, pid_t crashing_process, const void* blob, size_t blob_size, const MappingList& mappings, const AppMemoryList& appmem) { LinuxPtraceDumper dumper(crashing_process); const ExceptionHandler::CrashContext* context = NULL; if (blob) { if (blob_size != sizeof(ExceptionHandler::CrashContext)) return false; context = reinterpret_cast<const ExceptionHandler::CrashContext*>(blob); dumper.set_crash_address( reinterpret_cast<uintptr_t>(context->siginfo.si_addr)); dumper.set_crash_signal(context->siginfo.si_signo); dumper.set_crash_thread(context->tid); } MinidumpWriter writer(minidump_path, minidump_fd, context, mappings, appmem, &dumper); // Set desired limit for file size of minidump (-1 means no limit). writer.set_minidump_size_limit(minidump_size_limit); if (!writer.Init()) return false; return writer.Dump(); } } // namespace namespace google_breakpad { bool WriteMinidump(const char* minidump_path, pid_t crashing_process, const void* blob, size_t blob_size) { return WriteMinidumpImpl(minidump_path, -1, -1, crashing_process, blob, blob_size, MappingList(), AppMemoryList()); } bool WriteMinidump(int minidump_fd, pid_t crashing_process, const void* blob, size_t blob_size) { return WriteMinidumpImpl(NULL, minidump_fd, -1, crashing_process, blob, blob_size, MappingList(), AppMemoryList()); } bool WriteMinidump(const char* minidump_path, pid_t process, pid_t process_blamed_thread) { LinuxPtraceDumper dumper(process); // MinidumpWriter will set crash address dumper.set_crash_signal(MD_EXCEPTION_CODE_LIN_DUMP_REQUESTED); dumper.set_crash_thread(process_blamed_thread); MinidumpWriter writer(minidump_path, -1, NULL, MappingList(), AppMemoryList(), &dumper); if (!writer.Init()) return false; return writer.Dump(); } bool WriteMinidump(const char* minidump_path, pid_t crashing_process, const void* blob, size_t blob_size, const MappingList& mappings, const AppMemoryList& appmem) { return WriteMinidumpImpl(minidump_path, -1, -1, crashing_process, blob, blob_size, mappings, appmem); } bool WriteMinidump(int minidump_fd, pid_t crashing_process, const void* blob, size_t blob_size, const MappingList& mappings, const AppMemoryList& appmem) { return WriteMinidumpImpl(NULL, minidump_fd, -1, crashing_process, blob, blob_size, mappings, appmem); } bool WriteMinidump(const char* minidump_path, off_t minidump_size_limit, pid_t crashing_process, const void* blob, size_t blob_size, const MappingList& mappings, const AppMemoryList& appmem) { return WriteMinidumpImpl(minidump_path, -1, minidump_size_limit, crashing_process, blob, blob_size, mappings, appmem); } bool WriteMinidump(int minidump_fd, off_t minidump_size_limit, pid_t crashing_process, const void* blob, size_t blob_size, const MappingList& mappings, const AppMemoryList& appmem) { return WriteMinidumpImpl(NULL, minidump_fd, minidump_size_limit, crashing_process, blob, blob_size, mappings, appmem); } bool WriteMinidump(const char* filename, const MappingList& mappings, const AppMemoryList& appmem, LinuxDumper* dumper) { MinidumpWriter writer(filename, -1, NULL, mappings, appmem, dumper); if (!writer.Init()) return false; return writer.Dump(); } } // namespace google_breakpad
49,718
16,448
#ifndef MYSORT_HPP #define MYSORT_HPP template<typename T> void _swap(T& a, T& b) { T temp = a; a = b; b = temp; } template<typename T> void _quick_sort(T* items, int l, int r) { if (r <= l) return; int m = (l + r) / 2; if (items[m] < items[l]) _swap(items[m], items[l]); if (items[r] < items[m]) _swap(items[r], items[m]); if (items[m] < items[l]) _swap(items[m], items[l]); if (2 < r - l) { int pivot = l + 1; int left = pivot + 1; int right = r - 1; _swap(items[m], items[pivot]); while (left <= right) { while (left <= right && items[left] <= items[pivot]) left++; while (left <= right && items[pivot] <= items[right]) right--; if (left <= right) _swap(items[left], items[right]); } _swap(items[pivot], items[right]); _quick_sort(items, l, right - 1); _quick_sort(items, right + 1, r); } } template <typename T> void myQuickSort(T* items, int size) { _quick_sort<T>(items, 0, size - 1); } #endif
966
455
#include "TexturesManager.h" TexturesManager::TexturesManager() { _logger = Logger::GetInstance(); } void TexturesManager::LoadFromFile(const std::string& name, const std::string& path, const sf::IntRect& area) { std::string message = " graphics No" + std::to_string(_textures.size() + 1) + " (" + name + ") from \"" + path + "\""; if (_textures[name].loadFromFile(path, area) == false) _logger->Log(Logger::LogType::ERROR, "Unable to load" + message); else _logger->Log(Logger::LogType::INFO, "Loaded" + message); } void TexturesManager::LoadFromImage(const std::string& name, const sf::Image& img, const sf::IntRect& area) { std::string message = " graphics No" + std::to_string(_textures.size() + 1) + " (" + name + ") from image"; if (_textures[name].loadFromImage(img, area) == false) _logger->Log(Logger::LogType::ERROR, "Unable to load" + message); else _logger->Log(Logger::LogType::INFO, "Loaded" + message); } void TexturesManager::LoadFromMemory(const std::string& name, const void* data, size_t size, const sf::IntRect& area) { std::string message = " graphics No" + std::to_string(_textures.size() + 1) + " (" + name + ") from memory"; if (_textures[name].loadFromMemory(data, size, area) == false) _logger->Log(Logger::LogType::ERROR, "Unable to load" + message); else _logger->Log(Logger::LogType::INFO, "Loaded" + message); } void TexturesManager::LoadFromStream(const std::string& name, sf::InputStream& stream, const sf::IntRect& area) { std::string message = " graphics No" + std::to_string(_textures.size() + 1) + " (" + name + ") from stream"; if (_textures[name].loadFromStream(stream, area) == false) _logger->Log(Logger::LogType::ERROR, "Unable to load" + message); else _logger->Log(Logger::LogType::INFO, "Loaded" + message); } std::shared_ptr<sf::Texture> TexturesManager::CreateTmpTexture(const std::string& name, const std::string& source, const sf::IntRect& area) { auto found = _tmpTextures.find(name); if (found != _tmpTextures.end() && found->second.use_count() > 1) return nullptr; auto tex = GetTexture(source); if (tex == nullptr) return nullptr; auto srcSize = tex->getSize(); if (CollisionHelper::CheckRectContains(sf::IntRect(0, 0, int(srcSize.x), int(srcSize.y)), area) == false) return nullptr; //Find first with use_count <= 1 std::shared_ptr<sf::Texture> empty = nullptr; for(auto it = _tmpTextures.begin(); it != _tmpTextures.end(); it++) { if (it->second.use_count() <= 1) { if (it->second == nullptr) { _tmpTextures.erase(it->first); continue; } else { it->second.swap(empty); _tmpTextures.erase(it->first); break; } } } //Convert auto img = tex->copyToImage(); if (empty == nullptr) empty = std::make_shared<sf::Texture>(); if (empty->loadFromImage(img, area) == false) return nullptr; _tmpTextures[name] = empty; return _tmpTextures[name]; } sf::Texture* TexturesManager::GetTexture(const std::string& name) { auto found = _textures.find(name); if (found != _textures.end()) return &((*found).second); else return nullptr; } std::shared_ptr<sf::Texture> TexturesManager::GetTmpTexture(const std::string& name) { auto found = _tmpTextures.find(name); if (found != _tmpTextures.end()) { if (found->second.use_count() > 1) return found->second; else return nullptr; } return nullptr; } bool TexturesManager::Exists(const std::string& name) const { if (_textures.find(name) != _textures.end()) return true; return false; } bool TexturesManager::TmpExists(const std::string& name) const { auto found = _tmpTextures.find(name); if (found != _tmpTextures.end()) { if (found->second.use_count() > 1) return true; else return false; } return false; } void TexturesManager::ApplySmooth(bool smooth) { for (auto it = _textures.begin(); it != _textures.end(); it++) it->second.setSmooth(smooth); } void TexturesManager::ApplyRepeat(bool repeat) { for (auto it = _textures.begin(); it != _textures.end(); it++) it->second.setRepeated(repeat); }
4,049
1,510
// // George O'Neill, University of York 2020 // // Make a basic cube that allows for addition of photonic objects // // This defines histograms we are filling // #ifndef HistoManager_h #define HistoManager_h 1 #define VERBOSE 1 #include <g4root.hh> // change this for different types of files #include <G4UnitsTable.hh> #include <globals.hh> class HistoManager{ public: HistoManager(): fFileName( "n4s_histos" ){ Book(); }; // default constructor ~HistoManager(){ delete G4AnalysisManager::Instance(); }; // default destructor private: void Book(); // histogram collection G4String fFileName; // root file name }; // end HistoManager #endif
658
238