hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
4f922825623d68bf502a8726890b3376a7b1e5ad
3,316
cc
C++
src/fcst/source/layers/homogeneous_CL.cc
OpenFcst/OpenFcst0.2
770a0d9b145cd39c3a065b653a53b5082dc5d85c
[ "MIT" ]
16
2015-05-08T18:19:39.000Z
2021-05-21T17:22:47.000Z
src/fcst/source/layers/homogeneous_CL.cc
OpenFcst/OpenFcst0.2
770a0d9b145cd39c3a065b653a53b5082dc5d85c
[ "MIT" ]
3
2016-09-05T10:17:36.000Z
2016-12-11T18:23:06.000Z
src/fcst/source/layers/homogeneous_CL.cc
OpenFcst/OpenFcst0.2
770a0d9b145cd39c3a065b653a53b5082dc5d85c
[ "MIT" ]
1
2021-04-15T16:45:47.000Z
2021-04-15T16:45:47.000Z
//--------------------------------------------------------------------------- // // FCST: Fuel Cell Simulation Toolbox // // Copyright (C) 2006-13 by Energy Systems Design Laboratory, University of Alberta // // This software is distributed under the MIT License. // For more information, see the README file in /doc/LICENSE // - Class: homogeneous_CL.h // - Description: Class characterizing the macro-homogeneous catalyst layer. // - Developers: Marc Secanell, Peter Dobson and Madhur Bhaiya // - Id: $Id: homogeneous_CL.cc 2605 2014-08-15 03:36:44Z secanell $ // //--------------------------------------------------------------------------- #include "layers/homogeneous_CL.h" namespace NAME = FuelCellShop::Layer; template <int dim> const std::string NAME::HomogeneousCL<dim>::concrete_name ("HomogeneousCL"); template <int dim> NAME::HomogeneousCL<dim> const* NAME::HomogeneousCL<dim>::PROTOTYPE = new NAME::HomogeneousCL<dim>(); //--------------------------------------------------------------------------- template <int dim> NAME::HomogeneousCL<dim>::HomogeneousCL() : ConventionalCL<dim>() { this->get_mapFactory()->insert(std::pair<std::string, FuelCellShop::Layer::CatalystLayer<dim>* >(concrete_name, this)); } //--------------------------------------------------------------------------- template <int dim> NAME::HomogeneousCL<dim>::HomogeneousCL(std::string name) : ConventionalCL<dim>(name) { } //--------------------------------------------------------------------------- template <int dim> NAME::HomogeneousCL<dim>::~HomogeneousCL() {} //--------------------------------------------------------------------------- template <int dim> void NAME::HomogeneousCL<dim>::declare_parameters (const std::string& cl_section_name, ParameterHandler &param) const { NAME::ConventionalCL<dim>::declare_parameters(cl_section_name, param); } //--------------------------------------------------------------------------- template <int dim> void NAME::HomogeneousCL<dim>::initialize (ParameterHandler &param) { NAME::ConventionalCL<dim>::initialize(param); } //--------------------------------------------------------------------------- template <int dim> void NAME::HomogeneousCL<dim>::current_density(std::vector<double>& coef) { this->kinetics->current_density(coef); for (unsigned int i = 0; i<coef.size(); ++i) coef[i] *= this->Av.at(this->local_material_id()); } //--------------------------------------------------------------------------- template <int dim> void NAME::HomogeneousCL<dim>::derivative_current_density(std::map< VariableNames, std::vector<double> >& dcoef_du) { this->kinetics->derivative_current(dcoef_du); for (std::map< VariableNames, std::vector<double> >::iterator iter=dcoef_du.begin(); iter!=dcoef_du.end(); ++iter) for (unsigned int q=0; q<iter->second.size(); ++q) iter->second[q] *= this->Av.at(this->local_material_id()); } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- // Explicit instantiations. template class NAME::HomogeneousCL<deal_II_dimension>;
37.681818
123
0.503619
OpenFcst
4f93d422c57cdc708062a3fddc26bc7560ccd52c
762,726
hpp
C++
runtime.Kokkos.NET/Analyzes/BesselMethods.hpp
trmcnealy/Kokkos.NET
d81aa03d720c7d8a089fdb42da18b240f127758c
[ "MIT" ]
null
null
null
runtime.Kokkos.NET/Analyzes/BesselMethods.hpp
trmcnealy/Kokkos.NET
d81aa03d720c7d8a089fdb42da18b240f127758c
[ "MIT" ]
null
null
null
runtime.Kokkos.NET/Analyzes/BesselMethods.hpp
trmcnealy/Kokkos.NET
d81aa03d720c7d8a089fdb42da18b240f127758c
[ "MIT" ]
null
null
null
#pragma once #include <runtime.Kokkos/ViewTypes.hpp> #include <runtime.Kokkos/Extensions.hpp> #include <Complex.hpp> //template<typename DataType, class ExecutionSpace> //using KokkosView = Kokkos::View<float*, typename ExecutionSpace::array_layout, ExecutionSpace>; static int32 c__1 = 1; static System::Complex<float> c_b17 = {(float)2., (float)0.}; static int32 c__2 = 2; static int32 c__4 = 4; static int32 c__12 = 12; static int32 c__13 = 13; static int32 c__5 = 5; static int32 c__11 = 11; static int32 c__9 = 9; static int32 c__0 = 0; static int32 c__14 = 14; static int32 c__15 = 15; static int32 c__16 = 16; static double c_b876 = .5; static double c_b877 = 0.; static int cacai_(System::Complex<float>* z__, float* fnu, int32* kode, int32* mr, int32* n, System::Complex<float> * y, int32* nz, float* rl, float* tol, float* elim, float* alim) { /* Initialized data */ static float pi = (float)3.14159265358979324; /* System generated locals */ System::Complex<float> q__1, q__2, q__3; System::Complex<float> c1, c2; float az; System::Complex<float> cy[2]; int32 nn, nw; System::Complex<float> zn; float yy, arg, cpn; int32 iuf; float fmr, sgn; int32 inu; float spn; System::Complex<float> csgn; float dfnu; System::Complex<float> cspn; float ascle; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE CACAI */ /* ***REFER TO CAIRY */ /* C CACAI APPLIES THE ANALYTIC CONTINUATION FORMULA */ /* K(FNU,ZN*EXP(MP))=K(FNU,ZN)*EXP(-MP*FNU) - MP*I(FNU,ZN) */ /* MP=PI*MR*CMPLX(0.0,1.0) */ /* TO CONTINUE THE K FUNCTION FROM THE RIGHT HALF TO THE LEFT */ /* HALF Z PLANE FOR USE WITH CAIRY WHERE FNU=1/3 OR 2/3 AND N=1. */ /* CACAI IS THE SAME AS CACON WITH THE PARTS FOR LARGER ORDERS AND */ /* RECURRENCE REMOVED. A RECURSIVE CALL TO CACON CAN RESULT IF CACON */ /* IS CALLED FROM CAIRY. */ /* ***ROUTINES CALLED CASYI,CBKNU,CMLRI,CSERI,CS1S2,R1MACH */ /* ***END PROLOGUE CACAI */ /* Parameter adjustments */ --y; /* Function Body */ *nz = 0; q__1 = -*z__; zn = q__1; az = c_abs(z__); nn = *n; dfnu = *fnu + (float)(*n - 1); if(az <= (float)2.) { goto L10; } if(az * az * (float).25 > dfnu + (float)1.) { goto L20; } L10: /* ----------------------------------------------------------------------- */ /* POWER SERIES FOR THE I FUNCTION */ /* ----------------------------------------------------------------------- */ cseri_(&zn, fnu, kode, &nn, &y[1], &nw, tol, elim, alim); goto L40; L20: if(az < *rl) { goto L30; } /* ----------------------------------------------------------------------- */ /* ASYMPTOTIC EXPANSION FOR LARGE Z FOR THE I FUNCTION */ /* ----------------------------------------------------------------------- */ casyi_(&zn, fnu, kode, &nn, &y[1], &nw, rl, tol, elim, alim); if(nw < 0) { goto L70; } goto L40; L30: /* ----------------------------------------------------------------------- */ /* MILLER ALGORITHM NORMALIZED BY THE SERIES FOR THE I FUNCTION */ /* ----------------------------------------------------------------------- */ cmlri_(&zn, fnu, kode, &nn, &y[1], &nw, tol); if(nw < 0) { goto L70; } L40: /* ----------------------------------------------------------------------- */ /* ANALYTIC CONTINUATION TO THE LEFT HALF PLANE FOR THE K FUNCTION */ /* ----------------------------------------------------------------------- */ cbknu_(&zn, fnu, kode, &c__1, cy, &nw, tol, elim, alim); if(nw != 0) { goto L70; } fmr = (float)(*mr); sgn = -r_sign(&pi, &fmr); q__1.real() = (float)0., q__1.imag() = sgn; csgn.real() = q__1.real(), csgn.imag() = q__1.imag(); if(*kode == 1) { goto L50; } yy = -r_imag(&zn); cpn = cos(yy); spn = sin(yy); q__2.real() = cpn, q__2.imag() = spn; q__1.real() = csgn.real() * q__2.real() - csgn.imag() * q__2.imag(), q__1.imag() = csgn.real() * q__2.imag() + csgn.imag() * q__2.real(); csgn.real() = q__1.real(), csgn.imag() = q__1.imag(); L50: /* ----------------------------------------------------------------------- */ /* CALCULATE CSPN=EXP(FNU*PI*I) TO MINIMIZE LOSSES OF SIGNIFICANCE */ /* WHEN FNU IS LARGE */ /* ----------------------------------------------------------------------- */ inu = (int32)(*fnu); arg = (*fnu - (float)inu) * sgn; cpn = cos(arg); spn = sin(arg); q__1.real() = cpn, q__1.imag() = spn; cspn.real() = q__1.real(), cspn.imag() = q__1.imag(); if(inu % 2 == 1) { q__1.real() = -cspn.real(), q__1.imag() = -cspn.imag(); cspn.real() = q__1.real(), cspn.imag() = q__1.imag(); } c1.real() = cy[0].real(), c1.imag() = cy[0].imag(); c2.real() = y[1].real(), c2.imag() = y[1].imag(); if(*kode == 1) { goto L60; } iuf = 0; ascle = r1mach_(&c__1) * (float)1e3 / *tol; cs1s2_(&zn, &c1, &c2, &nw, &ascle, alim, &iuf); *nz += nw; L60: q__2.real() = cspn.real() * c1.real() - cspn.imag() * c1.imag(), q__2.imag() = cspn.real() * c1.imag() + cspn.imag() * c1.real(); q__3.real() = csgn.real() * c2.real() - csgn.imag() * c2.imag(), q__3.imag() = csgn.real() * c2.imag() + csgn.imag() * c2.real(); q__1.real() = q__2.real() + q__3.real(), q__1.imag() = q__2.imag() + q__3.imag(); y[1].real() = q__1.real(), y[1].imag() = q__1.imag(); return 0; L70: *nz = -1; if(nw == -2) { *nz = -2; } return 0; } /* cacai_ */ static int cacon_(System::Complex<float>* z__, float* fnu, int32* kode, int32* mr, int32* n, System::Complex<float>* y, int32* nz, float* rl, float* fnul, float* tol, float* elim, float* alim) { /* Initialized data */ static float pi = (float)3.14159265358979324; static System::Complex<float> cone = {(float)1., (float)0.}; /* System generated locals */ int32 i__1, i__2; float r__1; System::Complex<float> q__1, q__2, q__3; int32 i__; System::Complex<float> c1, c2, s1, s2, ck, cs, cy[2]; int32 nn, nw; System::Complex<float> st, zn, rz; float yy, c1i, c1m, as2; System::Complex<float> sc1, sc2; float c1r, arg, cpn; int32 iuf; float fmr; System::Complex<float> csr[3], css[3]; float sgn; int32 inu; float bry[3], spn; System::Complex<float> cscl, cscr, csgn; System::Complex<float> cspn; int32 kflag; float ascle, bscle; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE CACON */ /* ***REFER TO CBESK,CBESH */ /* C CACON APPLIES THE ANALYTIC CONTINUATION FORMULA */ /* K(FNU,ZN*EXP(MP))=K(FNU,ZN)*EXP(-MP*FNU) - MP*I(FNU,ZN) */ /* MP=PI*MR*CMPLX(0.0,1.0) */ /* TO CONTINUE THE K FUNCTION FROM THE RIGHT HALF TO THE LEFT */ /* HALF Z PLANE */ /* ***ROUTINES CALLED CBINU,CBKNU,CS1S2,R1MACH */ /* ***END PROLOGUE CACON */ /* Parameter adjustments */ --y; /* Function Body */ *nz = 0; q__1.real() = -z__->real(), q__1.imag() = -z__->imag(); zn.real() = q__1.real(), zn.imag() = q__1.imag(); nn = *n; cbinu_(&zn, fnu, kode, &nn, &y[1], &nw, rl, fnul, tol, elim, alim); if(nw < 0) { goto L80; } /* ----------------------------------------------------------------------- */ /* ANALYTIC CONTINUATION TO THE LEFT HALF PLANE FOR THE K FUNCTION */ /* ----------------------------------------------------------------------- */ nn = std::min(2L, *n); cbknu_(&zn, fnu, kode, &nn, cy, &nw, tol, elim, alim); if(nw != 0) { goto L80; } s1.real() = cy[0].real(), s1.imag() = cy[0].imag(); fmr = (float)(*mr); sgn = -r_sign(&pi, &fmr); q__1.real() = (float)0., q__1.imag() = sgn; csgn.real() = q__1.real(), csgn.imag() = q__1.imag(); if(*kode == 1) { goto L10; } yy = -r_imag(&zn); cpn = cos(yy); spn = sin(yy); q__2.real() = cpn, q__2.imag() = spn; q__1.real() = csgn.real() * q__2.real() - csgn.imag() * q__2.imag(), q__1.imag() = csgn.real() * q__2.imag() + csgn.imag() * q__2.real(); csgn.real() = q__1.real(), csgn.imag() = q__1.imag(); L10: /* ----------------------------------------------------------------------- */ /* CALCULATE CSPN=EXP(FNU*PI*I) TO MINIMIZE LOSSES OF SIGNIFICANCE */ /* WHEN FNU IS LARGE */ /* ----------------------------------------------------------------------- */ inu = (int32)(*fnu); arg = (*fnu - (float)inu) * sgn; cpn = cos(arg); spn = sin(arg); q__1.real() = cpn, q__1.imag() = spn; cspn.real() = q__1.real(), cspn.imag() = q__1.imag(); if(inu % 2 == 1) { q__1.real() = -cspn.real(), q__1.imag() = -cspn.imag(); cspn.real() = q__1.real(), cspn.imag() = q__1.imag(); } iuf = 0; c1.real() = s1.real(), c1.imag() = s1.imag(); c2.real() = y[1].real(), c2.imag() = y[1].imag(); ascle = r1mach_(&c__1) * (float)1e3 / *tol; if(*kode == 1) { goto L20; } cs1s2_(&zn, &c1, &c2, &nw, &ascle, alim, &iuf); *nz += nw; sc1.real() = c1.real(), sc1.imag() = c1.imag(); L20: q__2.real() = cspn.real() * c1.real() - cspn.imag() * c1.imag(), q__2.imag() = cspn.real() * c1.imag() + cspn.imag() * c1.real(); q__3.real() = csgn.real() * c2.real() - csgn.imag() * c2.imag(), q__3.imag() = csgn.real() * c2.imag() + csgn.imag() * c2.real(); q__1.real() = q__2.real() + q__3.real(), q__1.imag() = q__2.imag() + q__3.imag(); y[1].real() = q__1.real(), y[1].imag() = q__1.imag(); if(*n == 1) { return 0; } q__1.real() = -cspn.real(), q__1.imag() = -cspn.imag(); cspn.real() = q__1.real(), cspn.imag() = q__1.imag(); s2.real() = cy[1].real(), s2.imag() = cy[1].imag(); c1.real() = s2.real(), c1.imag() = s2.imag(); c2.real() = y[2].real(), c2.imag() = y[2].imag(); if(*kode == 1) { goto L30; } cs1s2_(&zn, &c1, &c2, &nw, &ascle, alim, &iuf); *nz += nw; sc2.real() = c1.real(), sc2.imag() = c1.imag(); L30: q__2.real() = cspn.real() * c1.real() - cspn.imag() * c1.imag(), q__2.imag() = cspn.real() * c1.imag() + cspn.imag() * c1.real(); q__3.real() = csgn.real() * c2.real() - csgn.imag() * c2.imag(), q__3.imag() = csgn.real() * c2.imag() + csgn.imag() * c2.real(); q__1.real() = q__2.real() + q__3.real(), q__1.imag() = q__2.imag() + q__3.imag(); y[2].real() = q__1.real(), y[2].imag() = q__1.imag(); if(*n == 2) { return 0; } q__1.real() = -cspn.real(), q__1.imag() = -cspn.imag(); cspn.real() = q__1.real(), cspn.imag() = q__1.imag(); c_div(&q__1, &c_b17, &zn); rz.real() = q__1.real(), rz.imag() = q__1.imag(); r__1 = *fnu + (float)1.; q__2.real() = r__1, q__2.imag() = (float)0.; q__1.real() = q__2.real() * rz.real() - q__2.imag() * rz.imag(), q__1.imag() = q__2.real() * rz.imag() + q__2.imag() * rz.real(); ck.real() = q__1.real(), ck.imag() = q__1.imag(); /* ----------------------------------------------------------------------- */ /* SCALE NEAR EXPONENT EXTREMES DURING RECURRENCE ON K FUNCTIONS */ /* ----------------------------------------------------------------------- */ r__1 = (float)1. / *tol; q__1.real() = r__1, q__1.imag() = (float)0.; cscl.real() = q__1.real(), cscl.imag() = q__1.imag(); q__1.real() = *tol, q__1.imag() = (float)0.; cscr.real() = q__1.real(), cscr.imag() = q__1.imag(); css[0].real() = cscl.real(), css[0].imag() = cscl.imag(); css[1].real() = cone.real(), css[1].imag() = cone.imag(); css[2].real() = cscr.real(), css[2].imag() = cscr.imag(); csr[0].real() = cscr.real(), csr[0].imag() = cscr.imag(); csr[1].real() = cone.real(), csr[1].imag() = cone.imag(); csr[2].real() = cscl.real(), csr[2].imag() = cscl.imag(); bry[0] = ascle; bry[1] = (float)1. / ascle; bry[2] = r1mach_(&c__2); as2 = c_abs(&s2); kflag = 2; if(as2 > bry[0]) { goto L40; } kflag = 1; goto L50; L40: if(as2 < bry[1]) { goto L50; } kflag = 3; L50: bscle = bry[kflag - 1]; i__1 = kflag - 1; q__1.real() = s1.real() * css[i__1].real() - s1.imag() * css[i__1].imag(), q__1.imag() = s1.real() * css[i__1].imag() + s1.imag() * css[i__1].real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); i__1 = kflag - 1; q__1.real() = s2.real() * css[i__1].real() - s2.imag() * css[i__1].imag(), q__1.imag() = s2.real() * css[i__1].imag() + s2.imag() * css[i__1].real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); i__1 = kflag - 1; cs.real() = csr[i__1].real(), cs.imag() = csr[i__1].imag(); i__1 = *n; for(i__ = 3; i__ <= i__1; ++i__) { st.real() = s2.real(), st.imag() = s2.imag(); q__2.real() = ck.real() * s2.real() - ck.imag() * s2.imag(), q__2.imag() = ck.real() * s2.imag() + ck.imag() * s2.real(); q__1.real() = q__2.real() + s1.real(), q__1.imag() = q__2.imag() + s1.imag(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); s1.real() = st.real(), s1.imag() = st.imag(); q__1.real() = s2.real() * cs.real() - s2.imag() * cs.imag(), q__1.imag() = s2.real() * cs.imag() + s2.imag() * cs.real(); c1.real() = q__1.real(), c1.imag() = q__1.imag(); st.real() = c1.real(), st.imag() = c1.imag(); i__2 = i__; c2.real() = y[i__2].real(), c2.imag() = y[i__2].imag(); if(*kode == 1) { goto L60; } if(iuf < 0) { goto L60; } cs1s2_(&zn, &c1, &c2, &nw, &ascle, alim, &iuf); *nz += nw; sc1.real() = sc2.real(), sc1.imag() = sc2.imag(); sc2.real() = c1.real(), sc2.imag() = c1.imag(); if(iuf != 3) { goto L60; } iuf = -4; i__2 = kflag - 1; q__1.real() = sc1.real() * css[i__2].real() - sc1.imag() * css[i__2].imag(), q__1.imag() = sc1.real() * css[i__2].imag() + sc1.imag() * css[i__2].real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); i__2 = kflag - 1; q__1.real() = sc2.real() * css[i__2].real() - sc2.imag() * css[i__2].imag(), q__1.imag() = sc2.real() * css[i__2].imag() + sc2.imag() * css[i__2].real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); st.real() = sc2.real(), st.imag() = sc2.imag(); L60: i__2 = i__; q__2.real() = cspn.real() * c1.real() - cspn.imag() * c1.imag(), q__2.imag() = cspn.real() * c1.imag() + cspn.imag() * c1.real(); q__3.real() = csgn.real() * c2.real() - csgn.imag() * c2.imag(), q__3.imag() = csgn.real() * c2.imag() + csgn.imag() * c2.real(); q__1.real() = q__2.real() + q__3.real(), q__1.imag() = q__2.imag() + q__3.imag(); y[i__2].real() = q__1.real(), y[i__2].imag() = q__1.imag(); q__1.real() = ck.real() + rz.real(), q__1.imag() = ck.imag() + rz.imag(); ck.real() = q__1.real(), ck.imag() = q__1.imag(); q__1.real() = -cspn.real(), q__1.imag() = -cspn.imag(); cspn.real() = q__1.real(), cspn.imag() = q__1.imag(); if(kflag >= 3) { goto L70; } c1r = c1.real(); c1i = r_imag(&c1); c1r = abs(c1r); c1i = abs(c1i); c1m = max(c1r, c1i); if(c1m <= bscle) { goto L70; } ++kflag; bscle = bry[kflag - 1]; q__1.real() = s1.real() * cs.real() - s1.imag() * cs.imag(), q__1.imag() = s1.real() * cs.imag() + s1.imag() * cs.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); s2.real() = st.real(), s2.imag() = st.imag(); i__2 = kflag - 1; q__1.real() = s1.real() * css[i__2].real() - s1.imag() * css[i__2].imag(), q__1.imag() = s1.real() * css[i__2].imag() + s1.imag() * css[i__2].real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); i__2 = kflag - 1; q__1.real() = s2.real() * css[i__2].real() - s2.imag() * css[i__2].imag(), q__1.imag() = s2.real() * css[i__2].imag() + s2.imag() * css[i__2].real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); i__2 = kflag - 1; cs.real() = csr[i__2].real(), cs.imag() = csr[i__2].imag(); L70:; } return 0; L80: *nz = -1; if(nw == -2) { *nz = -2; } return 0; } /* cacon_ */ static int cairy_(System::Complex<float>* z__, int32* id, int32* kode, System::Complex<float>* ai, int32* nz, int32* ierr) { /* Initialized data */ static float tth = (float).666666666666666667; static float c1 = (float).35502805388781724; static float c2 = (float).258819403792806799; static float coef = (float).183776298473930683; static System::Complex<float> cone = {(float)1., (float)0.}; /* System generated locals */ int32 i__1, i__2; float r__1, r__2; double d__1, d__2; System::Complex<float> q__1, q__2, q__3, q__4, q__5, q__6; int32 k; float d1, d2; int32 k1, k2; System::Complex<float> s1, s2, z3; float aa, bb, ad, ak, bk, ck, dk, az; System::Complex<float> cy[1]; int32 nn; float rl; int32 mr; float zi, zr, az3, z3i, z3r, fid, dig, r1m5; System::Complex<float> csq; float fnu; System::Complex<float> zta; float tol; System::Complex<float> trm1, trm2; float sfac, alim, elim, alaz, atrm; int32 iflag; /* *********************************************************************72 */ /* c CAIRY computes the System::Complex<float> Airy function AI(Z) or its derivative. */ /* ***BEGIN PROLOGUE CAIRY */ /* ***DATE WRITTEN 830501 (YYMMDD) */ /* ***REVISION DATE 890801, 930101 (YYMMDD) */ /* ***CATEGORY NO. B5K */ /* ***KEYWORDS AIRY FUNCTION,BESSEL FUNCTIONS OF ORDER ONE THIRD */ /* ***AUTHOR AMOS, DONALD E., SANDIA NATIONAL LABORATORIES */ /* ***PURPOSE TO COMPUTE AIRY FUNCTIONS AI(Z) AND DAI(Z) FOR COMPLEX Z */ /* ***DESCRIPTION */ /* ON KODE=1, CAIRY COMPUTES THE COMPLEX AIRY FUNCTION AI(Z) OR */ /* ITS DERIVATIVE DAI(Z)/DZ ON ID=0 OR ID=1 RESPECTIVELY. ON */ /* KODE=2, A SCALING OPTION CEXP(ZTA)*AI(Z) OR CEXP(ZTA)* */ /* DAI(Z)/DZ IS PROVIDED TO REMOVE THE EXPONENTIAL DECAY IN */ /* -PI/3.LT.ARG(Z).LT.PI/3 AND THE EXPONENTIAL GROWTH IN */ /* PI/3.LT.ABS(ARG(Z)).LT.PI WHERE ZTA=(2/3)*Z*CSQRT(Z) */ /* WHILE THE AIRY FUNCTIONS AI(Z) AND DAI(Z)/DZ ARE ANALYTIC IN */ /* THE WHOLE Z PLANE, THE CORRESPONDING SCALED FUNCTIONS DEFINED */ /* FOR KODE=2 HAVE A CUT ALONG THE NEGATIVE REAL AXIS. */ /* DEFINITIONS AND NOTATION ARE FOUND IN THE NBS HANDBOOK OF */ /* MATHEMATICAL FUNCTIONS (REF. 1). */ /* INPUT */ /* Z - Z=CMPLX(X,Y) */ /* ID - ORDER OF DERIVATIVE, ID=0 OR ID=1 */ /* KODE - A PARAMETER TO INDICATE THE SCALING OPTION */ /* KODE= 1 RETURNS */ /* AI=AI(Z) ON ID=0 OR */ /* AI=DAI(Z)/DZ ON ID=1 */ /* = 2 RETURNS */ /* AI=CEXP(ZTA)*AI(Z) ON ID=0 OR */ /* AI=CEXP(ZTA)*DAI(Z)/DZ ON ID=1 WHERE */ /* ZTA=(2/3)*Z*CSQRT(Z) */ /* OUTPUT */ /* AI - COMPLEX ANSWER DEPENDING ON THE CHOICES FOR ID AND */ /* KODE */ /* NZ - UNDERFLOW INDICATOR */ /* NZ= 0 , NORMAL RETURN */ /* NZ= 1 , AI=CMPLX(0.0,0.0) DUE TO UNDERFLOW IN */ /* -PI/3.LT.ARG(Z).LT.PI/3 ON KODE=1 */ /* IERR - ERROR FLAG */ /* IERR=0, NORMAL RETURN - COMPUTATION COMPLETED */ /* IERR=1, INPUT ERROR - NO COMPUTATION */ /* IERR=2, OVERFLOW - NO COMPUTATION, REAL(ZTA) */ /* TOO LARGE WITH KODE=1. */ /* IERR=3, CABS(Z) LARGE - COMPUTATION COMPLETED */ /* LOSSES OF SIGNIFCANCE BY ARGUMENT REDUCTION */ /* PRODUCE LESS THAN HALF OF MACHINE ACCURACY */ /* IERR=4, CABS(Z) TOO LARGE - NO COMPUTATION */ /* COMPLETE LOSS OF ACCURACY BY ARGUMENT */ /* REDUCTION */ /* IERR=5, ERROR - NO COMPUTATION, */ /* ALGORITHM TERMINATION CONDITION NOT MET */ /* ***LONG DESCRIPTION */ /* AI AND DAI ARE COMPUTED FOR CABS(Z).GT.1.0 FROM THE K BESSEL */ /* FUNCTIONS BY */ /* AI(Z)=C*SQRT(Z)*K(1/3,ZTA) , DAI(Z)=-C*Z*K(2/3,ZTA) */ /* C=1.0/(PI*SQRT(3.0)) */ /* ZTA=(2/3)*Z**(3/2) */ /* WITH THE POWER SERIES FOR CABS(Z).LE.1.0. */ /* IN MOST COMPLEX VARIABLE COMPUTATION, ONE MUST EVALUATE ELE- */ /* MENTARY FUNCTIONS. WHEN THE MAGNITUDE OF Z IS LARGE, LOSSES */ /* OF SIGNIFICANCE BY ARGUMENT REDUCTION OCCUR. CONSEQUENTLY, IF */ /* THE MAGNITUDE OF ZETA=(2/3)*Z**1.5 EXCEEDS U1=SQRT(0.5/UR), */ /* THEN LOSSES EXCEEDING HALF PRECISION ARE LIKELY AND AN ERROR */ /* FLAG IERR=3 IS TRIGGERED WHERE UR=R1MACH(4)=UNIT ROUNDOFF. */ /* ALSO, IF THE MAGNITUDE OF ZETA IS LARGER THAN U2=0.5/UR, THEN */ /* ALL SIGNIFICANCE IS LOST AND IERR=4. IN ORDER TO USE THE INT */ /* FUNCTION, ZETA MUST BE FURTHER RESTRICTED NOT TO EXCEED THE */ /* LARGEST INTEGER, U3=I1MACH(9). THUS, THE MAGNITUDE OF ZETA */ /* MUST BE RESTRICTED BY MIN(U2,U3). ON 32 BIT MACHINES, U1,U2, */ /* AND U3 ARE APPROXIMATELY 2.0E+3, 4.2E+6, 2.1E+9 IN SINGLE */ /* PRECISION ARITHMETIC AND 1.3E+8, 1.8E+16, 2.1E+9 IN DOUBLE */ /* PRECISION ARITHMETIC RESPECTIVELY. THIS MAKES U2 AND U3 LIMIT- */ /* ING IN THEIR RESPECTIVE ARITHMETICS. THIS MEANS THAT THE MAG- */ /* NITUDE OF Z CANNOT EXCEED 3.1E+4 IN SINGLE AND 2.1E+6 IN */ /* DOUBLE PRECISION ARITHMETIC. THIS ALSO MEANS THAT ONE CAN */ /* EXPECT TO RETAIN, IN THE WORST CASES ON 32 BIT MACHINES, */ /* NO DIGITS IN SINGLE PRECISION AND ONLY 7 DIGITS IN DOUBLE */ /* PRECISION ARITHMETIC. SIMILAR CONSIDERATIONS HOLD FOR OTHER */ /* MACHINES. */ /* THE APPROXIMATE RELATIVE ERROR IN THE MAGNITUDE OF A COMPLEX */ /* BESSEL FUNCTION CAN BE EXPRESSED BY P*10**S WHERE P=MAX(UNIT */ /* ROUNDOFF,1.0E-18) IS THE NOMINAL PRECISION AND 10**S REPRE- */ /* SENTS THE INCREASE IN ERROR DUE TO ARGUMENT REDUCTION IN THE */ /* ELEMENTARY FUNCTIONS. HERE, S=MAX(1,ABS(LOG10(CABS(Z))), */ /* ABS(LOG10(FNU))) APPROXIMATELY (I.E. S=MAX(1,ABS(EXPONENT OF */ /* CABS(Z),ABS(EXPONENT OF FNU)) ). HOWEVER, THE PHASE ANGLE MAY */ /* HAVE ONLY ABSOLUTE ACCURACY. THIS IS MOST LIKELY TO OCCUR WHEN */ /* ONE COMPONENT (IN ABSOLUTE VALUE) IS LARGER THAN THE OTHER BY */ /* SEVERAL ORDERS OF MAGNITUDE. IF ONE COMPONENT IS 10**K LARGER */ /* THAN THE OTHER, THEN ONE CAN EXPECT ONLY MAX(ABS(LOG10(P))-K, */ /* 0) SIGNIFICANT DIGITS; OR, STATED ANOTHER WAY, WHEN K EXCEEDS */ /* THE EXPONENT OF P, NO SIGNIFICANT DIGITS REMAIN IN THE SMALLER */ /* COMPONENT. HOWEVER, THE PHASE ANGLE RETAINS ABSOLUTE ACCURACY */ /* BECAUSE, IN COMPLEX ARITHMETIC WITH PRECISION P, THE SMALLER */ /* COMPONENT WILL NOT (AS A RULE) DECREASE BELOW P TIMES THE */ /* MAGNITUDE OF THE LARGER COMPONENT. IN THESE EXTREME CASES, */ /* THE PRINCIPAL PHASE ANGLE IS ON THE ORDER OF +P, -P, PI/2-P, */ /* OR -PI/2+P. */ /* ***REFERENCES HANDBOOK OF MATHEMATICAL FUNCTIONS BY M. ABRAMOWITZ */ /* AND I. A. STEGUN, NBS AMS SERIES 55, U.S. DEPT. OF */ /* COMMERCE, 1955. */ /* COMPUTATION OF BESSEL FUNCTIONS OF COMPLEX ARGUMENT */ /* AND LARGE ORDER BY D. E. AMOS, SAND83-0643, MAY, 1983 */ /* A SUBROUTINE PACKAGE FOR BESSEL FUNCTIONS OF A COMPLEX */ /* ARGUMENT AND NONNEGATIVE ORDER BY D. E. AMOS, SAND85- */ /* 1018, MAY, 1985 */ /* A PORTABLE PACKAGE FOR BESSEL FUNCTIONS OF A COMPLEX */ /* ARGUMENT AND NONNEGATIVE ORDER BY D. E. AMOS, ACM */ /* TRANS. MATH. SOFTWARE, VOL. 12, NO. 3, SEPTEMBER 1986, */ /* PP 265-273. */ /* ***ROUTINES CALLED CACAI,CBKNU,I1MACH,R1MACH */ /* ***END PROLOGUE CAIRY */ /* ***FIRST EXECUTABLE STATEMENT CAIRY */ *ierr = 0; *nz = 0; if(*id < 0 || *id > 1) { *ierr = 1; } if(*kode < 1 || *kode > 2) { *ierr = 1; } if(*ierr != 0) { return 0; } az = c_abs(z__); /* Computing MAX */ r__1 = r1mach_(&c__4); tol = max(r__1, (float)1e-18); fid = (float)(*id); if(az > (float)1.) { goto L60; } /* ----------------------------------------------------------------------- */ /* POWER SERIES FOR CABS(Z).LE.1. */ /* ----------------------------------------------------------------------- */ s1.real() = cone.real(), s1.imag() = cone.imag(); s2.real() = cone.real(), s2.imag() = cone.imag(); if(az < tol) { goto L160; } aa = az * az; if(aa < tol / az) { goto L40; } trm1.real() = cone.real(), trm1.imag() = cone.imag(); trm2.real() = cone.real(), trm2.imag() = cone.imag(); atrm = (float)1.; q__2.real() = z__->real() * z__->real() - z__->imag() * z__->imag(), q__2.imag() = z__->real() * z__->imag() + z__->imag() * z__->real(); q__1.real() = q__2.real() * z__->real() - q__2.imag() * z__->imag(), q__1.imag() = q__2.real() * z__->imag() + q__2.imag() * z__->real(); z3.real() = q__1.real(), z3.imag() = q__1.imag(); az3 = az * aa; ak = fid + (float)2.; bk = (float)3. - fid - fid; ck = (float)4. - fid; dk = fid + (float)3. + fid; d1 = ak * dk; d2 = bk * ck; ad = std::min(d1, d2); ak = fid * (float)9. + (float)24.; bk = (float)30. - fid * (float)9.; z3r = z3.real(); z3i = r_imag(&z3); for(k = 1; k <= 25; ++k) { r__1 = z3r / d1; r__2 = z3i / d1; q__2.real() = r__1, q__2.imag() = r__2; q__1.real() = trm1.real() * q__2.real() - trm1.imag() * q__2.imag(), q__1.imag() = trm1.real() * q__2.imag() + trm1.imag() * q__2.real(); trm1.real() = q__1.real(), trm1.imag() = q__1.imag(); q__1.real() = s1.real() + trm1.real(), q__1.imag() = s1.imag() + trm1.imag(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); r__1 = z3r / d2; r__2 = z3i / d2; q__2.real() = r__1, q__2.imag() = r__2; q__1.real() = trm2.real() * q__2.real() - trm2.imag() * q__2.imag(), q__1.imag() = trm2.real() * q__2.imag() + trm2.imag() * q__2.real(); trm2.real() = q__1.real(), trm2.imag() = q__1.imag(); q__1.real() = s2.real() + trm2.real(), q__1.imag() = s2.imag() + trm2.imag(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); atrm = atrm * az3 / ad; d1 += ak; d2 += bk; ad = std::min(d1, d2); if(atrm < tol * ad) { goto L40; } ak += (float)18.; bk += (float)18.; /* L30: */ } L40: if(*id == 1) { goto L50; } q__3.real() = c1, q__3.imag() = (float)0.; q__2.real() = s1.real() * q__3.real() - s1.imag() * q__3.imag(), q__2.imag() = s1.real() * q__3.imag() + s1.imag() * q__3.real(); q__5.real() = z__->real() * s2.real() - z__->imag() * s2.imag(), q__5.imag() = z__->real() * s2.imag() + z__->imag() * s2.real(); q__6.real() = c2, q__6.imag() = (float)0.; q__4.real() = q__5.real() * q__6.real() - q__5.imag() * q__6.imag(), q__4.imag() = q__5.real() * q__6.imag() + q__5.imag() * q__6.real(); q__1.real() = q__2.real() - q__4.real(), q__1.imag() = q__2.imag() - q__4.imag(); ai->real() = q__1.real(), ai->imag() = q__1.imag(); if(*kode == 1) { return 0; } c_sqrt(&q__3, z__); q__2.real() = z__->real() * q__3.real() - z__->imag() * q__3.imag(), q__2.imag() = z__->real() * q__3.imag() + z__->imag() * q__3.real(); q__4.real() = tth, q__4.imag() = (float)0.; q__1.real() = q__2.real() * q__4.real() - q__2.imag() * q__4.imag(), q__1.imag() = q__2.real() * q__4.imag() + q__2.imag() * q__4.real(); zta.real() = q__1.real(), zta.imag() = q__1.imag(); c_exp(&q__2, &zta); q__1.real() = ai->real() * q__2.real() - ai->imag() * q__2.imag(), q__1.imag() = ai->real() * q__2.imag() + ai->imag() * q__2.real(); ai->real() = q__1.real(), ai->imag() = q__1.imag(); return 0; L50: q__2.real() = -s2.real(), q__2.imag() = -s2.imag(); q__3.real() = c2, q__3.imag() = (float)0.; q__1.real() = q__2.real() * q__3.real() - q__2.imag() * q__3.imag(), q__1.imag() = q__2.real() * q__3.imag() + q__2.imag() * q__3.real(); ai->real() = q__1.real(), ai->imag() = q__1.imag(); if(az > tol) { q__4.real() = z__->real() * z__->real() - z__->imag() * z__->imag(), q__4.imag() = z__->real() * z__->imag() + z__->imag() * z__->real(); q__3.real() = q__4.real() * s1.real() - q__4.imag() * s1.imag(), q__3.imag() = q__4.real() * s1.imag() + q__4.imag() * s1.real(); r__1 = c1 / (fid + (float)1.); q__5.real() = r__1, q__5.imag() = (float)0.; q__2.real() = q__3.real() * q__5.real() - q__3.imag() * q__5.imag(), q__2.imag() = q__3.real() * q__5.imag() + q__3.imag() * q__5.real(); q__1.real() = ai->real() + q__2.real(), q__1.imag() = ai->imag() + q__2.imag(); ai->real() = q__1.real(), ai->imag() = q__1.imag(); } if(*kode == 1) { return 0; } c_sqrt(&q__3, z__); q__2.real() = z__->real() * q__3.real() - z__->imag() * q__3.imag(), q__2.imag() = z__->real() * q__3.imag() + z__->imag() * q__3.real(); q__4.real() = tth, q__4.imag() = (float)0.; q__1.real() = q__2.real() * q__4.real() - q__2.imag() * q__4.imag(), q__1.imag() = q__2.real() * q__4.imag() + q__2.imag() * q__4.real(); zta.real() = q__1.real(), zta.imag() = q__1.imag(); c_exp(&q__2, &zta); q__1.real() = ai->real() * q__2.real() - ai->imag() * q__2.imag(), q__1.imag() = ai->real() * q__2.imag() + ai->imag() * q__2.real(); ai->real() = q__1.real(), ai->imag() = q__1.imag(); return 0; /* ----------------------------------------------------------------------- */ /* CASE FOR CABS(Z).GT.1.0 */ /* ----------------------------------------------------------------------- */ L60: fnu = (fid + (float)1.) / (float)3.; /* ----------------------------------------------------------------------- */ /* SET PARAMETERS RELATED TO MACHINE CONSTANTS. */ /* TOL IS THE APPROXIMATE UNIT ROUNDOFF LIMITED TO 1.0E-18. */ /* ELIM IS THE APPROXIMATE EXPONENTIAL OVER- AND UNDERFLOW LIMIT. */ /* EXP(-ELIM).LT.EXP(-ALIM)=EXP(-ELIM)/TOL AND */ /* EXP(ELIM).GT.EXP(ALIM)=EXP(ELIM)*TOL ARE INTERVALS NEAR */ /* UNDERFLOW AND OVERFLOW LIMITS WHERE SCALED ARITHMETIC IS DONE. */ /* RL IS THE LOWER BOUNDARY OF THE ASYMPTOTIC EXPANSION FOR LARGE Z. */ /* DIG = NUMBER OF BASE 10 DIGITS IN TOL = 10**(-DIG). */ /* ----------------------------------------------------------------------- */ k1 = i1mach_(&c__12); k2 = i1mach_(&c__13); r1m5 = r1mach_(&c__5); /* Computing MIN */ i__1 = abs(k1), i__2 = abs(k2); k = std::min(i__1, i__2); elim = ((float)k * r1m5 - (float)3.) * (float)2.303; k1 = i1mach_(&c__11) - 1; aa = r1m5 * (float)k1; dig = std::min(aa, (float)18.); aa *= (float)2.303; /* Computing MAX */ r__1 = -aa; alim = elim + max(r__1, (float)-41.45); rl = dig * (float)1.2 + (float)3.; alaz = log(az); /* ----------------------------------------------------------------------- */ /* TEST FOR RANGE */ /* ----------------------------------------------------------------------- */ aa = (float).5 / tol; bb = (float)i1mach_(&c__9) * (float).5; aa = std::min(aa, bb); d__1 = (double)aa; d__2 = (double)tth; aa = pow_dd(&d__1, &d__2); if(az > aa) { goto L260; } aa = sqrt(aa); if(az > aa) { *ierr = 3; } c_sqrt(&q__1, z__); csq.real() = q__1.real(), csq.imag() = q__1.imag(); q__2.real() = z__->real() * csq.real() - z__->imag() * csq.imag(), q__2.imag() = z__->real() * csq.imag() + z__->imag() * csq.real(); q__3.real() = tth, q__3.imag() = (float)0.; q__1.real() = q__2.real() * q__3.real() - q__2.imag() * q__3.imag(), q__1.imag() = q__2.real() * q__3.imag() + q__2.imag() * q__3.real(); zta.real() = q__1.real(), zta.imag() = q__1.imag(); /* ----------------------------------------------------------------------- */ /* RE(ZTA).LE.0 WHEN RE(Z).LT.0, ESPECIALLY WHEN IM(Z) IS SMALL */ /* ----------------------------------------------------------------------- */ iflag = 0; sfac = (float)1.; zi = r_imag(z__); zr = z__->real(); ak = r_imag(&zta); if(zr >= (float)0.) { goto L70; } bk = zta.real(); ck = -abs(bk); q__1.real() = ck, q__1.imag() = ak; zta.real() = q__1.real(), zta.imag() = q__1.imag(); L70: if(zi != (float)0.) { goto L80; } if(zr > (float)0.) { goto L80; } q__1.real() = (float)0., q__1.imag() = ak; zta.real() = q__1.real(), zta.imag() = q__1.imag(); L80: aa = zta.real(); if(aa >= (float)0. && zr > (float)0.) { goto L100; } if(*kode == 2) { goto L90; } /* ----------------------------------------------------------------------- */ /* OVERFLOW TEST */ /* ----------------------------------------------------------------------- */ if(aa > -alim) { goto L90; } aa = -aa + alaz * (float).25; iflag = 1; sfac = tol; if(aa > elim) { goto L240; } L90: /* ----------------------------------------------------------------------- */ /* CBKNU AND CACAI RETURN EXP(ZTA)*K(FNU,ZTA) ON KODE=2 */ /* ----------------------------------------------------------------------- */ mr = 1; if(zi < (float)0.) { mr = -1; } cacai_(&zta, &fnu, kode, &mr, &c__1, cy, &nn, &rl, &tol, &elim, &alim); if(nn < 0) { goto L250; } *nz += nn; goto L120; L100: if(*kode == 2) { goto L110; } /* ----------------------------------------------------------------------- */ /* UNDERFLOW TEST */ /* ----------------------------------------------------------------------- */ if(aa < alim) { goto L110; } aa = -aa - alaz * (float).25; iflag = 2; sfac = (float)1. / tol; if(aa < -elim) { goto L180; } L110: cbknu_(&zta, &fnu, kode, &c__1, cy, nz, &tol, &elim, &alim); L120: q__2.real() = coef, q__2.imag() = (float)0.; q__1.real() = cy[0].real() * q__2.real() - cy[0].imag() * q__2.imag(), q__1.imag() = cy[0].real() * q__2.imag() + cy[0].imag() * q__2.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); if(iflag != 0) { goto L140; } if(*id == 1) { goto L130; } q__1.real() = csq.real() * s1.real() - csq.imag() * s1.imag(), q__1.imag() = csq.real() * s1.imag() + csq.imag() * s1.real(); ai->real() = q__1.real(), ai->imag() = q__1.imag(); return 0; L130: q__2.real() = -z__->real(), q__2.imag() = -z__->imag(); q__1.real() = q__2.real() * s1.real() - q__2.imag() * s1.imag(), q__1.imag() = q__2.real() * s1.imag() + q__2.imag() * s1.real(); ai->real() = q__1.real(), ai->imag() = q__1.imag(); return 0; L140: q__2.real() = sfac, q__2.imag() = (float)0.; q__1.real() = s1.real() * q__2.real() - s1.imag() * q__2.imag(), q__1.imag() = s1.real() * q__2.imag() + s1.imag() * q__2.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); if(*id == 1) { goto L150; } q__1.real() = s1.real() * csq.real() - s1.imag() * csq.imag(), q__1.imag() = s1.real() * csq.imag() + s1.imag() * csq.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); r__1 = (float)1. / sfac; q__2.real() = r__1, q__2.imag() = (float)0.; q__1.real() = s1.real() * q__2.real() - s1.imag() * q__2.imag(), q__1.imag() = s1.real() * q__2.imag() + s1.imag() * q__2.real(); ai->real() = q__1.real(), ai->imag() = q__1.imag(); return 0; L150: q__2.real() = -s1.real(), q__2.imag() = -s1.imag(); q__1.real() = q__2.real() * z__->real() - q__2.imag() * z__->imag(), q__1.imag() = q__2.real() * z__->imag() + q__2.imag() * z__->real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); r__1 = (float)1. / sfac; q__2.real() = r__1, q__2.imag() = (float)0.; q__1.real() = s1.real() * q__2.real() - s1.imag() * q__2.imag(), q__1.imag() = s1.real() * q__2.imag() + s1.imag() * q__2.real(); ai->real() = q__1.real(), ai->imag() = q__1.imag(); return 0; L160: aa = r1mach_(&c__1) * (float)1e3; s1.real() = (float)0., s1.imag() = (float)0.; if(*id == 1) { goto L170; } if(az > aa) { q__2.real() = c2, q__2.imag() = (float)0.; q__1.real() = q__2.real() * z__->real() - q__2.imag() * z__->imag(), q__1.imag() = q__2.real() * z__->imag() + q__2.imag() * z__->real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); } q__2.real() = c1, q__2.imag() = (float)0.; q__1.real() = q__2.real() - s1.real(), q__1.imag() = q__2.imag() - s1.imag(); ai->real() = q__1.real(), ai->imag() = q__1.imag(); return 0; L170: q__2.real() = c2, q__2.imag() = (float)0.; q__1.real() = -q__2.real(), q__1.imag() = -q__2.imag(); ai->real() = q__1.real(), ai->imag() = q__1.imag(); aa = sqrt(aa); if(az > aa) { q__2.real() = z__->real() * z__->real() - z__->imag() * z__->imag(), q__2.imag() = z__->real() * z__->imag() + z__->imag() * z__->real(); q__1.real() = q__2.real() * (float).5 - q__2.imag() * (float)0., q__1.imag() = q__2.real() * (float)0. + q__2.imag() * (float).5; s1.real() = q__1.real(), s1.imag() = q__1.imag(); } q__3.real() = c1, q__3.imag() = (float)0.; q__2.real() = s1.real() * q__3.real() - s1.imag() * q__3.imag(), q__2.imag() = s1.real() * q__3.imag() + s1.imag() * q__3.real(); q__1.real() = ai->real() + q__2.real(), q__1.imag() = ai->imag() + q__2.imag(); ai->real() = q__1.real(), ai->imag() = q__1.imag(); return 0; L180: *nz = 1; ai->real() = (float)0., ai->imag() = (float)0.; return 0; L240: *nz = 0; *ierr = 2; return 0; L250: if(nn == -1) { goto L240; } *nz = 0; *ierr = 5; return 0; L260: *ierr = 4; *nz = 0; return 0; } /* cairy_ */ static int casyi_(System::Complex<float>* z__, float* fnu, int32* kode, int32* n, System::Complex<float>* y, int32* nz, float* rl, float* tol, float* elim, float* alim) { /* Initialized data */ static float pi = (float)3.14159265358979324; static float rtpi = (float).159154943091895336; static System::Complex<float> czero = {(float)0., (float)0.}; static System::Complex<float> cone = {(float)1., (float)0.}; /* System generated locals */ int32 i__1, i__2, i__3, i__4; float r__1; System::Complex<float> q__1, q__2, q__3, q__4, q__5, q__6; int32 i__, j, k, m; float s, x; System::Complex<float> p1, s2; float aa, bb; int32 ib; float ak, bk; System::Complex<float> ck, dk; int32 il, jl; float az; int32 nn; System::Complex<float> cz, ez, rz; float yy; System::Complex<float> ak1, cs1, cs2; float fdn, arg, acz, aez, arm, sgn; int32 inu; float sqk, dnu2, rtr1, dfnu, atol; int32 koded; /* *********************************************************************72 */ /* c CASYI computs the I Bessel function. */ /* ***BEGIN PROLOGUE CASYI */ /* ***REFER TO CBESI,CBESK */ /* CASYI COMPUTES THE I BESSEL FUNCTION FOR REAL(Z).GE.0.0 BY */ /* MEANS OF THE ASYMPTOTIC EXPANSION FOR LARGE CABS(Z) IN THE */ /* REGION CABS(Z).GT.MAX(RL,FNU*FNU/2). NZ=0 IS A NORMAL RETURN. */ /* NZ.LT.0 INDICATES AN OVERFLOW ON KODE=1. */ /* ***ROUTINES CALLED R1MACH */ /* ***END PROLOGUE CASYI */ /* Parameter adjustments */ --y; /* Function Body */ *nz = 0; az = c_abs(z__); x = z__->real(); arm = r1mach_(&c__1) * (float)1e3; rtr1 = sqrt(arm); il = std::min(2L, *n); dfnu = *fnu + (float)(*n - il); /* ----------------------------------------------------------------------- */ /* OVERFLOW TEST */ /* ----------------------------------------------------------------------- */ q__2.real() = rtpi, q__2.imag() = (float)0.; c_div(&q__1, &q__2, z__); ak1.real() = q__1.real(), ak1.imag() = q__1.imag(); c_sqrt(&q__1, &ak1); ak1.real() = q__1.real(), ak1.imag() = q__1.imag(); cz.real() = z__->real(), cz.imag() = z__->imag(); if(*kode == 2) { q__2.real() = x, q__2.imag() = (float)0.; q__1.real() = z__->real() - q__2.real(), q__1.imag() = z__->imag() - q__2.imag(); cz.real() = q__1.real(), cz.imag() = q__1.imag(); } acz = cz.real(); if(abs(acz) > *elim) { goto L80; } dnu2 = dfnu + dfnu; koded = 1; if(abs(acz) > *alim && *n > 2) { goto L10; } koded = 0; c_exp(&q__2, &cz); q__1.real() = ak1.real() * q__2.real() - ak1.imag() * q__2.imag(), q__1.imag() = ak1.real() * q__2.imag() + ak1.imag() * q__2.real(); ak1.real() = q__1.real(), ak1.imag() = q__1.imag(); L10: fdn = (float)0.; if(dnu2 > rtr1) { fdn = dnu2 * dnu2; } q__1.real() = z__->real() * (float)8. - z__->imag() * (float)0., q__1.imag() = z__->real() * (float)0. + z__->imag() * (float)8.; ez.real() = q__1.real(), ez.imag() = q__1.imag(); /* ----------------------------------------------------------------------- */ /* WHEN Z IS IMAGINARY, THE ERROR TEST MUST BE MADE RELATIVE TO THE */ /* FIRST RECIPROCAL POWER SINCE THIS IS THE LEADING TERM OF THE */ /* EXPANSION FOR THE IMAGINARY PART. */ /* ----------------------------------------------------------------------- */ aez = az * (float)8.; s = *tol / aez; jl = (int32)(*rl + *rl) + 2; yy = r_imag(z__); p1.real() = czero.real(), p1.imag() = czero.imag(); if(yy == (float)0.) { goto L20; } /* ----------------------------------------------------------------------- */ /* CALCULATE EXP(PI*(0.5+FNU+N-IL)*I) TO MINIMIZE LOSSES OF */ /* SIGNIFICANCE WHEN FNU OR N IS LARGE */ /* ----------------------------------------------------------------------- */ inu = (int32)(*fnu); arg = (*fnu - (float)inu) * pi; inu = inu + *n - il; ak = -sin(arg); bk = cos(arg); if(yy < (float)0.) { bk = -bk; } q__1.real() = ak, q__1.imag() = bk; p1.real() = q__1.real(), p1.imag() = q__1.imag(); if(inu % 2 == 1) { q__1.real() = -p1.real(), q__1.imag() = -p1.imag(); p1.real() = q__1.real(), p1.imag() = q__1.imag(); } L20: i__1 = il; for(k = 1; k <= i__1; ++k) { sqk = fdn - (float)1.; atol = s * abs(sqk); sgn = (float)1.; cs1.real() = cone.real(), cs1.imag() = cone.imag(); cs2.real() = cone.real(), cs2.imag() = cone.imag(); ck.real() = cone.real(), ck.imag() = cone.imag(); ak = (float)0.; aa = (float)1.; bb = aez; dk.real() = ez.real(), dk.imag() = ez.imag(); i__2 = jl; for(j = 1; j <= i__2; ++j) { q__3.real() = sqk, q__3.imag() = (float)0.; q__2.real() = ck.real() * q__3.real() - ck.imag() * q__3.imag(), q__2.imag() = ck.real() * q__3.imag() + ck.imag() * q__3.real(); c_div(&q__1, &q__2, &dk); ck.real() = q__1.real(), ck.imag() = q__1.imag(); q__1.real() = cs2.real() + ck.real(), q__1.imag() = cs2.imag() + ck.imag(); cs2.real() = q__1.real(), cs2.imag() = q__1.imag(); sgn = -sgn; q__3.real() = sgn, q__3.imag() = (float)0.; q__2.real() = ck.real() * q__3.real() - ck.imag() * q__3.imag(), q__2.imag() = ck.real() * q__3.imag() + ck.imag() * q__3.real(); q__1.real() = cs1.real() + q__2.real(), q__1.imag() = cs1.imag() + q__2.imag(); cs1.real() = q__1.real(), cs1.imag() = q__1.imag(); q__1.real() = dk.real() + ez.real(), q__1.imag() = dk.imag() + ez.imag(); dk.real() = q__1.real(), dk.imag() = q__1.imag(); aa = aa * abs(sqk) / bb; bb += aez; ak += (float)8.; sqk -= ak; if(aa <= atol) { goto L40; } /* L30: */ } goto L90; L40: s2.real() = cs1.real(), s2.imag() = cs1.imag(); if(x + x < *elim) { q__3.real() = p1.real() * cs2.real() - p1.imag() * cs2.imag(), q__3.imag() = p1.real() * cs2.imag() + p1.imag() * cs2.real(); q__6.real() = -z__->real(), q__6.imag() = -z__->imag(); q__5.real() = q__6.real() - z__->real(), q__5.imag() = q__6.imag() - z__->imag(); c_exp(&q__4, &q__5); q__2.real() = q__3.real() * q__4.real() - q__3.imag() * q__4.imag(), q__2.imag() = q__3.real() * q__4.imag() + q__3.imag() * q__4.real(); q__1.real() = s2.real() + q__2.real(), q__1.imag() = s2.imag() + q__2.imag(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); } fdn = fdn + dfnu * (float)8. + (float)4.; q__1.real() = -p1.real(), q__1.imag() = -p1.imag(); p1.real() = q__1.real(), p1.imag() = q__1.imag(); m = *n - il + k; i__2 = m; q__1.real() = s2.real() * ak1.real() - s2.imag() * ak1.imag(), q__1.imag() = s2.real() * ak1.imag() + s2.imag() * ak1.real(); y[i__2].real() = q__1.real(), y[i__2].imag() = q__1.imag(); /* L50: */ } if(*n <= 2) { return 0; } nn = *n; k = nn - 2; ak = (float)k; q__2.real() = cone.real() + cone.real(), q__2.imag() = cone.imag() + cone.imag(); c_div(&q__1, &q__2, z__); rz.real() = q__1.real(), rz.imag() = q__1.imag(); ib = 3; i__1 = nn; for(i__ = ib; i__ <= i__1; ++i__) { i__2 = k; r__1 = ak + *fnu; q__4.real() = r__1, q__4.imag() = (float)0.; q__3.real() = q__4.real() * rz.real() - q__4.imag() * rz.imag(), q__3.imag() = q__4.real() * rz.imag() + q__4.imag() * rz.real(); i__3 = k + 1; q__2.real() = q__3.real() * y[i__3].real() - q__3.imag() * y[i__3].imag(), q__2.imag() = q__3.real() * y[i__3].imag() + q__3.imag() * y[i__3].real(); i__4 = k + 2; q__1.real() = q__2.real() + y[i__4].real(), q__1.imag() = q__2.imag() + y[i__4].imag(); y[i__2].real() = q__1.real(), y[i__2].imag() = q__1.imag(); ak += (float)-1.; --k; /* L60: */ } if(koded == 0) { return 0; } c_exp(&q__1, &cz); ck.real() = q__1.real(), ck.imag() = q__1.imag(); i__1 = nn; for(i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; i__3 = i__; q__1.real() = y[i__3].real() * ck.real() - y[i__3].imag() * ck.imag(), q__1.imag() = y[i__3].real() * ck.imag() + y[i__3].imag() * ck.real(); y[i__2].real() = q__1.real(), y[i__2].imag() = q__1.imag(); /* L70: */ } return 0; L80: *nz = -1; return 0; L90: *nz = -2; return 0; } /* casyi_ */ static int cbesh_(System::Complex<float>* z__, float* fnu, int32* kode, int32* m, int32* n, System::Complex<float>* cy, int32* nz, int32* ierr) { /* Initialized data */ static float hpi = (float)1.57079632679489662; /* System generated locals */ int32 i__1, i__2; float r__1, r__2; System::Complex<float> q__1, q__2; int32 i__, k, k1, k2; float aa, bb, fn; int32 mm; float az; int32 ir; float rl; int32 mr, nn, nw; float xn, yn; System::Complex<float> zn, zt; float xx, yy, dig, arg, aln, fmm, cpn, r1m5, ufl, sgn; int32 nuf, inu; float tol, spn, alim, elim; System::Complex<float> csgn; float atol, rhpi; int32 inuh; float fnul, rtol; float ascle; /* *********************************************************************72 */ /* c CBESH computes a sequence of System::Complex<float> Hankel functions. */ /* ***BEGIN PROLOGUE CBESH */ /* ***DATE WRITTEN 830501 (YYMMDD) */ /* ***REVISION DATE 890801, 930101 (YYMMDD) */ /* ***CATEGORY NO. B5K */ /* ***KEYWORDS H-BESSEL FUNCTIONS,BESSEL FUNCTIONS OF COMPLEX ARGUMENT, */ /* BESSEL FUNCTIONS OF THIRD KIND,HANKEL FUNCTIONS */ /* ***AUTHOR AMOS, DONALD E., SANDIA NATIONAL LABORATORIES */ /* ***PURPOSE TO COMPUTE THE H-BESSEL FUNCTIONS OF A COMPLEX ARGUMENT */ /* ***DESCRIPTION */ /* ON KODE=1, CBESH COMPUTES AN N MEMBER SEQUENCE OF COMPLEX */ /* HANKEL (BESSEL) FUNCTIONS CY(J)=H(M,FNU+J-1,Z) FOR KINDS M=1 */ /* OR 2, REAL, NONNEGATIVE ORDERS FNU+J-1, J=1,...,N, AND COMPLEX */ /* Z.NE.CMPLX(0.0E0,0.0E0) IN THE CUT PLANE -PI.LT.ARG(Z).LE.PI. */ /* ON KODE=2, CBESH COMPUTES THE SCALED HANKEL FUNCTIONS */ /* CY(I)=H(M,FNU+J-1,Z)*EXP(-MM*Z*I) MM=3-2M, I**2=-1. */ /* WHICH REMOVES THE EXPONENTIAL BEHAVIOR IN BOTH THE UPPER */ /* AND LOWER HALF PLANES. DEFINITIONS AND NOTATION ARE FOUND IN */ /* THE NBS HANDBOOK OF MATHEMATICAL FUNCTIONS (REF. 1). */ /* INPUT */ /* Z - Z=CMPLX(X,Y), Z.NE.CMPLX(0.,0.),-PI.LT.ARG(Z).LE.PI */ /* FNU - ORDER OF INITIAL H FUNCTION, FNU.GE.0.0E0 */ /* KODE - A PARAMETER TO INDICATE THE SCALING OPTION */ /* KODE= 1 RETURNS */ /* CY(J)=H(M,FNU+J-1,Z), J=1,...,N */ /* = 2 RETURNS */ /* CY(J)=H(M,FNU+J-1,Z)*EXP(-I*Z*(3-2M)) */ /* J=1,...,N , I**2=-1 */ /* M - KIND OF HANKEL FUNCTION, M=1 OR 2 */ /* N - NUMBER OF MEMBERS OF THE SEQUENCE, N.GE.1 */ /* OUTPUT */ /* CY - A COMPLEX VECTOR WHOSE FIRST N COMPONENTS CONTAIN */ /* VALUES FOR THE SEQUENCE */ /* CY(J)=H(M,FNU+J-1,Z) OR */ /* CY(J)=H(M,FNU+J-1,Z)*EXP(-I*Z*(3-2M)) J=1,...,N */ /* DEPENDING ON KODE, I**2=-1. */ /* NZ - NUMBER OF COMPONENTS SET TO ZERO DUE TO UNDERFLOW, */ /* NZ= 0 , NORMAL RETURN */ /* NZ.GT.0 , FIRST NZ COMPONENTS OF CY SET TO ZERO */ /* DUE TO UNDERFLOW, CY(J)=CMPLX(0.0,0.0) */ /* J=1,...,NZ WHEN Y.GT.0.0 AND M=1 OR */ /* Y.LT.0.0 AND M=2. FOR THE COMPLMENTARY */ /* HALF PLANES, NZ STATES ONLY THE NUMBER */ /* OF UNDERFLOWS. */ /* IERR -ERROR FLAG */ /* IERR=0, NORMAL RETURN - COMPUTATION COMPLETED */ /* IERR=1, INPUT ERROR - NO COMPUTATION */ /* IERR=2, OVERFLOW - NO COMPUTATION, FNU+N-1 TOO */ /* LARGE OR CABS(Z) TOO SMALL OR BOTH */ /* IERR=3, CABS(Z) OR FNU+N-1 LARGE - COMPUTATION DONE */ /* BUT LOSSES OF SIGNIFCANCE BY ARGUMENT */ /* REDUCTION PRODUCE LESS THAN HALF OF MACHINE */ /* ACCURACY */ /* IERR=4, CABS(Z) OR FNU+N-1 TOO LARGE - NO COMPUTA- */ /* TION BECAUSE OF COMPLETE LOSSES OF SIGNIFI- */ /* CANCE BY ARGUMENT REDUCTION */ /* IERR=5, ERROR - NO COMPUTATION, */ /* ALGORITHM TERMINATION CONDITION NOT MET */ /* ***LONG DESCRIPTION */ /* THE COMPUTATION IS CARRIED OUT BY THE RELATION */ /* H(M,FNU,Z)=(1/MP)*EXP(-MP*FNU)*K(FNU,Z*EXP(-MP)) */ /* MP=MM*HPI*I, MM=3-2*M, HPI=PI/2, I**2=-1 */ /* FOR M=1 OR 2 WHERE THE K BESSEL FUNCTION IS COMPUTED FOR THE */ /* RIGHT HALF PLANE RE(Z).GE.0.0. THE K FUNCTION IS CONTINUED */ /* TO THE LEFT HALF PLANE BY THE RELATION */ /* K(FNU,Z*EXP(MP)) = EXP(-MP*FNU)*K(FNU,Z)-MP*I(FNU,Z) */ /* MP=MR*PI*I, MR=+1 OR -1, RE(Z).GT.0, I**2=-1 */ /* WHERE I(FNU,Z) IS THE I BESSEL FUNCTION. */ /* EXPONENTIAL DECAY OF H(M,FNU,Z) OCCURS IN THE UPPER HALF Z */ /* PLANE FOR M=1 AND THE LOWER HALF Z PLANE FOR M=2. EXPONENTIAL */ /* GROWTH OCCURS IN THE COMPLEMENTARY HALF PLANES. SCALING */ /* BY EXP(-MM*Z*I) REMOVES THE EXPONENTIAL BEHAVIOR IN THE */ /* WHOLE Z PLANE FOR Z TO INFINITY. */ /* FOR NEGATIVE ORDERS,THE FORMULAE */ /* H(1,-FNU,Z) = H(1,FNU,Z)*CEXP( PI*FNU*I) */ /* H(2,-FNU,Z) = H(2,FNU,Z)*CEXP(-PI*FNU*I) */ /* I**2=-1 */ /* CAN BE USED. */ /* IN MOST COMPLEX VARIABLE COMPUTATION, ONE MUST EVALUATE ELE- */ /* MENTARY FUNCTIONS. WHEN THE MAGNITUDE OF Z OR FNU+N-1 IS */ /* LARGE, LOSSES OF SIGNIFICANCE BY ARGUMENT REDUCTION OCCUR. */ /* CONSEQUENTLY, IF EITHER ONE EXCEEDS U1=SQRT(0.5/UR), THEN */ /* LOSSES EXCEEDING HALF PRECISION ARE LIKELY AND AN ERROR FLAG */ /* IERR=3 IS TRIGGERED WHERE UR=R1MACH(4)=UNIT ROUNDOFF. ALSO */ /* IF EITHER IS LARGER THAN U2=0.5/UR, THEN ALL SIGNIFICANCE IS */ /* LOST AND IERR=4. IN ORDER TO USE THE INT FUNCTION, ARGUMENTS */ /* MUST BE FURTHER RESTRICTED NOT TO EXCEED THE LARGEST MACHINE */ /* INTEGER, U3=I1MACH(9). THUS, THE MAGNITUDE OF Z AND FNU+N-1 IS */ /* RESTRICTED BY MIN(U2,U3). ON 32 BIT MACHINES, U1,U2, AND U3 */ /* ARE APPROXIMATELY 2.0E+3, 4.2E+6, 2.1E+9 IN SINGLE PRECISION */ /* ARITHMETIC AND 1.3E+8, 1.8E+16, 2.1E+9 IN DOUBLE PRECISION */ /* ARITHMETIC RESPECTIVELY. THIS MAKES U2 AND U3 LIMITING IN */ /* THEIR RESPECTIVE ARITHMETICS. THIS MEANS THAT ONE CAN EXPECT */ /* TO RETAIN, IN THE WORST CASES ON 32 BIT MACHINES, NO DIGITS */ /* IN SINGLE AND ONLY 7 DIGITS IN DOUBLE PRECISION ARITHMETIC. */ /* SIMILAR CONSIDERATIONS HOLD FOR OTHER MACHINES. */ /* THE APPROXIMATE RELATIVE ERROR IN THE MAGNITUDE OF A COMPLEX */ /* BESSEL FUNCTION CAN BE EXPRESSED BY P*10**S WHERE P=MAX(UNIT */ /* ROUNDOFF,1.0E-18) IS THE NOMINAL PRECISION AND 10**S REPRE- */ /* SENTS THE INCREASE IN ERROR DUE TO ARGUMENT REDUCTION IN THE */ /* ELEMENTARY FUNCTIONS. HERE, S=MAX(1,ABS(LOG10(CABS(Z))), */ /* ABS(LOG10(FNU))) APPROXIMATELY (I.E. S=MAX(1,ABS(EXPONENT OF */ /* CABS(Z),ABS(EXPONENT OF FNU)) ). HOWEVER, THE PHASE ANGLE MAY */ /* HAVE ONLY ABSOLUTE ACCURACY. THIS IS MOST LIKELY TO OCCUR WHEN */ /* ONE COMPONENT (IN ABSOLUTE VALUE) IS LARGER THAN THE OTHER BY */ /* SEVERAL ORDERS OF MAGNITUDE. IF ONE COMPONENT IS 10**K LARGER */ /* THAN THE OTHER, THEN ONE CAN EXPECT ONLY MAX(ABS(LOG10(P))-K, */ /* 0) SIGNIFICANT DIGITS; OR, STATED ANOTHER WAY, WHEN K EXCEEDS */ /* THE EXPONENT OF P, NO SIGNIFICANT DIGITS REMAIN IN THE SMALLER */ /* COMPONENT. HOWEVER, THE PHASE ANGLE RETAINS ABSOLUTE ACCURACY */ /* BECAUSE, IN COMPLEX ARITHMETIC WITH PRECISION P, THE SMALLER */ /* COMPONENT WILL NOT (AS A RULE) DECREASE BELOW P TIMES THE */ /* MAGNITUDE OF THE LARGER COMPONENT. IN THESE EXTREME CASES, */ /* THE PRINCIPAL PHASE ANGLE IS ON THE ORDER OF +P, -P, PI/2-P, */ /* OR -PI/2+P. */ /* ***REFERENCES HANDBOOK OF MATHEMATICAL FUNCTIONS BY M. ABRAMOWITZ */ /* AND I. A. STEGUN, NBS AMS SERIES 55, U.S. DEPT. OF */ /* COMMERCE, 1955. */ /* COMPUTATION OF BESSEL FUNCTIONS OF COMPLEX ARGUMENT */ /* BY D. E. AMOS, SAND83-0083, MAY, 1983. */ /* COMPUTATION OF BESSEL FUNCTIONS OF COMPLEX ARGUMENT */ /* AND LARGE ORDER BY D. E. AMOS, SAND83-0643, MAY, 1983 */ /* A SUBROUTINE PACKAGE FOR BESSEL FUNCTIONS OF A COMPLEX */ /* ARGUMENT AND NONNEGATIVE ORDER BY D. E. AMOS, SAND85- */ /* 1018, MAY, 1985 */ /* A PORTABLE PACKAGE FOR BESSEL FUNCTIONS OF A COMPLEX */ /* ARGUMENT AND NONNEGATIVE ORDER BY D. E. AMOS, ACM */ /* TRANS. MATH. SOFTWARE, VOL. 12, NO. 3, SEPTEMBER 1986, */ /* PP 265-273. */ /* ***ROUTINES CALLED CACON,CBKNU,CBUNK,CUOIK,I1MACH,R1MACH */ /* ***END PROLOGUE CBESH */ /* Parameter adjustments */ --cy; /* Function Body */ /* ***FIRST EXECUTABLE STATEMENT CBESH */ *nz = 0; xx = z__->real(); yy = r_imag(z__); *ierr = 0; if(xx == (float)0. && yy == (float)0.) { *ierr = 1; } if(*fnu < (float)0.) { *ierr = 1; } if(*m < 1 || *m > 2) { *ierr = 1; } if(*kode < 1 || *kode > 2) { *ierr = 1; } if(*n < 1) { *ierr = 1; } if(*ierr != 0) { return 0; } nn = *n; /* ----------------------------------------------------------------------- */ /* SET PARAMETERS RELATED TO MACHINE CONSTANTS. */ /* TOL IS THE APPROXIMATE UNIT ROUNDOFF LIMITED TO 1.0E-18. */ /* ELIM IS THE APPROXIMATE EXPONENTIAL OVER- AND UNDERFLOW LIMIT. */ /* EXP(-ELIM).LT.EXP(-ALIM)=EXP(-ELIM)/TOL AND */ /* EXP(ELIM).GT.EXP(ALIM)=EXP(ELIM)*TOL ARE INTERVALS NEAR */ /* UNDERFLOW AND OVERFLOW LIMITS WHERE SCALED ARITHMETIC IS DONE. */ /* RL IS THE LOWER BOUNDARY OF THE ASYMPTOTIC EXPANSION FOR LARGE Z. */ /* DIG = NUMBER OF BASE 10 DIGITS IN TOL = 10**(-DIG). */ /* FNUL IS THE LOWER BOUNDARY OF THE ASYMPTOTIC SERIES FOR LARGE FNU */ /* ----------------------------------------------------------------------- */ /* Computing MAX */ r__1 = r1mach_(&c__4); tol = max(r__1, (float)1e-18); k1 = i1mach_(&c__12); k2 = i1mach_(&c__13); r1m5 = r1mach_(&c__5); /* Computing MIN */ i__1 = abs(k1), i__2 = abs(k2); k = std::min(i__1, i__2); elim = ((float)k * r1m5 - (float)3.) * (float)2.303; k1 = i1mach_(&c__11) - 1; aa = r1m5 * (float)k1; dig = std::min(aa, (float)18.); aa *= (float)2.303; /* Computing MAX */ r__1 = -aa; alim = elim + max(r__1, (float)-41.45); fnul = (dig - (float)3.) * (float)6. + (float)10.; rl = dig * (float)1.2 + (float)3.; fn = *fnu + (float)(nn - 1); mm = 3 - *m - *m; fmm = (float)mm; r__1 = -fmm; q__2.real() = (float)0., q__2.imag() = r__1; q__1.real() = z__->real() * q__2.real() - z__->imag() * q__2.imag(), q__1.imag() = z__->real() * q__2.imag() + z__->imag() * q__2.real(); zn.real() = q__1.real(), zn.imag() = q__1.imag(); xn = zn.real(); yn = r_imag(&zn); az = c_abs(z__); /* ----------------------------------------------------------------------- */ /* TEST FOR RANGE */ /* ----------------------------------------------------------------------- */ aa = (float).5 / tol; bb = (float)i1mach_(&c__9) * (float).5; aa = std::min(aa, bb); if(az > aa) { goto L240; } if(fn > aa) { goto L240; } aa = sqrt(aa); if(az > aa) { *ierr = 3; } if(fn > aa) { *ierr = 3; } /* ----------------------------------------------------------------------- */ /* OVERFLOW TEST ON THE LAST MEMBER OF THE SEQUENCE */ /* ----------------------------------------------------------------------- */ ufl = r1mach_(&c__1) * (float)1e3; if(az < ufl) { goto L220; } if(*fnu > fnul) { goto L90; } if(fn <= (float)1.) { goto L70; } if(fn > (float)2.) { goto L60; } if(az > tol) { goto L70; } arg = az * (float).5; aln = -fn * log(arg); if(aln > elim) { goto L220; } goto L70; L60: cuoik_(&zn, fnu, kode, &c__2, &nn, &cy[1], &nuf, &tol, &elim, &alim); if(nuf < 0) { goto L220; } *nz += nuf; nn -= nuf; /* ----------------------------------------------------------------------- */ /* HERE NN=N OR NN=0 SINCE NUF=0,NN, OR -1 ON RETURN FROM CUOIK */ /* IF NUF=NN, THEN CY(I)=CZERO FOR ALL I */ /* ----------------------------------------------------------------------- */ if(nn == 0) { goto L130; } L70: if(xn < (float)0. || xn == (float)0. && yn < (float)0. && *m == 2) { goto L80; } /* ----------------------------------------------------------------------- */ /* RIGHT HALF PLANE COMPUTATION, XN.GE.0. .AND. (XN.NE.0. .OR. */ /* YN.GE.0. .OR. M=1) */ /* ----------------------------------------------------------------------- */ cbknu_(&zn, fnu, kode, &nn, &cy[1], nz, &tol, &elim, &alim); goto L110; /* ----------------------------------------------------------------------- */ /* LEFT HALF PLANE COMPUTATION */ /* ----------------------------------------------------------------------- */ L80: mr = -mm; cacon_(&zn, fnu, kode, &mr, &nn, &cy[1], &nw, &rl, &fnul, &tol, &elim, &alim); if(nw < 0) { goto L230; } *nz = nw; goto L110; L90: /* ----------------------------------------------------------------------- */ /* UNIFORM ASYMPTOTIC EXPANSIONS FOR FNU.GT.FNUL */ /* ----------------------------------------------------------------------- */ mr = 0; if(xn >= (float)0. && (xn != (float)0. || yn >= (float)0. || *m != 2)) { goto L100; } mr = -mm; if(xn == (float)0. && yn < (float)0.) { q__1.real() = -zn.real(), q__1.imag() = -zn.imag(); zn.real() = q__1.real(), zn.imag() = q__1.imag(); } L100: cbunk_(&zn, fnu, kode, &mr, &nn, &cy[1], &nw, &tol, &elim, &alim); if(nw < 0) { goto L230; } *nz += nw; L110: /* ----------------------------------------------------------------------- */ /* H(M,FNU,Z) = -FMM*(I/HPI)*(ZT**FNU)*K(FNU,-Z*ZT) */ /* ZT=EXP(-FMM*HPI*I) = CMPLX(0.0,-FMM), FMM=3-2*M, M=1,2 */ /* ----------------------------------------------------------------------- */ r__1 = -fmm; sgn = r_sign(&hpi, &r__1); /* ----------------------------------------------------------------------- */ /* CALCULATE EXP(FNU*HPI*I) TO MINIMIZE LOSSES OF SIGNIFICANCE */ /* WHEN FNU IS LARGE */ /* ----------------------------------------------------------------------- */ inu = (int32)(*fnu); inuh = inu / 2; ir = inu - (inuh << 1); arg = (*fnu - (float)(inu - ir)) * sgn; rhpi = (float)1. / sgn; cpn = rhpi * cos(arg); spn = rhpi * sin(arg); /* ZN = CMPLX(-SPN,CPN) */ r__1 = -spn; q__1.real() = r__1, q__1.imag() = cpn; csgn.real() = q__1.real(), csgn.imag() = q__1.imag(); /* IF (MOD(INUH,2).EQ.1) ZN = -ZN */ if(inuh % 2 == 1) { q__1.real() = -csgn.real(), q__1.imag() = -csgn.imag(); csgn.real() = q__1.real(), csgn.imag() = q__1.imag(); } r__1 = -fmm; q__1.real() = (float)0., q__1.imag() = r__1; zt.real() = q__1.real(), zt.imag() = q__1.imag(); rtol = (float)1. / tol; ascle = ufl * rtol; i__1 = nn; for(i__ = 1; i__ <= i__1; ++i__) { /* CY(I) = CY(I)*ZN */ /* ZN = ZN*ZT */ i__2 = i__; zn.real() = cy[i__2].real(), zn.imag() = cy[i__2].imag(); aa = zn.real(); bb = r_imag(&zn); atol = (float)1.; /* Computing MAX */ r__1 = abs(aa), r__2 = abs(bb); if(max(r__1, r__2) > ascle) { goto L125; } q__2.real() = rtol, q__2.imag() = (float)0.; q__1.real() = zn.real() * q__2.real() - zn.imag() * q__2.imag(), q__1.imag() = zn.real() * q__2.imag() + zn.imag() * q__2.real(); zn.real() = q__1.real(), zn.imag() = q__1.imag(); atol = tol; L125: q__1.real() = zn.real() * csgn.real() - zn.imag() * csgn.imag(), q__1.imag() = zn.real() * csgn.imag() + zn.imag() * csgn.real(); zn.real() = q__1.real(), zn.imag() = q__1.imag(); i__2 = i__; q__2.real() = atol, q__2.imag() = (float)0.; q__1.real() = zn.real() * q__2.real() - zn.imag() * q__2.imag(), q__1.imag() = zn.real() * q__2.imag() + zn.imag() * q__2.real(); cy[i__2].real() = q__1.real(), cy[i__2].imag() = q__1.imag(); q__1.real() = csgn.real() * zt.real() - csgn.imag() * zt.imag(), q__1.imag() = csgn.real() * zt.imag() + csgn.imag() * zt.real(); csgn.real() = q__1.real(), csgn.imag() = q__1.imag(); /* L120: */ } return 0; L130: if(xn < (float)0.) { goto L220; } return 0; L220: *ierr = 2; *nz = 0; return 0; L230: if(nw == -1) { goto L220; } *nz = 0; *ierr = 5; return 0; L240: *nz = 0; *ierr = 4; return 0; } /* cbesh_ */ static int cbesi_(System::Complex<float>* z__, float* fnu, int32* kode, int32* n, System::Complex<float>* cy, int32* nz, int32* ierr) { /* Initialized data */ static float pi = (float)3.14159265358979324; static System::Complex<float> cone = {(float)1., (float)0.}; /* System generated locals */ int32 i__1, i__2; float r__1, r__2; System::Complex<float> q__1, q__2; int32 i__, k, k1, k2; float s1, s2, aa, bb, fn, az; int32 nn; float rl; System::Complex<float> zn; float xx, yy, dig, arg, r1m5; int32 inu; float tol, alim, elim; System::Complex<float> csgn; float atol, fnul, rtol, ascle; /* *********************************************************************72 */ /* c CBESI computes a sequence of System::Complex<float> Bessel I functions. */ /* ***BEGIN PROLOGUE CBESI */ /* ***DATE WRITTEN 830501 (YYMMDD) */ /* ***REVISION DATE 890801, 930101 (YYMMDD) */ /* ***CATEGORY NO. B5K */ /* ***KEYWORDS I-BESSEL FUNCTION,COMPLEX BESSEL FUNCTION, */ /* MODIFIED BESSEL FUNCTION OF THE FIRST KIND */ /* ***AUTHOR AMOS, DONALD E., SANDIA NATIONAL LABORATORIES */ /* ***PURPOSE TO COMPUTE I-BESSEL FUNCTIONS OF COMPLEX ARGUMENT */ /* ***DESCRIPTION */ /* ON KODE=1, CBESI COMPUTES AN N MEMBER SEQUENCE OF COMPLEX */ /* BESSEL FUNCTIONS CY(J)=I(FNU+J-1,Z) FOR REAL, NONNEGATIVE */ /* ORDERS FNU+J-1, J=1,...,N AND COMPLEX Z IN THE CUT PLANE */ /* -PI.LT.ARG(Z).LE.PI. ON KODE=2, CBESI RETURNS THE SCALED */ /* FUNCTIONS */ /* CY(J)=EXP(-ABS(X))*I(FNU+J-1,Z) J = 1,...,N , X=REAL(Z) */ /* WITH THE EXPONENTIAL GROWTH REMOVED IN BOTH THE LEFT AND */ /* RIGHT HALF PLANES FOR Z TO INFINITY. DEFINITIONS AND */ /* NOTATION ARE FOUND IN THE NBS HANDBOOK OF MATHEMATICAL */ /* FUNCTIONS (REF.1) */ /* INPUT */ /* Z - Z=CMPLX(X,Y), -PI.LT.ARG(Z).LE.PI */ /* FNU - ORDER OF INITIAL I FUNCTION, FNU.GE.0.0E0 */ /* KODE - A PARAMETER TO INDICATE THE SCALING OPTION */ /* KODE= 1 RETURNS */ /* CY(J)=I(FNU+J-1,Z), J=1,...,N */ /* = 2 RETURNS */ /* CY(J)=I(FNU+J-1,Z)*EXP(-ABS(X)), J=1,...,N */ /* N - NUMBER OF MEMBERS OF THE SEQUENCE, N.GE.1 */ /* OUTPUT */ /* CY - A COMPLEX VECTOR WHOSE FIRST N COMPONENTS CONTAIN */ /* VALUES FOR THE SEQUENCE */ /* CY(J)=I(FNU+J-1,Z) OR */ /* CY(J)=I(FNU+J-1,Z)*EXP(-ABS(X)) J=1,...,N */ /* DEPENDING ON KODE, X=REAL(Z) */ /* NZ - NUMBER OF COMPONENTS SET TO ZERO DUE TO UNDERFLOW, */ /* NZ= 0 , NORMAL RETURN */ /* NZ.GT.0 , LAST NZ COMPONENTS OF CY SET TO ZERO */ /* DUE TO UNDERFLOW, CY(J)=CMPLX(0.0,0.0), */ /* J = N-NZ+1,...,N */ /* IERR - ERROR FLAG */ /* IERR=0, NORMAL RETURN - COMPUTATION COMPLETED */ /* IERR=1, INPUT ERROR - NO COMPUTATION */ /* IERR=2, OVERFLOW - NO COMPUTATION, REAL(Z) TOO */ /* LARGE ON KODE=1 */ /* IERR=3, CABS(Z) OR FNU+N-1 LARGE - COMPUTATION DONE */ /* BUT LOSSES OF SIGNIFCANCE BY ARGUMENT */ /* REDUCTION PRODUCE LESS THAN HALF OF MACHINE */ /* ACCURACY */ /* IERR=4, CABS(Z) OR FNU+N-1 TOO LARGE - NO COMPUTA- */ /* TION BECAUSE OF COMPLETE LOSSES OF SIGNIFI- */ /* CANCE BY ARGUMENT REDUCTION */ /* IERR=5, ERROR - NO COMPUTATION, */ /* ALGORITHM TERMINATION CONDITION NOT MET */ /* ***LONG DESCRIPTION */ /* THE COMPUTATION IS CARRIED OUT BY THE POWER SERIES FOR */ /* SMALL CABS(Z), THE ASYMPTOTIC EXPANSION FOR LARGE CABS(Z), */ /* THE MILLER ALGORITHM NORMALIZED BY THE WRONSKIAN AND A */ /* NEUMANN SERIES FOR IMTERMEDIATE MAGNITUDES, AND THE */ /* UNIFORM ASYMPTOTIC EXPANSIONS FOR I(FNU,Z) AND J(FNU,Z) */ /* FOR LARGE ORDERS. BACKWARD RECURRENCE IS USED TO GENERATE */ /* SEQUENCES OR REDUCE ORDERS WHEN NECESSARY. */ /* THE CALCULATIONS ABOVE ARE DONE IN THE RIGHT HALF PLANE AND */ /* CONTINUED INTO THE LEFT HALF PLANE BY THE FORMULA */ /* I(FNU,Z*EXP(M*PI)) = EXP(M*PI*FNU)*I(FNU,Z) REAL(Z).GT.0.0 */ /* M = +I OR -I, I**2=-1 */ /* FOR NEGATIVE ORDERS,THE FORMULA */ /* I(-FNU,Z) = I(FNU,Z) + (2/PI)*SIN(PI*FNU)*K(FNU,Z) */ /* CAN BE USED. HOWEVER,FOR LARGE ORDERS CLOSE TO INTEGERS, THE */ /* THE FUNCTION CHANGES RADICALLY. WHEN FNU IS A LARGE POSITIVE */ /* INTEGER,THE MAGNITUDE OF I(-FNU,Z)=I(FNU,Z) IS A LARGE */ /* NEGATIVE POWER OF TEN. BUT WHEN FNU IS NOT AN INTEGER, */ /* K(FNU,Z) DOMINATES IN MAGNITUDE WITH A LARGE POSITIVE POWER OF */ /* TEN AND THE MOST THAT THE SECOND TERM CAN BE REDUCED IS BY */ /* UNIT ROUNDOFF FROM THE COEFFICIENT. THUS, WIDE CHANGES CAN */ /* OCCUR WITHIN UNIT ROUNDOFF OF A LARGE INTEGER FOR FNU. HERE, */ /* LARGE MEANS FNU.GT.CABS(Z). */ /* IN MOST COMPLEX VARIABLE COMPUTATION, ONE MUST EVALUATE ELE- */ /* MENTARY FUNCTIONS. WHEN THE MAGNITUDE OF Z OR FNU+N-1 IS */ /* LARGE, LOSSES OF SIGNIFICANCE BY ARGUMENT REDUCTION OCCUR. */ /* CONSEQUENTLY, IF EITHER ONE EXCEEDS U1=SQRT(0.5/UR), THEN */ /* LOSSES EXCEEDING HALF PRECISION ARE LIKELY AND AN ERROR FLAG */ /* IERR=3 IS TRIGGERED WHERE UR=R1MACH(4)=UNIT ROUNDOFF. ALSO */ /* IF EITHER IS LARGER THAN U2=0.5/UR, THEN ALL SIGNIFICANCE IS */ /* LOST AND IERR=4. IN ORDER TO USE THE INT FUNCTION, ARGUMENTS */ /* MUST BE FURTHER RESTRICTED NOT TO EXCEED THE LARGEST MACHINE */ /* INTEGER, U3=I1MACH(9). THUS, THE MAGNITUDE OF Z AND FNU+N-1 IS */ /* RESTRICTED BY MIN(U2,U3). ON 32 BIT MACHINES, U1,U2, AND U3 */ /* ARE APPROXIMATELY 2.0E+3, 4.2E+6, 2.1E+9 IN SINGLE PRECISION */ /* ARITHMETIC AND 1.3E+8, 1.8E+16, 2.1E+9 IN DOUBLE PRECISION */ /* ARITHMETIC RESPECTIVELY. THIS MAKES U2 AND U3 LIMITING IN */ /* THEIR RESPECTIVE ARITHMETICS. THIS MEANS THAT ONE CAN EXPECT */ /* TO RETAIN, IN THE WORST CASES ON 32 BIT MACHINES, NO DIGITS */ /* IN SINGLE AND ONLY 7 DIGITS IN DOUBLE PRECISION ARITHMETIC. */ /* SIMILAR CONSIDERATIONS HOLD FOR OTHER MACHINES. */ /* THE APPROXIMATE RELATIVE ERROR IN THE MAGNITUDE OF A COMPLEX */ /* BESSEL FUNCTION CAN BE EXPRESSED BY P*10**S WHERE P=MAX(UNIT */ /* ROUNDOFF,1.0E-18) IS THE NOMINAL PRECISION AND 10**S REPRE- */ /* SENTS THE INCREASE IN ERROR DUE TO ARGUMENT REDUCTION IN THE */ /* ELEMENTARY FUNCTIONS. HERE, S=MAX(1,ABS(LOG10(CABS(Z))), */ /* ABS(LOG10(FNU))) APPROXIMATELY (I.E. S=MAX(1,ABS(EXPONENT OF */ /* CABS(Z),ABS(EXPONENT OF FNU)) ). HOWEVER, THE PHASE ANGLE MAY */ /* HAVE ONLY ABSOLUTE ACCURACY. THIS IS MOST LIKELY TO OCCUR WHEN */ /* ONE COMPONENT (IN ABSOLUTE VALUE) IS LARGER THAN THE OTHER BY */ /* SEVERAL ORDERS OF MAGNITUDE. IF ONE COMPONENT IS 10**K LARGER */ /* THAN THE OTHER, THEN ONE CAN EXPECT ONLY MAX(ABS(LOG10(P))-K, */ /* 0) SIGNIFICANT DIGITS; OR, STATED ANOTHER WAY, WHEN K EXCEEDS */ /* THE EXPONENT OF P, NO SIGNIFICANT DIGITS REMAIN IN THE SMALLER */ /* COMPONENT. HOWEVER, THE PHASE ANGLE RETAINS ABSOLUTE ACCURACY */ /* BECAUSE, IN COMPLEX ARITHMETIC WITH PRECISION P, THE SMALLER */ /* COMPONENT WILL NOT (AS A RULE) DECREASE BELOW P TIMES THE */ /* MAGNITUDE OF THE LARGER COMPONENT. IN THESE EXTREME CASES, */ /* THE PRINCIPAL PHASE ANGLE IS ON THE ORDER OF +P, -P, PI/2-P, */ /* OR -PI/2+P. */ /* ***REFERENCES HANDBOOK OF MATHEMATICAL FUNCTIONS BY M. ABRAMOWITZ */ /* AND I. A. STEGUN, NBS AMS SERIES 55, U.S. DEPT. OF */ /* COMMERCE, 1955. */ /* COMPUTATION OF BESSEL FUNCTIONS OF COMPLEX ARGUMENT */ /* BY D. E. AMOS, SAND83-0083, MAY, 1983. */ /* COMPUTATION OF BESSEL FUNCTIONS OF COMPLEX ARGUMENT */ /* AND LARGE ORDER BY D. E. AMOS, SAND83-0643, MAY, 1983 */ /* A SUBROUTINE PACKAGE FOR BESSEL FUNCTIONS OF A COMPLEX */ /* ARGUMENT AND NONNEGATIVE ORDER BY D. E. AMOS, SAND85- */ /* 1018, MAY, 1985 */ /* A PORTABLE PACKAGE FOR BESSEL FUNCTIONS OF A COMPLEX */ /* ARGUMENT AND NONNEGATIVE ORDER BY D. E. AMOS, ACM */ /* TRANS. MATH. SOFTWARE, VOL. 12, NO. 3, SEPTEMBER 1986, */ /* PP 265-273. */ /* ***ROUTINES CALLED CBINU,I1MACH,R1MACH */ /* ***END PROLOGUE CBESI */ /* Parameter adjustments */ --cy; /* Function Body */ /* ***FIRST EXECUTABLE STATEMENT CBESI */ *ierr = 0; *nz = 0; if(*fnu < (float)0.) { *ierr = 1; } if(*kode < 1 || *kode > 2) { *ierr = 1; } if(*n < 1) { *ierr = 1; } if(*ierr != 0) { return 0; } xx = z__->real(); yy = r_imag(z__); /* ----------------------------------------------------------------------- */ /* SET PARAMETERS RELATED TO MACHINE CONSTANTS. */ /* TOL IS THE APPROXIMATE UNIT ROUNDOFF LIMITED TO 1.0E-18. */ /* ELIM IS THE APPROXIMATE EXPONENTIAL OVER- AND UNDERFLOW LIMIT. */ /* EXP(-ELIM).LT.EXP(-ALIM)=EXP(-ELIM)/TOL AND */ /* EXP(ELIM).GT.EXP(ALIM)=EXP(ELIM)*TOL ARE INTERVALS NEAR */ /* UNDERFLOW AND OVERFLOW LIMITS WHERE SCALED ARITHMETIC IS DONE. */ /* RL IS THE LOWER BOUNDARY OF THE ASYMPTOTIC EXPANSION FOR LARGE Z. */ /* DIG = NUMBER OF BASE 10 DIGITS IN TOL = 10**(-DIG). */ /* FNUL IS THE LOWER BOUNDARY OF THE ASYMPTOTIC SERIES FOR LARGE FNU. */ /* ----------------------------------------------------------------------- */ /* Computing MAX */ r__1 = r1mach_(&c__4); tol = max(r__1, (float)1e-18); k1 = i1mach_(&c__12); k2 = i1mach_(&c__13); r1m5 = r1mach_(&c__5); /* Computing MIN */ i__1 = abs(k1), i__2 = abs(k2); k = std::min(i__1, i__2); elim = ((float)k * r1m5 - (float)3.) * (float)2.303; k1 = i1mach_(&c__11) - 1; aa = r1m5 * (float)k1; dig = std::min(aa, (float)18.); aa *= (float)2.303; /* Computing MAX */ r__1 = -aa; alim = elim + max(r__1, (float)-41.45); rl = dig * (float)1.2 + (float)3.; fnul = (dig - (float)3.) * (float)6. + (float)10.; az = c_abs(z__); /* ----------------------------------------------------------------------- */ /* TEST FOR RANGE */ /* ----------------------------------------------------------------------- */ aa = (float).5 / tol; bb = (float)i1mach_(&c__9) * (float).5; aa = std::min(aa, bb); if(az > aa) { goto L140; } fn = *fnu + (float)(*n - 1); if(fn > aa) { goto L140; } aa = sqrt(aa); if(az > aa) { *ierr = 3; } if(fn > aa) { *ierr = 3; } zn.real() = z__->real(), zn.imag() = z__->imag(); csgn.real() = cone.real(), csgn.imag() = cone.imag(); if(xx >= (float)0.) { goto L40; } q__1.real() = -z__->real(), q__1.imag() = -z__->imag(); zn.real() = q__1.real(), zn.imag() = q__1.imag(); /* ----------------------------------------------------------------------- */ /* CALCULATE CSGN=EXP(FNU*PI*I) TO MINIMIZE LOSSES OF SIGNIFICANCE */ /* WHEN FNU IS LARGE */ /* ----------------------------------------------------------------------- */ inu = (int32)(*fnu); arg = (*fnu - (float)inu) * pi; if(yy < (float)0.) { arg = -arg; } s1 = cos(arg); s2 = sin(arg); q__1.real() = s1, q__1.imag() = s2; csgn.real() = q__1.real(), csgn.imag() = q__1.imag(); if(inu % 2 == 1) { q__1.real() = -csgn.real(), q__1.imag() = -csgn.imag(); csgn.real() = q__1.real(), csgn.imag() = q__1.imag(); } L40: cbinu_(&zn, fnu, kode, n, &cy[1], nz, &rl, &fnul, &tol, &elim, &alim); if(*nz < 0) { goto L120; } if(xx >= (float)0.) { return 0; } /* ----------------------------------------------------------------------- */ /* ANALYTIC CONTINUATION TO THE LEFT HALF PLANE */ /* ----------------------------------------------------------------------- */ nn = *n - *nz; if(nn == 0) { return 0; } rtol = (float)1. / tol; ascle = r1mach_(&c__1) * rtol * (float)1e3; i__1 = nn; for(i__ = 1; i__ <= i__1; ++i__) { /* CY(I) = CY(I)*CSGN */ i__2 = i__; zn.real() = cy[i__2].real(), zn.imag() = cy[i__2].imag(); aa = zn.real(); bb = r_imag(&zn); atol = (float)1.; /* Computing MAX */ r__1 = abs(aa), r__2 = abs(bb); if(max(r__1, r__2) > ascle) { goto L55; } q__2.real() = rtol, q__2.imag() = (float)0.; q__1.real() = zn.real() * q__2.real() - zn.imag() * q__2.imag(), q__1.imag() = zn.real() * q__2.imag() + zn.imag() * q__2.real(); zn.real() = q__1.real(), zn.imag() = q__1.imag(); atol = tol; L55: q__1.real() = zn.real() * csgn.real() - zn.imag() * csgn.imag(), q__1.imag() = zn.real() * csgn.imag() + zn.imag() * csgn.real(); zn.real() = q__1.real(), zn.imag() = q__1.imag(); i__2 = i__; q__2.real() = atol, q__2.imag() = (float)0.; q__1.real() = zn.real() * q__2.real() - zn.imag() * q__2.imag(), q__1.imag() = zn.real() * q__2.imag() + zn.imag() * q__2.real(); cy[i__2].real() = q__1.real(), cy[i__2].imag() = q__1.imag(); q__1.real() = -csgn.real(), q__1.imag() = -csgn.imag(); csgn.real() = q__1.real(), csgn.imag() = q__1.imag(); /* L50: */ } return 0; L120: if(*nz == -2) { goto L130; } *nz = 0; *ierr = 2; return 0; L130: *nz = 0; *ierr = 5; return 0; L140: *nz = 0; *ierr = 4; return 0; } /* cbesi_ */ int cbesj_(System::Complex<float>* z__, float* fnu, int32* kode, int32* n, System::Complex<float>* cy, int32* nz, int32* ierr) { /* Initialized data */ static float hpi = (float)1.57079632679489662; /* System generated locals */ int32 i__1, i__2; float r__1, r__2; System::Complex<float> q__1, q__2; int32 i__, k, k1, k2; float r1, r2, aa, bb; System::Complex<float> ci; float fn; int32 nl; float az; int32 ir; float rl; System::Complex<float> zn; float yy, dig, arg, r1m5; int32 inu; float tol, alim, elim; System::Complex<float> csgn; float atol; int32 inuh; float fnul, rtol, ascle; /* *********************************************************************72 */ /* c CBESJ computes a sequence of System::Complex<float> Bessel J functions. */ /* ***BEGIN PROLOGUE CBESJ */ /* ***DATE WRITTEN 830501 (YYMMDD) */ /* ***REVISION DATE 890801, 930101 (YYMMDD) */ /* ***CATEGORY NO. B5K */ /* ***KEYWORDS J-BESSEL FUNCTION,BESSEL FUNCTION OF COMPLEX ARGUMENT, */ /* BESSEL FUNCTION OF FIRST KIND */ /* ***AUTHOR AMOS, DONALD E., SANDIA NATIONAL LABORATORIES */ /* ***PURPOSE TO COMPUTE THE J-BESSEL FUNCTION OF A COMPLEX ARGUMENT */ /* ***DESCRIPTION */ /* ON KODE=1, CBESJ COMPUTES AN N MEMBER SEQUENCE OF COMPLEX */ /* BESSEL FUNCTIONS CY(I)=J(FNU+I-1,Z) FOR REAL, NONNEGATIVE */ /* ORDERS FNU+I-1, I=1,...,N AND COMPLEX Z IN THE CUT PLANE */ /* -PI.LT.ARG(Z).LE.PI. ON KODE=2, CBESJ RETURNS THE SCALED */ /* FUNCTIONS */ /* CY(I)=EXP(-ABS(Y))*J(FNU+I-1,Z) I = 1,...,N , Y=AIMAG(Z) */ /* WHICH REMOVE THE EXPONENTIAL GROWTH IN BOTH THE UPPER AND */ /* LOWER HALF PLANES FOR Z TO INFINITY. DEFINITIONS AND NOTATION */ /* ARE FOUND IN THE NBS HANDBOOK OF MATHEMATICAL FUNCTIONS */ /* (REF. 1). */ /* INPUT */ /* Z - Z=CMPLX(X,Y), -PI.LT.ARG(Z).LE.PI */ /* FNU - ORDER OF INITIAL J FUNCTION, FNU.GE.0.0E0 */ /* KODE - A PARAMETER TO INDICATE THE SCALING OPTION */ /* KODE= 1 RETURNS */ /* CY(I)=J(FNU+I-1,Z), I=1,...,N */ /* = 2 RETURNS */ /* CY(I)=J(FNU+I-1,Z)*EXP(-ABS(Y)), I=1,... */ /* N - NUMBER OF MEMBERS OF THE SEQUENCE, N.GE.1 */ /* OUTPUT */ /* CY - A COMPLEX VECTOR WHOSE FIRST N COMPONENTS CONTAIN */ /* VALUES FOR THE SEQUENCE */ /* CY(I)=J(FNU+I-1,Z) OR */ /* CY(I)=J(FNU+I-1,Z)*EXP(-ABS(Y)) I=1,...,N */ /* DEPENDING ON KODE, Y=AIMAG(Z). */ /* NZ - NUMBER OF COMPONENTS SET TO ZERO DUE TO UNDERFLOW, */ /* NZ= 0 , NORMAL RETURN */ /* NZ.GT.0 , LAST NZ COMPONENTS OF CY SET TO ZERO */ /* DUE TO UNDERFLOW, CY(I)=CMPLX(0.0,0.0), */ /* I = N-NZ+1,...,N */ /* IERR - ERROR FLAG */ /* IERR=0, NORMAL RETURN - COMPUTATION COMPLETED */ /* IERR=1, INPUT ERROR - NO COMPUTATION */ /* IERR=2, OVERFLOW - NO COMPUTATION, AIMAG(Z) */ /* TOO LARGE ON KODE=1 */ /* IERR=3, CABS(Z) OR FNU+N-1 LARGE - COMPUTATION DONE */ /* BUT LOSSES OF SIGNIFCANCE BY ARGUMENT */ /* REDUCTION PRODUCE LESS THAN HALF OF MACHINE */ /* ACCURACY */ /* IERR=4, CABS(Z) OR FNU+N-1 TOO LARGE - NO COMPUTA- */ /* TION BECAUSE OF COMPLETE LOSSES OF SIGNIFI- */ /* CANCE BY ARGUMENT REDUCTION */ /* IERR=5, ERROR - NO COMPUTATION, */ /* ALGORITHM TERMINATION CONDITION NOT MET */ /* ***LONG DESCRIPTION */ /* THE COMPUTATION IS CARRIED OUT BY THE FORMULA */ /* J(FNU,Z)=EXP( FNU*PI*I/2)*I(FNU,-I*Z) AIMAG(Z).GE.0.0 */ /* J(FNU,Z)=EXP(-FNU*PI*I/2)*I(FNU, I*Z) AIMAG(Z).LT.0.0 */ /* WHERE I**2 = -1 AND I(FNU,Z) IS THE I BESSEL FUNCTION. */ /* FOR NEGATIVE ORDERS,THE FORMULA */ /* J(-FNU,Z) = J(FNU,Z)*COS(PI*FNU) - Y(FNU,Z)*SIN(PI*FNU) */ /* CAN BE USED. HOWEVER,FOR LARGE ORDERS CLOSE TO INTEGERS, THE */ /* THE FUNCTION CHANGES RADICALLY. WHEN FNU IS A LARGE POSITIVE */ /* INTEGER,THE MAGNITUDE OF J(-FNU,Z)=J(FNU,Z)*COS(PI*FNU) IS A */ /* LARGE NEGATIVE POWER OF TEN. BUT WHEN FNU IS NOT AN INTEGER, */ /* Y(FNU,Z) DOMINATES IN MAGNITUDE WITH A LARGE POSITIVE POWER OF */ /* TEN AND THE MOST THAT THE SECOND TERM CAN BE REDUCED IS BY */ /* UNIT ROUNDOFF FROM THE COEFFICIENT. THUS, WIDE CHANGES CAN */ /* OCCUR WITHIN UNIT ROUNDOFF OF A LARGE INTEGER FOR FNU. HERE, */ /* LARGE MEANS FNU.GT.CABS(Z). */ /* IN MOST COMPLEX VARIABLE COMPUTATION, ONE MUST EVALUATE ELE- */ /* MENTARY FUNCTIONS. WHEN THE MAGNITUDE OF Z OR FNU+N-1 IS */ /* LARGE, LOSSES OF SIGNIFICANCE BY ARGUMENT REDUCTION OCCUR. */ /* CONSEQUENTLY, IF EITHER ONE EXCEEDS U1=SQRT(0.5/UR), THEN */ /* LOSSES EXCEEDING HALF PRECISION ARE LIKELY AND AN ERROR FLAG */ /* IERR=3 IS TRIGGERED WHERE UR=R1MACH(4)=UNIT ROUNDOFF. ALSO */ /* IF EITHER IS LARGER THAN U2=0.5/UR, THEN ALL SIGNIFICANCE IS */ /* LOST AND IERR=4. IN ORDER TO USE THE INT FUNCTION, ARGUMENTS */ /* MUST BE FURTHER RESTRICTED NOT TO EXCEED THE LARGEST MACHINE */ /* INTEGER, U3=I1MACH(9). THUS, THE MAGNITUDE OF Z AND FNU+N-1 IS */ /* RESTRICTED BY MIN(U2,U3). ON 32 BIT MACHINES, U1,U2, AND U3 */ /* ARE APPROXIMATELY 2.0E+3, 4.2E+6, 2.1E+9 IN SINGLE PRECISION */ /* ARITHMETIC AND 1.3E+8, 1.8E+16, 2.1E+9 IN DOUBLE PRECISION */ /* ARITHMETIC RESPECTIVELY. THIS MAKES U2 AND U3 LIMITING IN */ /* THEIR RESPECTIVE ARITHMETICS. THIS MEANS THAT ONE CAN EXPECT */ /* TO RETAIN, IN THE WORST CASES ON 32 BIT MACHINES, NO DIGITS */ /* IN SINGLE AND ONLY 7 DIGITS IN DOUBLE PRECISION ARITHMETIC. */ /* SIMILAR CONSIDERATIONS HOLD FOR OTHER MACHINES. */ /* THE APPROXIMATE RELATIVE ERROR IN THE MAGNITUDE OF A COMPLEX */ /* BESSEL FUNCTION CAN BE EXPRESSED BY P*10**S WHERE P=MAX(UNIT */ /* ROUNDOFF,1.0E-18) IS THE NOMINAL PRECISION AND 10**S REPRE- */ /* SENTS THE INCREASE IN ERROR DUE TO ARGUMENT REDUCTION IN THE */ /* ELEMENTARY FUNCTIONS. HERE, S=MAX(1,ABS(LOG10(CABS(Z))), */ /* ABS(LOG10(FNU))) APPROXIMATELY (I.E. S=MAX(1,ABS(EXPONENT OF */ /* CABS(Z),ABS(EXPONENT OF FNU)) ). HOWEVER, THE PHASE ANGLE MAY */ /* HAVE ONLY ABSOLUTE ACCURACY. THIS IS MOST LIKELY TO OCCUR WHEN */ /* ONE COMPONENT (IN ABSOLUTE VALUE) IS LARGER THAN THE OTHER BY */ /* SEVERAL ORDERS OF MAGNITUDE. IF ONE COMPONENT IS 10**K LARGER */ /* THAN THE OTHER, THEN ONE CAN EXPECT ONLY MAX(ABS(LOG10(P))-K, */ /* 0) SIGNIFICANT DIGITS; OR, STATED ANOTHER WAY, WHEN K EXCEEDS */ /* THE EXPONENT OF P, NO SIGNIFICANT DIGITS REMAIN IN THE SMALLER */ /* COMPONENT. HOWEVER, THE PHASE ANGLE RETAINS ABSOLUTE ACCURACY */ /* BECAUSE, IN COMPLEX ARITHMETIC WITH PRECISION P, THE SMALLER */ /* COMPONENT WILL NOT (AS A RULE) DECREASE BELOW P TIMES THE */ /* MAGNITUDE OF THE LARGER COMPONENT. IN THESE EXTREME CASES, */ /* THE PRINCIPAL PHASE ANGLE IS ON THE ORDER OF +P, -P, PI/2-P, */ /* OR -PI/2+P. */ /* ***REFERENCES HANDBOOK OF MATHEMATICAL FUNCTIONS BY M. ABRAMOWITZ */ /* AND I. A. STEGUN, NBS AMS SERIES 55, U.S. DEPT. OF */ /* COMMERCE, 1955. */ /* COMPUTATION OF BESSEL FUNCTIONS OF COMPLEX ARGUMENT */ /* BY D. E. AMOS, SAND83-0083, MAY, 1983. */ /* COMPUTATION OF BESSEL FUNCTIONS OF COMPLEX ARGUMENT */ /* AND LARGE ORDER BY D. E. AMOS, SAND83-0643, MAY, 1983 */ /* A SUBROUTINE PACKAGE FOR BESSEL FUNCTIONS OF A COMPLEX */ /* ARGUMENT AND NONNEGATIVE ORDER BY D. E. AMOS, SAND85- */ /* 1018, MAY, 1985 */ /* A PORTABLE PACKAGE FOR BESSEL FUNCTIONS OF A COMPLEX */ /* ARGUMENT AND NONNEGATIVE ORDER BY D. E. AMOS, ACM */ /* TRANS. MATH. SOFTWARE, VOL. 12, NO. 3, SEPTEMBER 1986, */ /* PP 265-273. */ /* ***ROUTINES CALLED CBINU,I1MACH,R1MACH */ /* ***END PROLOGUE CBESJ */ /* Parameter adjustments */ --cy; /* Function Body */ /* ***FIRST EXECUTABLE STATEMENT CBESJ */ *ierr = 0; *nz = 0; if(*fnu < (float)0.) { *ierr = 1; } if(*kode < 1 || *kode > 2) { *ierr = 1; } if(*n < 1) { *ierr = 1; } if(*ierr != 0) { return 0; } /* ----------------------------------------------------------------------- */ /* SET PARAMETERS RELATED TO MACHINE CONSTANTS. */ /* TOL IS THE APPROXIMATE UNIT ROUNDOFF LIMITED TO 1.0E-18. */ /* ELIM IS THE APPROXIMATE EXPONENTIAL OVER- AND UNDERFLOW LIMIT. */ /* EXP(-ELIM).LT.EXP(-ALIM)=EXP(-ELIM)/TOL AND */ /* EXP(ELIM).GT.EXP(ALIM)=EXP(ELIM)*TOL ARE INTERVALS NEAR */ /* UNDERFLOW AND OVERFLOW LIMITS WHERE SCALED ARITHMETIC IS DONE. */ /* RL IS THE LOWER BOUNDARY OF THE ASYMPTOTIC EXPANSION FOR LARGE Z. */ /* DIG = NUMBER OF BASE 10 DIGITS IN TOL = 10**(-DIG). */ /* FNUL IS THE LOWER BOUNDARY OF THE ASYMPTOTIC SERIES FOR LARGE FNU. */ /* ----------------------------------------------------------------------- */ /* Computing MAX */ r__1 = r1mach_(&c__4); tol = max(r__1, (float)1e-18); k1 = i1mach_(&c__12); k2 = i1mach_(&c__13); r1m5 = r1mach_(&c__5); /* Computing MIN */ i__1 = abs(k1), i__2 = abs(k2); k = std::min(i__1, i__2); elim = ((float)k * r1m5 - (float)3.) * (float)2.303; k1 = i1mach_(&c__11) - 1; aa = r1m5 * (float)k1; dig = std::min(aa, (float)18.); aa *= (float)2.303; /* Computing MAX */ r__1 = -aa; alim = elim + max(r__1, (float)-41.45); rl = dig * (float)1.2 + (float)3.; fnul = (dig - (float)3.) * (float)6. + (float)10.; ci.real() = (float)0., ci.imag() = (float)1.; yy = r_imag(z__); az = c_abs(z__); /* ----------------------------------------------------------------------- */ /* TEST FOR RANGE */ /* ----------------------------------------------------------------------- */ aa = (float).5 / tol; bb = (float)i1mach_(&c__9) * (float).5; aa = std::min(aa, bb); fn = *fnu + (float)(*n - 1); if(az > aa) { goto L140; } if(fn > aa) { goto L140; } aa = sqrt(aa); if(az > aa) { *ierr = 3; } if(fn > aa) { *ierr = 3; } /* ----------------------------------------------------------------------- */ /* CALCULATE CSGN=EXP(FNU*HPI*I) TO MINIMIZE LOSSES OF SIGNIFICANCE */ /* WHEN FNU IS LARGE */ /* ----------------------------------------------------------------------- */ inu = (int32)(*fnu); inuh = inu / 2; ir = inu - (inuh << 1); arg = (*fnu - (float)(inu - ir)) * hpi; r1 = cos(arg); r2 = sin(arg); q__1.real() = r1, q__1.imag() = r2; csgn.real() = q__1.real(), csgn.imag() = q__1.imag(); if(inuh % 2 == 1) { q__1.real() = -csgn.real(), q__1.imag() = -csgn.imag(); csgn.real() = q__1.real(), csgn.imag() = q__1.imag(); } /* ----------------------------------------------------------------------- */ /* ZN IS IN THE RIGHT HALF PLANE */ /* ----------------------------------------------------------------------- */ q__2.real() = -z__->real(), q__2.imag() = -z__->imag(); q__1.real() = q__2.real() * ci.real() - q__2.imag() * ci.imag(), q__1.imag() = q__2.real() * ci.imag() + q__2.imag() * ci.real(); zn.real() = q__1.real(), zn.imag() = q__1.imag(); if(yy >= (float)0.) { goto L40; } q__1.real() = -zn.real(), q__1.imag() = -zn.imag(); zn.real() = q__1.real(), zn.imag() = q__1.imag(); r_cnjg(&q__1, &csgn); csgn.real() = q__1.real(), csgn.imag() = q__1.imag(); r_cnjg(&q__1, &ci); ci.real() = q__1.real(), ci.imag() = q__1.imag(); L40: cbinu_(&zn, fnu, kode, n, &cy[1], nz, &rl, &fnul, &tol, &elim, &alim); if(*nz < 0) { goto L120; } nl = *n - *nz; if(nl == 0) { return 0; } rtol = (float)1. / tol; ascle = r1mach_(&c__1) * rtol * (float)1e3; i__1 = nl; for(i__ = 1; i__ <= i__1; ++i__) { /* CY(I)=CY(I)*CSGN */ i__2 = i__; zn.real() = cy[i__2].real(), zn.imag() = cy[i__2].imag(); aa = zn.real(); bb = r_imag(&zn); atol = (float)1.; /* Computing MAX */ r__1 = abs(aa), r__2 = abs(bb); if(max(r__1, r__2) > ascle) { goto L55; } q__2.real() = rtol, q__2.imag() = (float)0.; q__1.real() = zn.real() * q__2.real() - zn.imag() * q__2.imag(), q__1.imag() = zn.real() * q__2.imag() + zn.imag() * q__2.real(); zn.real() = q__1.real(), zn.imag() = q__1.imag(); atol = tol; L55: q__1.real() = zn.real() * csgn.real() - zn.imag() * csgn.imag(), q__1.imag() = zn.real() * csgn.imag() + zn.imag() * csgn.real(); zn.real() = q__1.real(), zn.imag() = q__1.imag(); i__2 = i__; q__2.real() = atol, q__2.imag() = (float)0.; q__1.real() = zn.real() * q__2.real() - zn.imag() * q__2.imag(), q__1.imag() = zn.real() * q__2.imag() + zn.imag() * q__2.real(); cy[i__2].real() = q__1.real(), cy[i__2].imag() = q__1.imag(); q__1.real() = csgn.real() * ci.real() - csgn.imag() * ci.imag(), q__1.imag() = csgn.real() * ci.imag() + csgn.imag() * ci.real(); csgn.real() = q__1.real(), csgn.imag() = q__1.imag(); /* L50: */ } return 0; L120: if(*nz == -2) { goto L130; } *nz = 0; *ierr = 2; return 0; L130: *nz = 0; *ierr = 5; return 0; L140: *nz = 0; *ierr = 4; return 0; } /* cbesj_ */ int cbesk_(System::Complex<float>* z__, float* fnu, int32* kode, int32* n, System::Complex<float>* cy, int32* nz, int32* ierr) { /* System generated locals */ int32 i__1, i__2; float r__1; int32 k, k1, k2; float aa, bb, fn, az; int32 nn; float rl; int32 mr, nw; float xx, yy, dig, arg, aln, r1m5, ufl; int32 nuf; float tol, alim, elim, fnul; /* *********************************************************************72 */ /* c CBESK computes a sequence of System::Complex<float> Bessel K functions. */ /* ***BEGIN PROLOGUE CBESK */ /* ***DATE WRITTEN 830501 (YYMMDD) */ /* ***REVISION DATE 890801, 930101 (YYMMDD) */ /* ***CATEGORY NO. B5K */ /* ***KEYWORDS K-BESSEL FUNCTION,COMPLEX BESSEL FUNCTION, */ /* MODIFIED BESSEL FUNCTION OF THE SECOND KIND, */ /* BESSEL FUNCTION OF THE THIRD KIND */ /* ***AUTHOR AMOS, DONALD E., SANDIA NATIONAL LABORATORIES */ /* ***PURPOSE TO COMPUTE K-BESSEL FUNCTIONS OF COMPLEX ARGUMENT */ /* ***DESCRIPTION */ /* ON KODE=1, CBESK COMPUTES AN N MEMBER SEQUENCE OF COMPLEX */ /* BESSEL FUNCTIONS CY(J)=K(FNU+J-1,Z) FOR REAL, NONNEGATIVE */ /* ORDERS FNU+J-1, J=1,...,N AND COMPLEX Z.NE.CMPLX(0.0,0.0) */ /* IN THE CUT PLANE -PI.LT.ARG(Z).LE.PI. ON KODE=2, CBESK */ /* RETURNS THE SCALED K FUNCTIONS, */ /* CY(J)=EXP(Z)*K(FNU+J-1,Z) , J=1,...,N, */ /* WHICH REMOVE THE EXPONENTIAL BEHAVIOR IN BOTH THE LEFT AND */ /* RIGHT HALF PLANES FOR Z TO INFINITY. DEFINITIONS AND */ /* NOTATION ARE FOUND IN THE NBS HANDBOOK OF MATHEMATICAL */ /* FUNCTIONS (REF. 1). */ /* INPUT */ /* Z - Z=CMPLX(X,Y),Z.NE.CMPLX(0.,0.),-PI.LT.ARG(Z).LE.PI */ /* FNU - ORDER OF INITIAL K FUNCTION, FNU.GE.0.0E0 */ /* N - NUMBER OF MEMBERS OF THE SEQUENCE, N.GE.1 */ /* KODE - A PARAMETER TO INDICATE THE SCALING OPTION */ /* KODE= 1 RETURNS */ /* CY(I)=K(FNU+I-1,Z), I=1,...,N */ /* = 2 RETURNS */ /* CY(I)=K(FNU+I-1,Z)*EXP(Z), I=1,...,N */ /* OUTPUT */ /* CY - A COMPLEX VECTOR WHOSE FIRST N COMPONENTS CONTAIN */ /* VALUES FOR THE SEQUENCE */ /* CY(I)=K(FNU+I-1,Z), I=1,...,N OR */ /* CY(I)=K(FNU+I-1,Z)*EXP(Z), I=1,...,N */ /* DEPENDING ON KODE */ /* NZ - NUMBER OF COMPONENTS SET TO ZERO DUE TO UNDERFLOW. */ /* NZ= 0 , NORMAL RETURN */ /* NZ.GT.0 , FIRST NZ COMPONENTS OF CY SET TO ZERO */ /* DUE TO UNDERFLOW, CY(I)=CMPLX(0.0,0.0), */ /* I=1,...,N WHEN X.GE.0.0. WHEN X.LT.0.0 */ /* NZ STATES ONLY THE NUMBER OF UNDERFLOWS */ /* IN THE SEQUENCE. */ /* IERR - ERROR FLAG */ /* IERR=0, NORMAL RETURN - COMPUTATION COMPLETED */ /* IERR=1, INPUT ERROR - NO COMPUTATION */ /* IERR=2, OVERFLOW - NO COMPUTATION, FNU+N-1 IS */ /* TOO LARGE OR CABS(Z) IS TOO SMALL OR BOTH */ /* IERR=3, CABS(Z) OR FNU+N-1 LARGE - COMPUTATION DONE */ /* BUT LOSSES OF SIGNIFCANCE BY ARGUMENT */ /* REDUCTION PRODUCE LESS THAN HALF OF MACHINE */ /* ACCURACY */ /* IERR=4, CABS(Z) OR FNU+N-1 TOO LARGE - NO COMPUTA- */ /* TION BECAUSE OF COMPLETE LOSSES OF SIGNIFI- */ /* CANCE BY ARGUMENT REDUCTION */ /* IERR=5, ERROR - NO COMPUTATION, */ /* ALGORITHM TERMINATION CONDITION NOT MET */ /* ***LONG DESCRIPTION */ /* EQUATIONS OF THE REFERENCE ARE IMPLEMENTED FOR SMALL ORDERS */ /* DNU AND DNU+1.0 IN THE RIGHT HALF PLANE X.GE.0.0. FORWARD */ /* RECURRENCE GENERATES HIGHER ORDERS. K IS CONTINUED TO THE LEFT */ /* HALF PLANE BY THE RELATION */ /* K(FNU,Z*EXP(MP)) = EXP(-MP*FNU)*K(FNU,Z)-MP*I(FNU,Z) */ /* MP=MR*PI*I, MR=+1 OR -1, RE(Z).GT.0, I**2=-1 */ /* WHERE I(FNU,Z) IS THE I BESSEL FUNCTION. */ /* FOR LARGE ORDERS, FNU.GT.FNUL, THE K FUNCTION IS COMPUTED */ /* BY MEANS OF ITS UNIFORM ASYMPTOTIC EXPANSIONS. */ /* FOR NEGATIVE ORDERS, THE FORMULA */ /* K(-FNU,Z) = K(FNU,Z) */ /* CAN BE USED. */ /* CBESK ASSUMES THAT A SIGNIFICANT DIGIT SINH(X) FUNCTION IS */ /* AVAILABLE. */ /* IN MOST COMPLEX VARIABLE COMPUTATION, ONE MUST EVALUATE ELE- */ /* MENTARY FUNCTIONS. WHEN THE MAGNITUDE OF Z OR FNU+N-1 IS */ /* LARGE, LOSSES OF SIGNIFICANCE BY ARGUMENT REDUCTION OCCUR. */ /* CONSEQUENTLY, IF EITHER ONE EXCEEDS U1=SQRT(0.5/UR), THEN */ /* LOSSES EXCEEDING HALF PRECISION ARE LIKELY AND AN ERROR FLAG */ /* IERR=3 IS TRIGGERED WHERE UR=R1MACH(4)=UNIT ROUNDOFF. ALSO */ /* IF EITHER IS LARGER THAN U2=0.5/UR, THEN ALL SIGNIFICANCE IS */ /* LOST AND IERR=4. IN ORDER TO USE THE INT FUNCTION, ARGUMENTS */ /* MUST BE FURTHER RESTRICTED NOT TO EXCEED THE LARGEST MACHINE */ /* INTEGER, U3=I1MACH(9). THUS, THE MAGNITUDE OF Z AND FNU+N-1 IS */ /* RESTRICTED BY MIN(U2,U3). ON 32 BIT MACHINES, U1,U2, AND U3 */ /* ARE APPROXIMATELY 2.0E+3, 4.2E+6, 2.1E+9 IN SINGLE PRECISION */ /* ARITHMETIC AND 1.3E+8, 1.8E+16, 2.1E+9 IN DOUBLE PRECISION */ /* ARITHMETIC RESPECTIVELY. THIS MAKES U2 AND U3 LIMITING IN */ /* THEIR RESPECTIVE ARITHMETICS. THIS MEANS THAT ONE CAN EXPECT */ /* TO RETAIN, IN THE WORST CASES ON 32 BIT MACHINES, NO DIGITS */ /* IN SINGLE AND ONLY 7 DIGITS IN DOUBLE PRECISION ARITHMETIC. */ /* SIMILAR CONSIDERATIONS HOLD FOR OTHER MACHINES. */ /* THE APPROXIMATE RELATIVE ERROR IN THE MAGNITUDE OF A COMPLEX */ /* BESSEL FUNCTION CAN BE EXPRESSED BY P*10**S WHERE P=MAX(UNIT */ /* ROUNDOFF,1.0E-18) IS THE NOMINAL PRECISION AND 10**S REPRE- */ /* SENTS THE INCREASE IN ERROR DUE TO ARGUMENT REDUCTION IN THE */ /* ELEMENTARY FUNCTIONS. HERE, S=MAX(1,ABS(LOG10(CABS(Z))), */ /* ABS(LOG10(FNU))) APPROXIMATELY (I.E. S=MAX(1,ABS(EXPONENT OF */ /* CABS(Z),ABS(EXPONENT OF FNU)) ). HOWEVER, THE PHASE ANGLE MAY */ /* HAVE ONLY ABSOLUTE ACCURACY. THIS IS MOST LIKELY TO OCCUR WHEN */ /* ONE COMPONENT (IN ABSOLUTE VALUE) IS LARGER THAN THE OTHER BY */ /* SEVERAL ORDERS OF MAGNITUDE. IF ONE COMPONENT IS 10**K LARGER */ /* THAN THE OTHER, THEN ONE CAN EXPECT ONLY MAX(ABS(LOG10(P))-K, */ /* 0) SIGNIFICANT DIGITS; OR, STATED ANOTHER WAY, WHEN K EXCEEDS */ /* THE EXPONENT OF P, NO SIGNIFICANT DIGITS REMAIN IN THE SMALLER */ /* COMPONENT. HOWEVER, THE PHASE ANGLE RETAINS ABSOLUTE ACCURACY */ /* BECAUSE, IN COMPLEX ARITHMETIC WITH PRECISION P, THE SMALLER */ /* COMPONENT WILL NOT (AS A RULE) DECREASE BELOW P TIMES THE */ /* MAGNITUDE OF THE LARGER COMPONENT. IN THESE EXTREME CASES, */ /* THE PRINCIPAL PHASE ANGLE IS ON THE ORDER OF +P, -P, PI/2-P, */ /* OR -PI/2+P. */ /* ***REFERENCES HANDBOOK OF MATHEMATICAL FUNCTIONS BY M. ABRAMOWITZ */ /* AND I. A. STEGUN, NBS AMS SERIES 55, U.S. DEPT. OF */ /* COMMERCE, 1955. */ /* COMPUTATION OF BESSEL FUNCTIONS OF COMPLEX ARGUMENT */ /* BY D. E. AMOS, SAND83-0083, MAY, 1983. */ /* COMPUTATION OF BESSEL FUNCTIONS OF COMPLEX ARGUMENT */ /* AND LARGE ORDER BY D. E. AMOS, SAND83-0643, MAY, 1983. */ /* A SUBROUTINE PACKAGE FOR BESSEL FUNCTIONS OF A COMPLEX */ /* ARGUMENT AND NONNEGATIVE ORDER BY D. E. AMOS, SAND85- */ /* 1018, MAY, 1985 */ /* A PORTABLE PACKAGE FOR BESSEL FUNCTIONS OF A COMPLEX */ /* ARGUMENT AND NONNEGATIVE ORDER BY D. E. AMOS, ACM */ /* TRANS. MATH. SOFTWARE, VOL. 12, NO. 3, SEPTEMBER 1986, */ /* PP 265-273. */ /* ***ROUTINES CALLED CACON,CBKNU,CBUNK,CUOIK,I1MACH,R1MACH */ /* ***END PROLOGUE CBESK */ /* ***FIRST EXECUTABLE STATEMENT CBESK */ /* Parameter adjustments */ --cy; /* Function Body */ *ierr = 0; *nz = 0; xx = z__->real(); yy = r_imag(z__); if(yy == (float)0. && xx == (float)0.) { *ierr = 1; } if(*fnu < (float)0.) { *ierr = 1; } if(*kode < 1 || *kode > 2) { *ierr = 1; } if(*n < 1) { *ierr = 1; } if(*ierr != 0) { return 0; } nn = *n; /* ----------------------------------------------------------------------- */ /* SET PARAMETERS RELATED TO MACHINE CONSTANTS. */ /* TOL IS THE APPROXIMATE UNIT ROUNDOFF LIMITED TO 1.0E-18. */ /* ELIM IS THE APPROXIMATE EXPONENTIAL OVER- AND UNDERFLOW LIMIT. */ /* EXP(-ELIM).LT.EXP(-ALIM)=EXP(-ELIM)/TOL AND */ /* EXP(ELIM).GT.EXP(ALIM)=EXP(ELIM)*TOL ARE INTERVALS NEAR */ /* UNDERFLOW AND OVERFLOW LIMITS WHERE SCALED ARITHMETIC IS DONE. */ /* RL IS THE LOWER BOUNDARY OF THE ASYMPTOTIC EXPANSION FOR LARGE Z. */ /* DIG = NUMBER OF BASE 10 DIGITS IN TOL = 10**(-DIG). */ /* FNUL IS THE LOWER BOUNDARY OF THE ASYMPTOTIC SERIES FOR LARGE FNU */ /* ----------------------------------------------------------------------- */ /* Computing MAX */ r__1 = r1mach_(&c__4); tol = max(r__1, (float)1e-18); k1 = i1mach_(&c__12); k2 = i1mach_(&c__13); r1m5 = r1mach_(&c__5); /* Computing MIN */ i__1 = abs(k1), i__2 = abs(k2); k = std::min(i__1, i__2); elim = ((float)k * r1m5 - (float)3.) * (float)2.303; k1 = i1mach_(&c__11) - 1; aa = r1m5 * (float)k1; dig = std::min(aa, (float)18.); aa *= (float)2.303; /* Computing MAX */ r__1 = -aa; alim = elim + max(r__1, (float)-41.45); fnul = (dig - (float)3.) * (float)6. + (float)10.; rl = dig * (float)1.2 + (float)3.; az = c_abs(z__); fn = *fnu + (float)(nn - 1); /* ----------------------------------------------------------------------- */ /* TEST FOR RANGE */ /* ----------------------------------------------------------------------- */ aa = (float).5 / tol; bb = (float)i1mach_(&c__9) * (float).5; aa = std::min(aa, bb); if(az > aa) { goto L210; } if(fn > aa) { goto L210; } aa = sqrt(aa); if(az > aa) { *ierr = 3; } if(fn > aa) { *ierr = 3; } /* ----------------------------------------------------------------------- */ /* OVERFLOW TEST ON THE LAST MEMBER OF THE SEQUENCE */ /* ----------------------------------------------------------------------- */ /* UFL = EXP(-ELIM) */ ufl = r1mach_(&c__1) * (float)1e3; if(az < ufl) { goto L180; } if(*fnu > fnul) { goto L80; } if(fn <= (float)1.) { goto L60; } if(fn > (float)2.) { goto L50; } if(az > tol) { goto L60; } arg = az * (float).5; aln = -fn * log(arg); if(aln > elim) { goto L180; } goto L60; L50: cuoik_(z__, fnu, kode, &c__2, &nn, &cy[1], &nuf, &tol, &elim, &alim); if(nuf < 0) { goto L180; } *nz += nuf; nn -= nuf; /* ----------------------------------------------------------------------- */ /* HERE NN=N OR NN=0 SINCE NUF=0,NN, OR -1 ON RETURN FROM CUOIK */ /* IF NUF=NN, THEN CY(I)=CZERO FOR ALL I */ /* ----------------------------------------------------------------------- */ if(nn == 0) { goto L100; } L60: if(xx < (float)0.) { goto L70; } /* ----------------------------------------------------------------------- */ /* RIGHT HALF PLANE COMPUTATION, REAL(Z).GE.0. */ /* ----------------------------------------------------------------------- */ cbknu_(z__, fnu, kode, &nn, &cy[1], &nw, &tol, &elim, &alim); if(nw < 0) { goto L200; } *nz = nw; return 0; /* ----------------------------------------------------------------------- */ /* LEFT HALF PLANE COMPUTATION */ /* PI/2.LT.ARG(Z).LE.PI AND -PI.LT.ARG(Z).LT.-PI/2. */ /* ----------------------------------------------------------------------- */ L70: if(*nz != 0) { goto L180; } mr = 1; if(yy < (float)0.) { mr = -1; } cacon_(z__, fnu, kode, &mr, &nn, &cy[1], &nw, &rl, &fnul, &tol, &elim, &alim); if(nw < 0) { goto L200; } *nz = nw; return 0; /* ----------------------------------------------------------------------- */ /* UNIFORM ASYMPTOTIC EXPANSIONS FOR FNU.GT.FNUL */ /* ----------------------------------------------------------------------- */ L80: mr = 0; if(xx >= (float)0.) { goto L90; } mr = 1; if(yy < (float)0.) { mr = -1; } L90: cbunk_(z__, fnu, kode, &mr, &nn, &cy[1], &nw, &tol, &elim, &alim); if(nw < 0) { goto L200; } *nz += nw; return 0; L100: if(xx < (float)0.) { goto L180; } return 0; L180: *nz = 0; *ierr = 2; return 0; L200: if(nw == -1) { goto L180; } *nz = 0; *ierr = 5; return 0; L210: *nz = 0; *ierr = 4; return 0; } /* cbesk_ */ int cbesy_(System::Complex<float>* z__, float* fnu, int32* kode, int32* n, System::Complex<float>* cy, int32* nz, System::Complex<float>* cwrk, int32* ierr) { /* Initialized data */ static System::Complex<float> cip[4] = {{(float)1., (float)0.}, {(float)0., (float)1.}, {(float)-1., (float)0.}, {(float)0., (float)-1.}}; static float hpi = (float)1.57079632679489662; /* System generated locals */ int32 i__1, i__2, i__3, i__4; float r__1, r__2; System::Complex<float> q__1, q__2, q__3; int32 i__, k, k1, k2, i4; float r1, r2, aa, bb; System::Complex<float> ci, ex; float ey; System::Complex<float> zn, zu, zv; float xx, yy; System::Complex<float> zz; int32 nz1, nz2; float arg, r1m5, tay, tol, elim; System::Complex<float> csgn; float ffnu, atol, rhpi; System::Complex<float> cspn; int32 ifnu; float rtol; float ascle; /* *********************************************************************72 */ /* c CBESY computes a sequence of System::Complex<float> Bessel Y functions. */ /* ***BEGIN PROLOGUE CBESY */ /* ***DATE WRITTEN 830501 (YYMMDD) */ /* ***REVISION DATE 890801, 930101 (YYMMDD) */ /* ***CATEGORY NO. B5K */ /* ***KEYWORDS Y-BESSEL FUNCTION,BESSEL FUNCTION OF COMPLEX ARGUMENT, */ /* BESSEL FUNCTION OF SECOND KIND */ /* ***AUTHOR AMOS, DONALD E., SANDIA NATIONAL LABORATORIES */ /* ***PURPOSE TO COMPUTE THE Y-BESSEL FUNCTION OF A COMPLEX ARGUMENT */ /* ***DESCRIPTION */ /* ON KODE=1, CBESY COMPUTES AN N MEMBER SEQUENCE OF COMPLEX */ /* BESSEL FUNCTIONS CY(I)=Y(FNU+I-1,Z) FOR REAL, NONNEGATIVE */ /* ORDERS FNU+I-1, I=1,...,N AND COMPLEX Z IN THE CUT PLANE */ /* -PI.LT.ARG(Z).LE.PI. ON KODE=2, CBESY RETURNS THE SCALED */ /* FUNCTIONS */ /* CY(I)=EXP(-ABS(Y))*Y(FNU+I-1,Z) I = 1,...,N , Y=AIMAG(Z) */ /* WHICH REMOVE THE EXPONENTIAL GROWTH IN BOTH THE UPPER AND */ /* LOWER HALF PLANES FOR Z TO INFINITY. DEFINITIONS AND NOTATION */ /* ARE FOUND IN THE NBS HANDBOOK OF MATHEMATICAL FUNCTIONS */ /* (REF. 1). */ /* INPUT */ /* Z - Z=CMPLX(X,Y), Z.NE.CMPLX(0.,0.),-PI.LT.ARG(Z).LE.PI */ /* FNU - ORDER OF INITIAL Y FUNCTION, FNU.GE.0.0E0 */ /* KODE - A PARAMETER TO INDICATE THE SCALING OPTION */ /* KODE= 1 RETURNS */ /* CY(I)=Y(FNU+I-1,Z), I=1,...,N */ /* = 2 RETURNS */ /* CY(I)=Y(FNU+I-1,Z)*EXP(-ABS(Y)), I=1,...,N */ /* WHERE Y=AIMAG(Z) */ /* N - NUMBER OF MEMBERS OF THE SEQUENCE, N.GE.1 */ /* CWRK - A COMPLEX WORK VECTOR OF DIMENSION AT LEAST N */ /* OUTPUT */ /* CY - A COMPLEX VECTOR WHOSE FIRST N COMPONENTS CONTAIN */ /* VALUES FOR THE SEQUENCE */ /* CY(I)=Y(FNU+I-1,Z) OR */ /* CY(I)=Y(FNU+I-1,Z)*EXP(-ABS(Y)) I=1,...,N */ /* DEPENDING ON KODE. */ /* NZ - NZ=0 , A NORMAL RETURN */ /* NZ.GT.0 , NZ COMPONENTS OF CY SET TO ZERO DUE TO */ /* UNDERFLOW (GENERALLY ON KODE=2) */ /* IERR - ERROR FLAG */ /* IERR=0, NORMAL RETURN - COMPUTATION COMPLETED */ /* IERR=1, INPUT ERROR - NO COMPUTATION */ /* IERR=2, OVERFLOW - NO COMPUTATION, FNU+N-1 IS */ /* TOO LARGE OR CABS(Z) IS TOO SMALL OR BOTH */ /* IERR=3, CABS(Z) OR FNU+N-1 LARGE - COMPUTATION DONE */ /* BUT LOSSES OF SIGNIFCANCE BY ARGUMENT */ /* REDUCTION PRODUCE LESS THAN HALF OF MACHINE */ /* ACCURACY */ /* IERR=4, CABS(Z) OR FNU+N-1 TOO LARGE - NO COMPUTA- */ /* TION BECAUSE OF COMPLETE LOSSES OF SIGNIFI- */ /* CANCE BY ARGUMENT REDUCTION */ /* IERR=5, ERROR - NO COMPUTATION, */ /* ALGORITHM TERMINATION CONDITION NOT MET */ /* ***LONG DESCRIPTION */ /* THE COMPUTATION IS CARRIED OUT IN TERMS OF THE I(FNU,Z) AND */ /* K(FNU,Z) BESSEL FUNCTIONS IN THE RIGHT HALF PLANE BY */ /* Y(FNU,Z) = I*CC*I(FNU,ARG) - (2/PI)*CONJG(CC)*K(FNU,ARG) */ /* Y(FNU,Z) = CONJG(Y(FNU,CONJG(Z))) */ /* FOR AIMAG(Z).GE.0 AND AIMAG(Z).LT.0 RESPECTIVELY, WHERE */ /* CC=EXP(I*PI*FNU/2), ARG=Z*EXP(-I*PI/2) AND I**2=-1. */ /* FOR NEGATIVE ORDERS,THE FORMULA */ /* Y(-FNU,Z) = Y(FNU,Z)*COS(PI*FNU) + J(FNU,Z)*SIN(PI*FNU) */ /* CAN BE USED. HOWEVER,FOR LARGE ORDERS CLOSE TO HALF ODD */ /* INTEGERS THE FUNCTION CHANGES RADICALLY. WHEN FNU IS A LARGE */ /* POSITIVE HALF ODD INTEGER,THE MAGNITUDE OF Y(-FNU,Z)=J(FNU,Z)* */ /* SIN(PI*FNU) IS A LARGE NEGATIVE POWER OF TEN. BUT WHEN FNU IS */ /* NOT A HALF ODD INTEGER, Y(FNU,Z) DOMINATES IN MAGNITUDE WITH A */ /* LARGE POSITIVE POWER OF TEN AND THE MOST THAT THE SECOND TERM */ /* CAN BE REDUCED IS BY UNIT ROUNDOFF FROM THE COEFFICIENT. THUS, */ /* WIDE CHANGES CAN OCCUR WITHIN UNIT ROUNDOFF OF A LARGE HALF */ /* ODD INTEGER. HERE, LARGE MEANS FNU.GT.CABS(Z). */ /* IN MOST COMPLEX VARIABLE COMPUTATION, ONE MUST EVALUATE ELE- */ /* MENTARY FUNCTIONS. WHEN THE MAGNITUDE OF Z OR FNU+N-1 IS */ /* LARGE, LOSSES OF SIGNIFICANCE BY ARGUMENT REDUCTION OCCUR. */ /* CONSEQUENTLY, IF EITHER ONE EXCEEDS U1=SQRT(0.5/UR), THEN */ /* LOSSES EXCEEDING HALF PRECISION ARE LIKELY AND AN ERROR FLAG */ /* IERR=3 IS TRIGGERED WHERE UR=R1MACH(4)=UNIT ROUNDOFF. ALSO */ /* IF EITHER IS LARGER THAN U2=0.5/UR, THEN ALL SIGNIFICANCE IS */ /* LOST AND IERR=4. IN ORDER TO USE THE INT FUNCTION, ARGUMENTS */ /* MUST BE FURTHER RESTRICTED NOT TO EXCEED THE LARGEST MACHINE */ /* INTEGER, U3=I1MACH(9). THUS, THE MAGNITUDE OF Z AND FNU+N-1 IS */ /* RESTRICTED BY MIN(U2,U3). ON 32 BIT MACHINES, U1,U2, AND U3 */ /* ARE APPROXIMATELY 2.0E+3, 4.2E+6, 2.1E+9 IN SINGLE PRECISION */ /* ARITHMETIC AND 1.3E+8, 1.8E+16, 2.1E+9 IN DOUBLE PRECISION */ /* ARITHMETIC RESPECTIVELY. THIS MAKES U2 AND U3 LIMITING IN */ /* THEIR RESPECTIVE ARITHMETICS. THIS MEANS THAT ONE CAN EXPECT */ /* TO RETAIN, IN THE WORST CASES ON 32 BIT MACHINES, NO DIGITS */ /* IN SINGLE AND ONLY 7 DIGITS IN DOUBLE PRECISION ARITHMETIC. */ /* SIMILAR CONSIDERATIONS HOLD FOR OTHER MACHINES. */ /* THE APPROXIMATE RELATIVE ERROR IN THE MAGNITUDE OF A COMPLEX */ /* BESSEL FUNCTION CAN BE EXPRESSED BY P*10**S WHERE P=MAX(UNIT */ /* ROUNDOFF,1.0E-18) IS THE NOMINAL PRECISION AND 10**S REPRE- */ /* SENTS THE INCREASE IN ERROR DUE TO ARGUMENT REDUCTION IN THE */ /* ELEMENTARY FUNCTIONS. HERE, S=MAX(1,ABS(LOG10(CABS(Z))), */ /* ABS(LOG10(FNU))) APPROXIMATELY (I.E. S=MAX(1,ABS(EXPONENT OF */ /* CABS(Z),ABS(EXPONENT OF FNU)) ). HOWEVER, THE PHASE ANGLE MAY */ /* HAVE ONLY ABSOLUTE ACCURACY. THIS IS MOST LIKELY TO OCCUR WHEN */ /* ONE COMPONENT (IN ABSOLUTE VALUE) IS LARGER THAN THE OTHER BY */ /* SEVERAL ORDERS OF MAGNITUDE. IF ONE COMPONENT IS 10**K LARGER */ /* THAN THE OTHER, THEN ONE CAN EXPECT ONLY MAX(ABS(LOG10(P))-K, */ /* 0) SIGNIFICANT DIGITS; OR, STATED ANOTHER WAY, WHEN K EXCEEDS */ /* THE EXPONENT OF P, NO SIGNIFICANT DIGITS REMAIN IN THE SMALLER */ /* COMPONENT. HOWEVER, THE PHASE ANGLE RETAINS ABSOLUTE ACCURACY */ /* BECAUSE, IN COMPLEX ARITHMETIC WITH PRECISION P, THE SMALLER */ /* COMPONENT WILL NOT (AS A RULE) DECREASE BELOW P TIMES THE */ /* MAGNITUDE OF THE LARGER COMPONENT. IN THESE EXTREME CASES, */ /* THE PRINCIPAL PHASE ANGLE IS ON THE ORDER OF +P, -P, PI/2-P, */ /* OR -PI/2+P. */ /* ***REFERENCES HANDBOOK OF MATHEMATICAL FUNCTIONS BY M. ABRAMOWITZ */ /* AND I. A. STEGUN, NBS AMS SERIES 55, U.S. DEPT. OF */ /* COMMERCE, 1955. */ /* COMPUTATION OF BESSEL FUNCTIONS OF COMPLEX ARGUMENT */ /* BY D. E. AMOS, SAND83-0083, MAY, 1983. */ /* COMPUTATION OF BESSEL FUNCTIONS OF COMPLEX ARGUMENT */ /* AND LARGE ORDER BY D. E. AMOS, SAND83-0643, MAY, 1983 */ /* A SUBROUTINE PACKAGE FOR BESSEL FUNCTIONS OF A COMPLEX */ /* ARGUMENT AND NONNEGATIVE ORDER BY D. E. AMOS, SAND85- */ /* 1018, MAY, 1985 */ /* A PORTABLE PACKAGE FOR BESSEL FUNCTIONS OF A COMPLEX */ /* ARGUMENT AND NONNEGATIVE ORDER BY D. E. AMOS, ACM */ /* TRANS. MATH. SOFTWARE, VOL. 12, NO. 3, SEPTEMBER 1986, */ /* PP 265-273. */ /* ***ROUTINES CALLED CBESI,CBESK,I1MACH,R1MACH */ /* ***END PROLOGUE CBESY */ /* Parameter adjustments */ --cwrk; --cy; /* Function Body */ /* ***FIRST EXECUTABLE STATEMENT CBESY */ xx = z__->real(); yy = r_imag(z__); *ierr = 0; *nz = 0; if(xx == (float)0. && yy == (float)0.) { *ierr = 1; } if(*fnu < (float)0.) { *ierr = 1; } if(*kode < 1 || *kode > 2) { *ierr = 1; } if(*n < 1) { *ierr = 1; } if(*ierr != 0) { return 0; } ci.real() = (float)0., ci.imag() = (float)1.; zz.real() = z__->real(), zz.imag() = z__->imag(); if(yy < (float)0.) { r_cnjg(&q__1, z__); zz.real() = q__1.real(), zz.imag() = q__1.imag(); } q__2.real() = -ci.real(), q__2.imag() = -ci.imag(); q__1.real() = q__2.real() * zz.real() - q__2.imag() * zz.imag(), q__1.imag() = q__2.real() * zz.imag() + q__2.imag() * zz.real(); zn.real() = q__1.real(), zn.imag() = q__1.imag(); cbesi_(&zn, fnu, kode, n, &cy[1], &nz1, ierr); if(*ierr != 0 && *ierr != 3) { goto L90; } cbesk_(&zn, fnu, kode, n, &cwrk[1], &nz2, ierr); if(*ierr != 0 && *ierr != 3) { goto L90; } *nz = std::min(nz1, nz2); ifnu = (int32)(*fnu); ffnu = *fnu - (float)ifnu; arg = hpi * ffnu; r__1 = cos(arg); r__2 = sin(arg); q__1.real() = r__1, q__1.imag() = r__2; csgn.real() = q__1.real(), csgn.imag() = q__1.imag(); i4 = ifnu % 4 + 1; i__1 = i4 - 1; q__1.real() = csgn.real() * cip[i__1].real() - csgn.imag() * cip[i__1].imag(), q__1.imag() = csgn.real() * cip[i__1].imag() + csgn.imag() * cip[i__1].real(); csgn.real() = q__1.real(), csgn.imag() = q__1.imag(); rhpi = (float)1. / hpi; r_cnjg(&q__2, &csgn); q__3.real() = rhpi, q__3.imag() = (float)0.; q__1.real() = q__2.real() * q__3.real() - q__2.imag() * q__3.imag(), q__1.imag() = q__2.real() * q__3.imag() + q__2.imag() * q__3.real(); cspn.real() = q__1.real(), cspn.imag() = q__1.imag(); q__1.real() = csgn.real() * ci.real() - csgn.imag() * ci.imag(), q__1.imag() = csgn.real() * ci.imag() + csgn.imag() * ci.real(); csgn.real() = q__1.real(), csgn.imag() = q__1.imag(); if(*kode == 2) { goto L60; } i__1 = *n; for(i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; i__3 = i__; q__2.real() = csgn.real() * cy[i__3].real() - csgn.imag() * cy[i__3].imag(), q__2.imag() = csgn.real() * cy[i__3].imag() + csgn.imag() * cy[i__3].real(); i__4 = i__; q__3.real() = cspn.real() * cwrk[i__4].real() - cspn.imag() * cwrk[i__4].imag(), q__3.imag() = cspn.real() * cwrk[i__4].imag() + cspn.imag() * cwrk[i__4].real(); q__1.real() = q__2.real() - q__3.real(), q__1.imag() = q__2.imag() - q__3.imag(); cy[i__2].real() = q__1.real(), cy[i__2].imag() = q__1.imag(); q__1.real() = ci.real() * csgn.real() - ci.imag() * csgn.imag(), q__1.imag() = ci.real() * csgn.imag() + ci.imag() * csgn.real(); csgn.real() = q__1.real(), csgn.imag() = q__1.imag(); q__2.real() = -ci.real(), q__2.imag() = -ci.imag(); q__1.real() = q__2.real() * cspn.real() - q__2.imag() * cspn.imag(), q__1.imag() = q__2.real() * cspn.imag() + q__2.imag() * cspn.real(); cspn.real() = q__1.real(), cspn.imag() = q__1.imag(); /* L50: */ } if(yy < (float)0.) { i__1 = *n; for(i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; r_cnjg(&q__1, &cy[i__]); cy[i__2].real() = q__1.real(), cy[i__2].imag() = q__1.imag(); /* L55: */ } } return 0; L60: r1 = cos(xx); r2 = sin(xx); q__1.real() = r1, q__1.imag() = r2; ex.real() = q__1.real(), ex.imag() = q__1.imag(); /* Computing MAX */ r__1 = r1mach_(&c__4); tol = max(r__1, (float)1e-18); k1 = i1mach_(&c__12); k2 = i1mach_(&c__13); /* Computing MIN */ i__1 = abs(k1), i__2 = abs(k2); k = std::min(i__1, i__2); r1m5 = r1mach_(&c__5); /* ----------------------------------------------------------------------- */ /* ELIM IS THE APPROXIMATE EXPONENTIAL UNDER- AND OVERFLOW LIMIT */ /* ----------------------------------------------------------------------- */ elim = ((float)k * r1m5 - (float)3.) * (float)2.303; ey = (float)0.; tay = (r__1 = yy + yy, abs(r__1)); if(tay < elim) { ey = exp(-tay); } q__3.real() = ey, q__3.imag() = (float)0.; q__2.real() = ex.real() * q__3.real() - ex.imag() * q__3.imag(), q__2.imag() = ex.real() * q__3.imag() + ex.imag() * q__3.real(); q__1.real() = q__2.real() * cspn.real() - q__2.imag() * cspn.imag(), q__1.imag() = q__2.real() * cspn.imag() + q__2.imag() * cspn.real(); cspn.real() = q__1.real(), cspn.imag() = q__1.imag(); *nz = 0; rtol = (float)1. / tol; ascle = r1mach_(&c__1) * rtol * (float)1e3; i__1 = *n; for(i__ = 1; i__ <= i__1; ++i__) { /* ---------------------------------------------------------------------- */ /* CY(I) = CSGN*CY(I)-CSPN*CWRK(I): PRODUCTS ARE COMPUTED IN */ /* SCALED MODE IF CY(I) OR CWRK(I) ARE CLOSE TO UNDERFLOW TO */ /* PREVENT UNDERFLOW IN AN INTERMEDIATE COMPUTATION. */ /* ---------------------------------------------------------------------- */ i__2 = i__; zv.real() = cwrk[i__2].real(), zv.imag() = cwrk[i__2].imag(); aa = zv.real(); bb = r_imag(&zv); atol = (float)1.; /* Computing MAX */ r__1 = abs(aa), r__2 = abs(bb); if(max(r__1, r__2) > ascle) { goto L75; } q__2.real() = rtol, q__2.imag() = (float)0.; q__1.real() = zv.real() * q__2.real() - zv.imag() * q__2.imag(), q__1.imag() = zv.real() * q__2.imag() + zv.imag() * q__2.real(); zv.real() = q__1.real(), zv.imag() = q__1.imag(); atol = tol; L75: q__1.real() = zv.real() * cspn.real() - zv.imag() * cspn.imag(), q__1.imag() = zv.real() * cspn.imag() + zv.imag() * cspn.real(); zv.real() = q__1.real(), zv.imag() = q__1.imag(); q__2.real() = atol, q__2.imag() = (float)0.; q__1.real() = zv.real() * q__2.real() - zv.imag() * q__2.imag(), q__1.imag() = zv.real() * q__2.imag() + zv.imag() * q__2.real(); zv.real() = q__1.real(), zv.imag() = q__1.imag(); i__2 = i__; zu.real() = cy[i__2].real(), zu.imag() = cy[i__2].imag(); aa = zu.real(); bb = r_imag(&zu); atol = (float)1.; /* Computing MAX */ r__1 = abs(aa), r__2 = abs(bb); if(max(r__1, r__2) > ascle) { goto L85; } q__2.real() = rtol, q__2.imag() = (float)0.; q__1.real() = zu.real() * q__2.real() - zu.imag() * q__2.imag(), q__1.imag() = zu.real() * q__2.imag() + zu.imag() * q__2.real(); zu.real() = q__1.real(), zu.imag() = q__1.imag(); atol = tol; L85: q__1.real() = zu.real() * csgn.real() - zu.imag() * csgn.imag(), q__1.imag() = zu.real() * csgn.imag() + zu.imag() * csgn.real(); zu.real() = q__1.real(), zu.imag() = q__1.imag(); q__2.real() = atol, q__2.imag() = (float)0.; q__1.real() = zu.real() * q__2.real() - zu.imag() * q__2.imag(), q__1.imag() = zu.real() * q__2.imag() + zu.imag() * q__2.real(); zu.real() = q__1.real(), zu.imag() = q__1.imag(); i__2 = i__; q__1.real() = zu.real() - zv.real(), q__1.imag() = zu.imag() - zv.imag(); cy[i__2].real() = q__1.real(), cy[i__2].imag() = q__1.imag(); if(yy < (float)0.) { i__2 = i__; r_cnjg(&q__1, &cy[i__]); cy[i__2].real() = q__1.real(), cy[i__2].imag() = q__1.imag(); } i__2 = i__; if(cy[i__2].real() == (float)0. && cy[i__2].imag() == (float)0. && ey == (float)0.) { ++(*nz); } q__1.real() = ci.real() * csgn.real() - ci.imag() * csgn.imag(), q__1.imag() = ci.real() * csgn.imag() + ci.imag() * csgn.real(); csgn.real() = q__1.real(), csgn.imag() = q__1.imag(); q__2.real() = -ci.real(), q__2.imag() = -ci.imag(); q__1.real() = q__2.real() * cspn.real() - q__2.imag() * cspn.imag(), q__1.imag() = q__2.real() * cspn.imag() + q__2.imag() * cspn.real(); cspn.real() = q__1.real(), cspn.imag() = q__1.imag(); /* L80: */ } return 0; L90: *nz = 0; return 0; } /* cbesy_ */ int cbinu_(System::Complex<float>* z__, float* fnu, int32* kode, int32* n, System::Complex<float>* cy, int32* nz, float* rl, float* fnul, float* tol, float* elim, float* alim) { /* Initialized data */ static System::Complex<float> czero = {(float)0., (float)0.}; /* System generated locals */ int32 i__1, i__2; int32 i__; System::Complex<float> cw[2]; float az; int32 nn, nw, nui, inw; float dfnu; int32 nlast; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE CBINU */ /* ***REFER TO CBESH,CBESI,CBESJ,CBESK,CAIRY,CBIRY */ /* c CBINU COMPUTES THE I FUNCTION IN THE RIGHT HALF Z PLANE. */ /* ***ROUTINES CALLED CASYI,CBUNI,CMLRI,CSERI,CUOIK,CWRSK */ /* ***END PROLOGUE CBINU */ /* Parameter adjustments */ --cy; /* Function Body */ *nz = 0; az = c_abs(z__); nn = *n; dfnu = *fnu + (float)(*n - 1); if(az <= (float)2.) { goto L10; } if(az * az * (float).25 > dfnu + (float)1.) { goto L20; } L10: /* ----------------------------------------------------------------------- */ /* POWER SERIES */ /* ----------------------------------------------------------------------- */ cseri_(z__, fnu, kode, &nn, &cy[1], &nw, tol, elim, alim); inw = abs(nw); *nz += inw; nn -= inw; if(nn == 0) { return 0; } if(nw >= 0) { goto L120; } dfnu = *fnu + (float)(nn - 1); L20: if(az < *rl) { goto L40; } if(dfnu <= (float)1.) { goto L30; } if(az + az < dfnu * dfnu) { goto L50; } /* ----------------------------------------------------------------------- */ /* ASYMPTOTIC EXPANSION FOR LARGE Z */ /* ----------------------------------------------------------------------- */ L30: casyi_(z__, fnu, kode, &nn, &cy[1], &nw, rl, tol, elim, alim); if(nw < 0) { goto L130; } goto L120; L40: if(dfnu <= (float)1.) { goto L70; } L50: /* ----------------------------------------------------------------------- */ /* OVERFLOW AND UNDERFLOW TEST ON I SEQUENCE FOR MILLER ALGORITHM */ /* ----------------------------------------------------------------------- */ cuoik_(z__, fnu, kode, &c__1, &nn, &cy[1], &nw, tol, elim, alim); if(nw < 0) { goto L130; } *nz += nw; nn -= nw; if(nn == 0) { return 0; } dfnu = *fnu + (float)(nn - 1); if(dfnu > *fnul) { goto L110; } if(az > *fnul) { goto L110; } L60: if(az > *rl) { goto L80; } L70: /* ----------------------------------------------------------------------- */ /* MILLER ALGORITHM NORMALIZED BY THE SERIES */ /* ----------------------------------------------------------------------- */ cmlri_(z__, fnu, kode, &nn, &cy[1], &nw, tol); if(nw < 0) { goto L130; } goto L120; L80: /* ----------------------------------------------------------------------- */ /* MILLER ALGORITHM NORMALIZED BY THE WRONSKIAN */ /* ----------------------------------------------------------------------- */ /* ----------------------------------------------------------------------- */ /* OVERFLOW TEST ON K FUNCTIONS USED IN WRONSKIAN */ /* ----------------------------------------------------------------------- */ cuoik_(z__, fnu, kode, &c__2, &c__2, cw, &nw, tol, elim, alim); if(nw >= 0) { goto L100; } *nz = nn; i__1 = nn; for(i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; cy[i__2].real() = czero.real(), cy[i__2].imag() = czero.imag(); /* L90: */ } return 0; L100: if(nw > 0) { goto L130; } cwrsk_(z__, fnu, kode, &nn, &cy[1], &nw, cw, tol, elim, alim); if(nw < 0) { goto L130; } goto L120; L110: /* ----------------------------------------------------------------------- */ /* INCREMENT FNU+NN-1 UP TO FNUL, COMPUTE AND RECUR BACKWARD */ /* ----------------------------------------------------------------------- */ nui = (int32)(*fnul - dfnu) + 1; nui = max(nui, 0); cbuni_(z__, fnu, kode, &nn, &cy[1], &nw, &nui, &nlast, fnul, tol, elim, alim); if(nw < 0) { goto L130; } *nz += nw; if(nlast == 0) { goto L120; } nn = nlast; goto L60; L120: return 0; L130: *nz = -1; if(nw == -2) { *nz = -2; } return 0; } /* cbinu_ */ int cbiry_(System::Complex<float>* z__, int32* id, int32* kode, System::Complex<float>* bi, int32* ierr) { /* Initialized data */ static float tth = (float).666666666666666667; static float c1 = (float).614926627446000736; static float c2 = (float).448288357353826359; static float coef = (float).577350269189625765; static float pi = (float)3.14159265358979324; static System::Complex<float> cone = {(float)1., (float)0.}; /* System generated locals */ int32 i__1, i__2; float r__1, r__2; double d__1, d__2; System::Complex<float> q__1, q__2, q__3, q__4, q__5, q__6; int32 k; float d1, d2; int32 k1, k2; System::Complex<float> s1, s2, z3; float aa, bb, ad, ak, bk, ck, dk, az; System::Complex<float> cy[2]; float rl, zi; int32 nz; float zr, az3, z3i, z3r, fid, dig, fmr, r1m5; System::Complex<float> csq; float fnu; System::Complex<float> zta; float tol; System::Complex<float> trm1, trm2; float sfac, alim, elim, atrm, fnul; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE CBIRY */ /* ***DATE WRITTEN 830501 (YYMMDD) */ /* ***REVISION DATE 890801, 930101 (YYMMDD) */ /* ***CATEGORY NO. B5K */ /* ***KEYWORDS AIRY FUNCTION,BESSEL FUNCTIONS OF ORDER ONE THIRD */ /* ***AUTHOR AMOS, DONALD E., SANDIA NATIONAL LABORATORIES */ /* ***PURPOSE TO COMPUTE AIRY FUNCTIONS BI(Z) AND DBI(Z) FOR COMPLEX Z */ /* ***DESCRIPTION */ /* ON KODE=1, CBIRY COMPUTES THE COMPLEX AIRY FUNCTION BI(Z) OR */ /* ITS DERIVATIVE DBI(Z)/DZ ON ID=0 OR ID=1 RESPECTIVELY. ON */ /* KODE=2, A SCALING OPTION CEXP(-AXZTA)*BI(Z) OR CEXP(-AXZTA)* */ /* DBI(Z)/DZ IS PROVIDED TO REMOVE THE EXPONENTIAL BEHAVIOR IN */ /* BOTH THE LEFT AND RIGHT HALF PLANES WHERE */ /* ZTA=(2/3)*Z*CSQRT(Z)=CMPLX(XZTA,YZTA) AND AXZTA=ABS(XZTA). */ /* DEFINITIONS AND NOTATION ARE FOUND IN THE NBS HANDBOOK OF */ /* MATHEMATICAL FUNCTIONS (REF. 1). */ /* INPUT */ /* Z - Z=CMPLX(X,Y) */ /* ID - ORDER OF DERIVATIVE, ID=0 OR ID=1 */ /* KODE - A PARAMETER TO INDICATE THE SCALING OPTION */ /* KODE= 1 RETURNS */ /* BI=BI(Z) ON ID=0 OR */ /* BI=DBI(Z)/DZ ON ID=1 */ /* = 2 RETURNS */ /* BI=CEXP(-AXZTA)*BI(Z) ON ID=0 OR */ /* BI=CEXP(-AXZTA)*DBI(Z)/DZ ON ID=1 WHERE */ /* ZTA=(2/3)*Z*CSQRT(Z)=CMPLX(XZTA,YZTA) */ /* AND AXZTA=ABS(XZTA) */ /* OUTPUT */ /* BI - COMPLEX ANSWER DEPENDING ON THE CHOICES FOR ID AND */ /* KODE */ /* IERR - ERROR FLAG */ /* IERR=0, NORMAL RETURN - COMPUTATION COMPLETED */ /* IERR=1, INPUT ERROR - NO COMPUTATION */ /* IERR=2, OVERFLOW - NO COMPUTATION, REAL(Z) */ /* TOO LARGE WITH KODE=1 */ /* IERR=3, CABS(Z) LARGE - COMPUTATION COMPLETED */ /* LOSSES OF SIGNIFCANCE BY ARGUMENT REDUCTION */ /* PRODUCE LESS THAN HALF OF MACHINE ACCURACY */ /* IERR=4, CABS(Z) TOO LARGE - NO COMPUTATION */ /* COMPLETE LOSS OF ACCURACY BY ARGUMENT */ /* REDUCTION */ /* IERR=5, ERROR - NO COMPUTATION, */ /* ALGORITHM TERMINATION CONDITION NOT MET */ /* ***LONG DESCRIPTION */ /* BI AND DBI ARE COMPUTED FOR CABS(Z).GT.1.0 FROM THE I BESSEL */ /* FUNCTIONS BY */ /* BI(Z)=C*SQRT(Z)*( I(-1/3,ZTA) + I(1/3,ZTA) ) */ /* DBI(Z)=C * Z * ( I(-2/3,ZTA) + I(2/3,ZTA) ) */ /* C=1.0/SQRT(3.0) */ /* ZTA=(2/3)*Z**(3/2) */ /* WITH THE POWER SERIES FOR CABS(Z).LE.1.0. */ /* IN MOST COMPLEX VARIABLE COMPUTATION, ONE MUST EVALUATE ELE- */ /* MENTARY FUNCTIONS. WHEN THE MAGNITUDE OF Z IS LARGE, LOSSES */ /* OF SIGNIFICANCE BY ARGUMENT REDUCTION OCCUR. CONSEQUENTLY, IF */ /* THE MAGNITUDE OF ZETA=(2/3)*Z**1.5 EXCEEDS U1=SQRT(0.5/UR), */ /* THEN LOSSES EXCEEDING HALF PRECISION ARE LIKELY AND AN ERROR */ /* FLAG IERR=3 IS TRIGGERED WHERE UR=R1MACH(4)=UNIT ROUNDOFF. */ /* ALSO, IF THE MAGNITUDE OF ZETA IS LARGER THAN U2=0.5/UR, THEN */ /* ALL SIGNIFICANCE IS LOST AND IERR=4. IN ORDER TO USE THE INT */ /* FUNCTION, ZETA MUST BE FURTHER RESTRICTED NOT TO EXCEED THE */ /* LARGEST INTEGER, U3=I1MACH(9). THUS, THE MAGNITUDE OF ZETA */ /* MUST BE RESTRICTED BY MIN(U2,U3). ON 32 BIT MACHINES, U1,U2, */ /* AND U3 ARE APPROXIMATELY 2.0E+3, 4.2E+6, 2.1E+9 IN SINGLE */ /* PRECISION ARITHMETIC AND 1.3E+8, 1.8E+16, 2.1E+9 IN DOUBLE */ /* PRECISION ARITHMETIC RESPECTIVELY. THIS MAKES U2 AND U3 LIMIT- */ /* ING IN THEIR RESPECTIVE ARITHMETICS. THIS MEANS THAT THE MAG- */ /* NITUDE OF Z CANNOT EXCEED 3.1E+4 IN SINGLE AND 2.1E+6 IN */ /* DOUBLE PRECISION ARITHMETIC. THIS ALSO MEANS THAT ONE CAN */ /* EXPECT TO RETAIN, IN THE WORST CASES ON 32 BIT MACHINES, */ /* NO DIGITS IN SINGLE PRECISION AND ONLY 7 DIGITS IN DOUBLE */ /* PRECISION ARITHMETIC. */ /* THE APPROXIMATE RELATIVE ERROR IN THE MAGNITUDE OF A COMPLEX */ /* BESSEL FUNCTION CAN BE EXPRESSED BY P*10**S WHERE P=MAX(UNIT */ /* ROUNDOFF,1.0E-18) IS THE NOMINAL PRECISION AND 10**S REPRE- */ /* SENTS THE INCREASE IN ERROR DUE TO ARGUMENT REDUCTION IN THE */ /* ELEMENTARY FUNCTIONS. HERE, S=MAX(1,ABS(LOG10(CABS(Z))), */ /* ABS(LOG10(FNU))) APPROXIMATELY (I.E. S=MAX(1,ABS(EXPONENT OF */ /* CABS(Z),ABS(EXPONENT OF FNU)) ). HOWEVER, THE PHASE ANGLE MAY */ /* HAVE ONLY ABSOLUTE ACCURACY. THIS IS MOST LIKELY TO OCCUR WHEN */ /* ONE COMPONENT (IN ABSOLUTE VALUE) IS LARGER THAN THE OTHER BY */ /* SEVERAL ORDERS OF MAGNITUDE. IF ONE COMPONENT IS 10**K LARGER */ /* THAN THE OTHER, THEN ONE CAN EXPECT ONLY MAX(ABS(LOG10(P))-K, */ /* 0) SIGNIFICANT DIGITS; OR, STATED ANOTHER WAY, WHEN K EXCEEDS */ /* THE EXPONENT OF P, NO SIGNIFICANT DIGITS REMAIN IN THE SMALLER */ /* COMPONENT. HOWEVER, THE PHASE ANGLE RETAINS ABSOLUTE ACCURACY */ /* BECAUSE, IN COMPLEX ARITHMETIC WITH PRECISION P, THE SMALLER */ /* COMPONENT WILL NOT (AS A RULE) DECREASE BELOW P TIMES THE */ /* MAGNITUDE OF THE LARGER COMPONENT. IN THESE EXTREME CASES, */ /* THE PRINCIPAL PHASE ANGLE IS ON THE ORDER OF +P, -P, PI/2-P, */ /* OR -PI/2+P. */ /* ***REFERENCES HANDBOOK OF MATHEMATICAL FUNCTIONS BY M. ABRAMOWITZ */ /* AND I. A. STEGUN, NBS AMS SERIES 55, U.S. DEPT. OF */ /* COMMERCE, 1955. */ /* COMPUTATION OF BESSEL FUNCTIONS OF COMPLEX ARGUMENT */ /* AND LARGE ORDER BY D. E. AMOS, SAND83-0643, MAY, 1983 */ /* A SUBROUTINE PACKAGE FOR BESSEL FUNCTIONS OF A COMPLEX */ /* ARGUMENT AND NONNEGATIVE ORDER BY D. E. AMOS, SAND85- */ /* 1018, MAY, 1985 */ /* A PORTABLE PACKAGE FOR BESSEL FUNCTIONS OF A COMPLEX */ /* ARGUMENT AND NONNEGATIVE ORDER BY D. E. AMOS, ACM */ /* TRANS. MATH. SOFTWARE, VOL. 12, NO. 3, SEPTEMBER 1986, */ /* PP 265-273. */ /* ***ROUTINES CALLED CBINU,I1MACH,R1MACH */ /* ***END PROLOGUE CBIRY */ /* ***FIRST EXECUTABLE STATEMENT CBIRY */ *ierr = 0; nz = 0; if(*id < 0 || *id > 1) { *ierr = 1; } if(*kode < 1 || *kode > 2) { *ierr = 1; } if(*ierr != 0) { return 0; } az = c_abs(z__); /* Computing MAX */ r__1 = r1mach_(&c__4); tol = max(r__1, (float)1e-18); fid = (float)(*id); if(az > (float)1.) { goto L60; } /* ----------------------------------------------------------------------- */ /* POWER SERIES FOR CABS(Z).LE.1. */ /* ----------------------------------------------------------------------- */ s1.real() = cone.real(), s1.imag() = cone.imag(); s2.real() = cone.real(), s2.imag() = cone.imag(); if(az < tol) { goto L110; } aa = az * az; if(aa < tol / az) { goto L40; } trm1.real() = cone.real(), trm1.imag() = cone.imag(); trm2.real() = cone.real(), trm2.imag() = cone.imag(); atrm = (float)1.; q__2.real() = z__->real() * z__->real() - z__->imag() * z__->imag(), q__2.imag() = z__->real() * z__->imag() + z__->imag() * z__->real(); q__1.real() = q__2.real() * z__->real() - q__2.imag() * z__->imag(), q__1.imag() = q__2.real() * z__->imag() + q__2.imag() * z__->real(); z3.real() = q__1.real(), z3.imag() = q__1.imag(); az3 = az * aa; ak = fid + (float)2.; bk = (float)3. - fid - fid; ck = (float)4. - fid; dk = fid + (float)3. + fid; d1 = ak * dk; d2 = bk * ck; ad = std::min(d1, d2); ak = fid * (float)9. + (float)24.; bk = (float)30. - fid * (float)9.; z3r = z3.real(); z3i = r_imag(&z3); for(k = 1; k <= 25; ++k) { r__1 = z3r / d1; r__2 = z3i / d1; q__2.real() = r__1, q__2.imag() = r__2; q__1.real() = trm1.real() * q__2.real() - trm1.imag() * q__2.imag(), q__1.imag() = trm1.real() * q__2.imag() + trm1.imag() * q__2.real(); trm1.real() = q__1.real(), trm1.imag() = q__1.imag(); q__1.real() = s1.real() + trm1.real(), q__1.imag() = s1.imag() + trm1.imag(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); r__1 = z3r / d2; r__2 = z3i / d2; q__2.real() = r__1, q__2.imag() = r__2; q__1.real() = trm2.real() * q__2.real() - trm2.imag() * q__2.imag(), q__1.imag() = trm2.real() * q__2.imag() + trm2.imag() * q__2.real(); trm2.real() = q__1.real(), trm2.imag() = q__1.imag(); q__1.real() = s2.real() + trm2.real(), q__1.imag() = s2.imag() + trm2.imag(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); atrm = atrm * az3 / ad; d1 += ak; d2 += bk; ad = std::min(d1, d2); if(atrm < tol * ad) { goto L40; } ak += (float)18.; bk += (float)18.; /* L30: */ } L40: if(*id == 1) { goto L50; } q__3.real() = c1, q__3.imag() = (float)0.; q__2.real() = s1.real() * q__3.real() - s1.imag() * q__3.imag(), q__2.imag() = s1.real() * q__3.imag() + s1.imag() * q__3.real(); q__5.real() = z__->real() * s2.real() - z__->imag() * s2.imag(), q__5.imag() = z__->real() * s2.imag() + z__->imag() * s2.real(); q__6.real() = c2, q__6.imag() = (float)0.; q__4.real() = q__5.real() * q__6.real() - q__5.imag() * q__6.imag(), q__4.imag() = q__5.real() * q__6.imag() + q__5.imag() * q__6.real(); q__1.real() = q__2.real() + q__4.real(), q__1.imag() = q__2.imag() + q__4.imag(); bi->real() = q__1.real(), bi->imag() = q__1.imag(); if(*kode == 1) { return 0; } c_sqrt(&q__3, z__); q__2.real() = z__->real() * q__3.real() - z__->imag() * q__3.imag(), q__2.imag() = z__->real() * q__3.imag() + z__->imag() * q__3.real(); q__4.real() = tth, q__4.imag() = (float)0.; q__1.real() = q__2.real() * q__4.real() - q__2.imag() * q__4.imag(), q__1.imag() = q__2.real() * q__4.imag() + q__2.imag() * q__4.real(); zta.real() = q__1.real(), zta.imag() = q__1.imag(); aa = zta.real(); aa = -abs(aa); r__1 = exp(aa); q__2.real() = r__1, q__2.imag() = (float)0.; q__1.real() = bi->real() * q__2.real() - bi->imag() * q__2.imag(), q__1.imag() = bi->real() * q__2.imag() + bi->imag() * q__2.real(); bi->real() = q__1.real(), bi->imag() = q__1.imag(); return 0; L50: q__2.real() = c2, q__2.imag() = (float)0.; q__1.real() = s2.real() * q__2.real() - s2.imag() * q__2.imag(), q__1.imag() = s2.real() * q__2.imag() + s2.imag() * q__2.real(); bi->real() = q__1.real(), bi->imag() = q__1.imag(); if(az > tol) { q__4.real() = z__->real() * z__->real() - z__->imag() * z__->imag(), q__4.imag() = z__->real() * z__->imag() + z__->imag() * z__->real(); q__3.real() = q__4.real() * s1.real() - q__4.imag() * s1.imag(), q__3.imag() = q__4.real() * s1.imag() + q__4.imag() * s1.real(); r__1 = c1 / (fid + (float)1.); q__5.real() = r__1, q__5.imag() = (float)0.; q__2.real() = q__3.real() * q__5.real() - q__3.imag() * q__5.imag(), q__2.imag() = q__3.real() * q__5.imag() + q__3.imag() * q__5.real(); q__1.real() = bi->real() + q__2.real(), q__1.imag() = bi->imag() + q__2.imag(); bi->real() = q__1.real(), bi->imag() = q__1.imag(); } if(*kode == 1) { return 0; } c_sqrt(&q__3, z__); q__2.real() = z__->real() * q__3.real() - z__->imag() * q__3.imag(), q__2.imag() = z__->real() * q__3.imag() + z__->imag() * q__3.real(); q__4.real() = tth, q__4.imag() = (float)0.; q__1.real() = q__2.real() * q__4.real() - q__2.imag() * q__4.imag(), q__1.imag() = q__2.real() * q__4.imag() + q__2.imag() * q__4.real(); zta.real() = q__1.real(), zta.imag() = q__1.imag(); aa = zta.real(); aa = -abs(aa); r__1 = exp(aa); q__2.real() = r__1, q__2.imag() = (float)0.; q__1.real() = bi->real() * q__2.real() - bi->imag() * q__2.imag(), q__1.imag() = bi->real() * q__2.imag() + bi->imag() * q__2.real(); bi->real() = q__1.real(), bi->imag() = q__1.imag(); return 0; /* ----------------------------------------------------------------------- */ /* CASE FOR CABS(Z).GT.1.0 */ /* ----------------------------------------------------------------------- */ L60: fnu = (fid + (float)1.) / (float)3.; /* ----------------------------------------------------------------------- */ /* SET PARAMETERS RELATED TO MACHINE CONSTANTS. */ /* TOL IS THE APPROXIMATE UNIT ROUNDOFF LIMITED TO 1.0E-18. */ /* ELIM IS THE APPROXIMATE EXPONENTIAL OVER- AND UNDERFLOW LIMIT. */ /* EXP(-ELIM).LT.EXP(-ALIM)=EXP(-ELIM)/TOL AND */ /* EXP(ELIM).GT.EXP(ALIM)=EXP(ELIM)*TOL ARE INTERVALS NEAR */ /* UNDERFLOW AND OVERFLOW LIMITS WHERE SCALED ARITHMETIC IS DONE. */ /* RL IS THE LOWER BOUNDARY OF THE ASYMPTOTIC EXPANSION FOR LARGE Z. */ /* DIG = NUMBER OF BASE 10 DIGITS IN TOL = 10**(-DIG). */ /* FNUL IS THE LOWER BOUNDARY OF THE ASYMPTOTIC SERIES FOR LARGE FNU. */ /* ----------------------------------------------------------------------- */ k1 = i1mach_(&c__12); k2 = i1mach_(&c__13); r1m5 = r1mach_(&c__5); /* Computing MIN */ i__1 = abs(k1), i__2 = abs(k2); k = std::min(i__1, i__2); elim = ((float)k * r1m5 - (float)3.) * (float)2.303; k1 = i1mach_(&c__11) - 1; aa = r1m5 * (float)k1; dig = std::min(aa, (float)18.); aa *= (float)2.303; /* Computing MAX */ r__1 = -aa; alim = elim + max(r__1, (float)-41.45); rl = dig * (float)1.2 + (float)3.; fnul = (dig - (float)3.) * (float)6. + (float)10.; /* ----------------------------------------------------------------------- */ /* TEST FOR RANGE */ /* ----------------------------------------------------------------------- */ aa = (float).5 / tol; bb = (float)i1mach_(&c__9) * (float).5; aa = std::min(aa, bb); d__1 = (double)aa; d__2 = (double)tth; aa = pow_dd(&d__1, &d__2); if(az > aa) { goto L190; } aa = sqrt(aa); if(az > aa) { *ierr = 3; } c_sqrt(&q__1, z__); csq.real() = q__1.real(), csq.imag() = q__1.imag(); q__2.real() = z__->real() * csq.real() - z__->imag() * csq.imag(), q__2.imag() = z__->real() * csq.imag() + z__->imag() * csq.real(); q__3.real() = tth, q__3.imag() = (float)0.; q__1.real() = q__2.real() * q__3.real() - q__2.imag() * q__3.imag(), q__1.imag() = q__2.real() * q__3.imag() + q__2.imag() * q__3.real(); zta.real() = q__1.real(), zta.imag() = q__1.imag(); /* ----------------------------------------------------------------------- */ /* RE(ZTA).LE.0 WHEN RE(Z).LT.0, ESPECIALLY WHEN IM(Z) IS SMALL */ /* ----------------------------------------------------------------------- */ sfac = (float)1.; zi = r_imag(z__); zr = z__->real(); ak = r_imag(&zta); if(zr >= (float)0.) { goto L70; } bk = zta.real(); ck = -abs(bk); q__1.real() = ck, q__1.imag() = ak; zta.real() = q__1.real(), zta.imag() = q__1.imag(); L70: if(zi == (float)0. && zr <= (float)0.) { q__1.real() = (float)0., q__1.imag() = ak; zta.real() = q__1.real(), zta.imag() = q__1.imag(); } aa = zta.real(); if(*kode == 2) { goto L80; } /* ----------------------------------------------------------------------- */ /* OVERFLOW TEST */ /* ----------------------------------------------------------------------- */ bb = abs(aa); if(bb < alim) { goto L80; } bb += log(az) * (float).25; sfac = tol; if(bb > elim) { goto L170; } L80: fmr = (float)0.; if(aa >= (float)0. && zr > (float)0.) { goto L90; } fmr = pi; if(zi < (float)0.) { fmr = -pi; } q__1.real() = -zta.real(), q__1.imag() = -zta.imag(); zta.real() = q__1.real(), zta.imag() = q__1.imag(); L90: /* ----------------------------------------------------------------------- */ /* AA=FACTOR FOR ANALYTIC CONTINUATION OF I(FNU,ZTA) */ /* KODE=2 RETURNS EXP(-ABS(XZTA))*I(FNU,ZTA) FROM CBINU */ /* ----------------------------------------------------------------------- */ cbinu_(&zta, &fnu, kode, &c__1, cy, &nz, &rl, &fnul, &tol, &elim, &alim); if(nz < 0) { goto L180; } aa = fmr * fnu; q__1.real() = sfac, q__1.imag() = (float)0.; z3.real() = q__1.real(), z3.imag() = q__1.imag(); r__1 = cos(aa); r__2 = sin(aa); q__3.real() = r__1, q__3.imag() = r__2; q__2.real() = cy[0].real() * q__3.real() - cy[0].imag() * q__3.imag(), q__2.imag() = cy[0].real() * q__3.imag() + cy[0].imag() * q__3.real(); q__1.real() = q__2.real() * z3.real() - q__2.imag() * z3.imag(), q__1.imag() = q__2.real() * z3.imag() + q__2.imag() * z3.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); fnu = ((float)2. - fid) / (float)3.; cbinu_(&zta, &fnu, kode, &c__2, cy, &nz, &rl, &fnul, &tol, &elim, &alim); q__1.real() = cy[0].real() * z3.real() - cy[0].imag() * z3.imag(), q__1.imag() = cy[0].real() * z3.imag() + cy[0].imag() * z3.real(); cy[0].real() = q__1.real(), cy[0].imag() = q__1.imag(); q__1.real() = cy[1].real() * z3.real() - cy[1].imag() * z3.imag(), q__1.imag() = cy[1].real() * z3.imag() + cy[1].imag() * z3.real(); cy[1].real() = q__1.real(), cy[1].imag() = q__1.imag(); /* ----------------------------------------------------------------------- */ /* BACKWARD RECUR ONE STEP FOR ORDERS -1/3 OR -2/3 */ /* ----------------------------------------------------------------------- */ r__1 = fnu + fnu; q__4.real() = r__1, q__4.imag() = (float)0.; q__3.real() = cy[0].real() * q__4.real() - cy[0].imag() * q__4.imag(), q__3.imag() = cy[0].real() * q__4.imag() + cy[0].imag() * q__4.real(); c_div(&q__2, &q__3, &zta); q__1.real() = q__2.real() + cy[1].real(), q__1.imag() = q__2.imag() + cy[1].imag(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); aa = fmr * (fnu - (float)1.); r__1 = cos(aa); r__2 = sin(aa); q__4.real() = r__1, q__4.imag() = r__2; q__3.real() = s2.real() * q__4.real() - s2.imag() * q__4.imag(), q__3.imag() = s2.real() * q__4.imag() + s2.imag() * q__4.real(); q__2.real() = s1.real() + q__3.real(), q__2.imag() = s1.imag() + q__3.imag(); q__5.real() = coef, q__5.imag() = (float)0.; q__1.real() = q__2.real() * q__5.real() - q__2.imag() * q__5.imag(), q__1.imag() = q__2.real() * q__5.imag() + q__2.imag() * q__5.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); if(*id == 1) { goto L100; } q__1.real() = csq.real() * s1.real() - csq.imag() * s1.imag(), q__1.imag() = csq.real() * s1.imag() + csq.imag() * s1.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); r__1 = (float)1. / sfac; q__2.real() = r__1, q__2.imag() = (float)0.; q__1.real() = s1.real() * q__2.real() - s1.imag() * q__2.imag(), q__1.imag() = s1.real() * q__2.imag() + s1.imag() * q__2.real(); bi->real() = q__1.real(), bi->imag() = q__1.imag(); return 0; L100: q__1.real() = z__->real() * s1.real() - z__->imag() * s1.imag(), q__1.imag() = z__->real() * s1.imag() + z__->imag() * s1.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); r__1 = (float)1. / sfac; q__2.real() = r__1, q__2.imag() = (float)0.; q__1.real() = s1.real() * q__2.real() - s1.imag() * q__2.imag(), q__1.imag() = s1.real() * q__2.imag() + s1.imag() * q__2.real(); bi->real() = q__1.real(), bi->imag() = q__1.imag(); return 0; L110: aa = c1 * ((float)1. - fid) + fid * c2; q__1.real() = aa, q__1.imag() = (float)0.; bi->real() = q__1.real(), bi->imag() = q__1.imag(); return 0; L170: nz = 0; *ierr = 2; return 0; L180: if(nz == -1) { goto L170; } nz = 0; *ierr = 5; return 0; L190: *ierr = 4; nz = 0; return 0; } /* cbiry_ */ int cbknu_(System::Complex<float>* z__, float* fnu, int32* kode, int32* n, System::Complex<float>* y, int32* nz, float* tol, float* elim, float* alim) { /* Initialized data */ static int32 kmax = 30; static float r1 = (float)2.; static System::Complex<float> czero = {(float)0., (float)0.}; static System::Complex<float> cone = {(float)1., (float)0.}; static System::Complex<float> ctwo = {(float)2., (float)0.}; static float pi = (float)3.14159265358979324; static float rthpi = (float)1.25331413731550025; static float spi = (float)1.90985931710274403; static float hpi = (float)1.57079632679489662; static float fpi = (float)1.89769999331517738; static float tth = (float).666666666666666666; static float cc[8] = {(float).577215664901532861, (float)-.0420026350340952355, (float)-.0421977345555443367, (float).00721894324666309954, (float)-2.15241674114950973e-4, (float)-2.01348547807882387e-5, (float)1.13302723198169588e-6, (float)6.11609510448141582e-9}; /* System generated locals */ int32 i__1, i__2; float r__1, r__2; System::Complex<float> q__1, q__2, q__3, q__4, q__5, q__6; System::Complex<float> f; int32 i__, j, k; System::Complex<float> p, q; float s, a1, a2, g1, g2; System::Complex<float> p1, p2, s1, s2; float t1, t2, aa, bb, fc, ak, bk; System::Complex<float> ck; int32 ic; float fk, as; System::Complex<float> cs; int32 kk; System::Complex<float> cy[2], cz, zd; float rk, xd, tm, yd; System::Complex<float> pt; int32 nw; System::Complex<float> st, rz; float xx, yy, p2i, p2m, p2r; System::Complex<float> cch, csh; float caz, fhs, elm, fks, dnu; System::Complex<float> csr[3], css[3], fmu; float bry[3]; int32 inu; System::Complex<float> smu; float dnu2; System::Complex<float> coef, celm; float alas; System::Complex<float> cscl, crsc; int32 inub, idum, iflag, kflag, koded; float ascle; float helim; float etest; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE CBKNU */ /* ***REFER TO CBESI,CBESK,CAIRY,CBESH */ /* CBKNU COMPUTES THE K BESSEL FUNCTION IN THE RIGHT HALF Z PLANE */ /* ***ROUTINES CALLED CKSCL,CSHCH,GAMLN,I1MACH,R1MACH,CUCHK */ /* ***END PROLOGUE CBKNU */ /* Parameter adjustments */ --y; /* Function Body */ xx = z__->real(); yy = r_imag(z__); caz = c_abs(z__); r__1 = (float)1. / *tol; q__1.real() = r__1, q__1.imag() = (float)0.; cscl.real() = q__1.real(), cscl.imag() = q__1.imag(); q__1.real() = *tol, q__1.imag() = (float)0.; crsc.real() = q__1.real(), crsc.imag() = q__1.imag(); css[0].real() = cscl.real(), css[0].imag() = cscl.imag(); css[1].real() = cone.real(), css[1].imag() = cone.imag(); css[2].real() = crsc.real(), css[2].imag() = crsc.imag(); csr[0].real() = crsc.real(), csr[0].imag() = crsc.imag(); csr[1].real() = cone.real(), csr[1].imag() = cone.imag(); csr[2].real() = cscl.real(), csr[2].imag() = cscl.imag(); bry[0] = r1mach_(&c__1) * (float)1e3 / *tol; bry[1] = (float)1. / bry[0]; bry[2] = r1mach_(&c__2); *nz = 0; iflag = 0; koded = *kode; c_div(&q__1, &ctwo, z__); rz.real() = q__1.real(), rz.imag() = q__1.imag(); inu = (int32)(*fnu + (float).5); dnu = *fnu - (float)inu; if(abs(dnu) == (float).5) { goto L110; } dnu2 = (float)0.; if(abs(dnu) > *tol) { dnu2 = dnu * dnu; } if(caz > r1) { goto L110; } /* ----------------------------------------------------------------------- */ /* SERIES FOR CABS(Z).LE.R1 */ /* ----------------------------------------------------------------------- */ fc = (float)1.; c_log(&q__1, &rz); smu.real() = q__1.real(), smu.imag() = q__1.imag(); q__2.real() = dnu, q__2.imag() = (float)0.; q__1.real() = smu.real() * q__2.real() - smu.imag() * q__2.imag(), q__1.imag() = smu.real() * q__2.imag() + smu.imag() * q__2.real(); fmu.real() = q__1.real(), fmu.imag() = q__1.imag(); cshch_(&fmu, &csh, &cch); if(dnu == (float)0.) { goto L10; } fc = dnu * pi; fc /= sin(fc); r__1 = (float)1. / dnu; q__2.real() = r__1, q__2.imag() = (float)0.; q__1.real() = csh.real() * q__2.real() - csh.imag() * q__2.imag(), q__1.imag() = csh.real() * q__2.imag() + csh.imag() * q__2.real(); smu.real() = q__1.real(), smu.imag() = q__1.imag(); L10: a2 = dnu + (float)1.; /* ----------------------------------------------------------------------- */ /* GAM(1-Z)*GAM(1+Z)=PI*Z/SIN(PI*Z), T1=1/GAM(1-DNU), T2=1/GAM(1+DNU) */ /* ----------------------------------------------------------------------- */ t2 = exp(-gamln_(&a2, &idum)); t1 = (float)1. / (t2 * fc); if(abs(dnu) > (float).1) { goto L40; } /* ----------------------------------------------------------------------- */ /* SERIES FOR F0 TO RESOLVE INDETERMINACY FOR SMALL ABS(DNU) */ /* ----------------------------------------------------------------------- */ ak = (float)1.; s = cc[0]; for(k = 2; k <= 8; ++k) { ak *= dnu2; tm = cc[k - 1] * ak; s += tm; if(abs(tm) < *tol) { goto L30; } /* L20: */ } L30: g1 = -s; goto L50; L40: g1 = (t1 - t2) / (dnu + dnu); L50: g2 = (t1 + t2) * (float).5 * fc; g1 *= fc; q__3.real() = g1, q__3.imag() = (float)0.; q__2.real() = q__3.real() * cch.real() - q__3.imag() * cch.imag(), q__2.imag() = q__3.real() * cch.imag() + q__3.imag() * cch.real(); q__5.real() = g2, q__5.imag() = (float)0.; q__4.real() = smu.real() * q__5.real() - smu.imag() * q__5.imag(), q__4.imag() = smu.real() * q__5.imag() + smu.imag() * q__5.real(); q__1.real() = q__2.real() + q__4.real(), q__1.imag() = q__2.imag() + q__4.imag(); f.real() = q__1.real(), f.imag() = q__1.imag(); c_exp(&q__1, &fmu); pt.real() = q__1.real(), pt.imag() = q__1.imag(); r__1 = (float).5 / t2; q__2.real() = r__1, q__2.imag() = (float)0.; q__1.real() = q__2.real() * pt.real() - q__2.imag() * pt.imag(), q__1.imag() = q__2.real() * pt.imag() + q__2.imag() * pt.real(); p.real() = q__1.real(), p.imag() = q__1.imag(); r__1 = (float).5 / t1; q__2.real() = r__1, q__2.imag() = (float)0.; c_div(&q__1, &q__2, &pt); q.real() = q__1.real(), q.imag() = q__1.imag(); s1.real() = f.real(), s1.imag() = f.imag(); s2.real() = p.real(), s2.imag() = p.imag(); ak = (float)1.; a1 = (float)1.; ck.real() = cone.real(), ck.imag() = cone.imag(); bk = (float)1. - dnu2; if(inu > 0 || *n > 1) { goto L80; } /* ----------------------------------------------------------------------- */ /* GENERATE K(FNU,Z), 0.0D0 .LE. FNU .LT. 0.5D0 AND N=1 */ /* ----------------------------------------------------------------------- */ if(caz < *tol) { goto L70; } q__2.real() = z__->real() * z__->real() - z__->imag() * z__->imag(), q__2.imag() = z__->real() * z__->imag() + z__->imag() * z__->real(); q__1.real() = q__2.real() * (float).25 - q__2.imag() * (float)0., q__1.imag() = q__2.real() * (float)0. + q__2.imag() * (float).25; cz.real() = q__1.real(), cz.imag() = q__1.imag(); t1 = caz * (float).25 * caz; L60: q__5.real() = ak, q__5.imag() = (float)0.; q__4.real() = f.real() * q__5.real() - f.imag() * q__5.imag(), q__4.imag() = f.real() * q__5.imag() + f.imag() * q__5.real(); q__3.real() = q__4.real() + p.real(), q__3.imag() = q__4.imag() + p.imag(); q__2.real() = q__3.real() + q.real(), q__2.imag() = q__3.imag() + q.imag(); r__1 = (float)1. / bk; q__6.real() = r__1, q__6.imag() = (float)0.; q__1.real() = q__2.real() * q__6.real() - q__2.imag() * q__6.imag(), q__1.imag() = q__2.real() * q__6.imag() + q__2.imag() * q__6.real(); f.real() = q__1.real(), f.imag() = q__1.imag(); r__1 = (float)1. / (ak - dnu); q__2.real() = r__1, q__2.imag() = (float)0.; q__1.real() = p.real() * q__2.real() - p.imag() * q__2.imag(), q__1.imag() = p.real() * q__2.imag() + p.imag() * q__2.real(); p.real() = q__1.real(), p.imag() = q__1.imag(); r__1 = (float)1. / (ak + dnu); q__2.real() = r__1, q__2.imag() = (float)0.; q__1.real() = q.real() * q__2.real() - q.imag() * q__2.imag(), q__1.imag() = q.real() * q__2.imag() + q.imag() * q__2.real(); q.real() = q__1.real(), q.imag() = q__1.imag(); rk = (float)1. / ak; q__2.real() = ck.real() * cz.real() - ck.imag() * cz.imag(), q__2.imag() = ck.real() * cz.imag() + ck.imag() * cz.real(); q__3.real() = rk, q__3.imag() = (float)0.; q__1.real() = q__2.real() * q__3.real() - q__2.imag() * q__3.imag(), q__1.imag() = q__2.real() * q__3.imag() + q__2.imag() * q__3.real(); ck.real() = q__1.real(), ck.imag() = q__1.imag(); q__2.real() = ck.real() * f.real() - ck.imag() * f.imag(), q__2.imag() = ck.real() * f.imag() + ck.imag() * f.real(); q__1.real() = s1.real() + q__2.real(), q__1.imag() = s1.imag() + q__2.imag(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); a1 = a1 * t1 * rk; bk = bk + ak + ak + (float)1.; ak += (float)1.; if(a1 > *tol) { goto L60; } L70: y[1].real() = s1.real(), y[1].imag() = s1.imag(); if(koded == 1) { return 0; } c_exp(&q__2, z__); q__1.real() = s1.real() * q__2.real() - s1.imag() * q__2.imag(), q__1.imag() = s1.real() * q__2.imag() + s1.imag() * q__2.real(); y[1].real() = q__1.real(), y[1].imag() = q__1.imag(); return 0; /* ----------------------------------------------------------------------- */ /* GENERATE K(DNU,Z) AND K(DNU+1,Z) FOR FORWARD RECURRENCE */ /* ----------------------------------------------------------------------- */ L80: if(caz < *tol) { goto L100; } q__2.real() = z__->real() * z__->real() - z__->imag() * z__->imag(), q__2.imag() = z__->real() * z__->imag() + z__->imag() * z__->real(); q__1.real() = q__2.real() * (float).25 - q__2.imag() * (float)0., q__1.imag() = q__2.real() * (float)0. + q__2.imag() * (float).25; cz.real() = q__1.real(), cz.imag() = q__1.imag(); t1 = caz * (float).25 * caz; L90: q__5.real() = ak, q__5.imag() = (float)0.; q__4.real() = f.real() * q__5.real() - f.imag() * q__5.imag(), q__4.imag() = f.real() * q__5.imag() + f.imag() * q__5.real(); q__3.real() = q__4.real() + p.real(), q__3.imag() = q__4.imag() + p.imag(); q__2.real() = q__3.real() + q.real(), q__2.imag() = q__3.imag() + q.imag(); r__1 = (float)1. / bk; q__6.real() = r__1, q__6.imag() = (float)0.; q__1.real() = q__2.real() * q__6.real() - q__2.imag() * q__6.imag(), q__1.imag() = q__2.real() * q__6.imag() + q__2.imag() * q__6.real(); f.real() = q__1.real(), f.imag() = q__1.imag(); r__1 = (float)1. / (ak - dnu); q__2.real() = r__1, q__2.imag() = (float)0.; q__1.real() = p.real() * q__2.real() - p.imag() * q__2.imag(), q__1.imag() = p.real() * q__2.imag() + p.imag() * q__2.real(); p.real() = q__1.real(), p.imag() = q__1.imag(); r__1 = (float)1. / (ak + dnu); q__2.real() = r__1, q__2.imag() = (float)0.; q__1.real() = q.real() * q__2.real() - q.imag() * q__2.imag(), q__1.imag() = q.real() * q__2.imag() + q.imag() * q__2.real(); q.real() = q__1.real(), q.imag() = q__1.imag(); rk = (float)1. / ak; q__2.real() = ck.real() * cz.real() - ck.imag() * cz.imag(), q__2.imag() = ck.real() * cz.imag() + ck.imag() * cz.real(); q__3.real() = rk, q__3.imag() = (float)0.; q__1.real() = q__2.real() * q__3.real() - q__2.imag() * q__3.imag(), q__1.imag() = q__2.real() * q__3.imag() + q__2.imag() * q__3.real(); ck.real() = q__1.real(), ck.imag() = q__1.imag(); q__2.real() = ck.real() * f.real() - ck.imag() * f.imag(), q__2.imag() = ck.real() * f.imag() + ck.imag() * f.real(); q__1.real() = s1.real() + q__2.real(), q__1.imag() = s1.imag() + q__2.imag(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); q__5.real() = ak, q__5.imag() = (float)0.; q__4.real() = f.real() * q__5.real() - f.imag() * q__5.imag(), q__4.imag() = f.real() * q__5.imag() + f.imag() * q__5.real(); q__3.real() = p.real() - q__4.real(), q__3.imag() = p.imag() - q__4.imag(); q__2.real() = ck.real() * q__3.real() - ck.imag() * q__3.imag(), q__2.imag() = ck.real() * q__3.imag() + ck.imag() * q__3.real(); q__1.real() = s2.real() + q__2.real(), q__1.imag() = s2.imag() + q__2.imag(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); a1 = a1 * t1 * rk; bk = bk + ak + ak + (float)1.; ak += (float)1.; if(a1 > *tol) { goto L90; } L100: kflag = 2; bk = smu.real(); a1 = *fnu + (float)1.; ak = a1 * abs(bk); if(ak > *alim) { kflag = 3; } i__1 = kflag - 1; q__1.real() = s2.real() * css[i__1].real() - s2.imag() * css[i__1].imag(), q__1.imag() = s2.real() * css[i__1].imag() + s2.imag() * css[i__1].real(); p2.real() = q__1.real(), p2.imag() = q__1.imag(); q__1.real() = p2.real() * rz.real() - p2.imag() * rz.imag(), q__1.imag() = p2.real() * rz.imag() + p2.imag() * rz.real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); i__1 = kflag - 1; q__1.real() = s1.real() * css[i__1].real() - s1.imag() * css[i__1].imag(), q__1.imag() = s1.real() * css[i__1].imag() + s1.imag() * css[i__1].real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); if(koded == 1) { goto L210; } c_exp(&q__1, z__); f.real() = q__1.real(), f.imag() = q__1.imag(); q__1.real() = s1.real() * f.real() - s1.imag() * f.imag(), q__1.imag() = s1.real() * f.imag() + s1.imag() * f.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); q__1.real() = s2.real() * f.real() - s2.imag() * f.imag(), q__1.imag() = s2.real() * f.imag() + s2.imag() * f.real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); goto L210; /* ----------------------------------------------------------------------- */ /* IFLAG=0 MEANS NO UNDERFLOW OCCURRED */ /* IFLAG=1 MEANS AN UNDERFLOW OCCURRED- COMPUTATION PROCEEDS WITH */ /* KODED=2 AND A TEST FOR ON SCALE VALUES IS MADE DURING FORWARD */ /* RECURSION */ /* ----------------------------------------------------------------------- */ L110: q__2.real() = rthpi, q__2.imag() = (float)0.; c_sqrt(&q__3, z__); c_div(&q__1, &q__2, &q__3); coef.real() = q__1.real(), coef.imag() = q__1.imag(); kflag = 2; if(koded == 2) { goto L120; } if(xx > *alim) { goto L290; } /* BLANK LINE */ i__1 = kflag - 1; a1 = exp(-xx) * css[i__1].real(); q__2.real() = a1, q__2.imag() = (float)0.; r__1 = cos(yy); r__2 = -sin(yy); q__3.real() = r__1, q__3.imag() = r__2; q__1.real() = q__2.real() * q__3.real() - q__2.imag() * q__3.imag(), q__1.imag() = q__2.real() * q__3.imag() + q__2.imag() * q__3.real(); pt.real() = q__1.real(), pt.imag() = q__1.imag(); q__1.real() = coef.real() * pt.real() - coef.imag() * pt.imag(), q__1.imag() = coef.real() * pt.imag() + coef.imag() * pt.real(); coef.real() = q__1.real(), coef.imag() = q__1.imag(); L120: if(abs(dnu) == (float).5) { goto L300; } /* ----------------------------------------------------------------------- */ /* MILLER ALGORITHM FOR CABS(Z).GT.R1 */ /* ----------------------------------------------------------------------- */ ak = cos(pi * dnu); ak = abs(ak); if(ak == (float)0.) { goto L300; } fhs = (r__1 = (float).25 - dnu2, abs(r__1)); if(fhs == (float)0.) { goto L300; } /* ----------------------------------------------------------------------- */ /* COMPUTE R2=F(E). IF CABS(Z).GE.R2, USE FORWARD RECURRENCE TO */ /* DETERMINE THE BACKWARD INDEX K. R2=F(E) IS A STRAIGHT LINE ON */ /* 12.LE.E.LE.60. E IS COMPUTED FROM 2**(-E)=B**(1-I1MACH(11))= */ /* TOL WHERE B IS THE BASE OF THE ARITHMETIC. */ /* ----------------------------------------------------------------------- */ t1 = (float)(i1mach_(&c__11) - 1) * r1mach_(&c__5) * (float)3.321928094; t1 = max(t1, (float)12.); t1 = std::min(t1, (float)60.); t2 = tth * t1 - (float)6.; if(xx != (float)0.) { goto L130; } t1 = hpi; goto L140; L130: t1 = atan(yy / xx); t1 = abs(t1); L140: if(t2 > caz) { goto L170; } /* ----------------------------------------------------------------------- */ /* FORWARD RECURRENCE LOOP WHEN CABS(Z).GE.R2 */ /* ----------------------------------------------------------------------- */ etest = ak / (pi * caz * *tol); fk = (float)1.; if(etest < (float)1.) { goto L180; } fks = (float)2.; rk = caz + caz + (float)2.; a1 = (float)0.; a2 = (float)1.; i__1 = kmax; for(i__ = 1; i__ <= i__1; ++i__) { ak = fhs / fks; bk = rk / (fk + (float)1.); tm = a2; a2 = bk * a2 - ak * a1; a1 = tm; rk += (float)2.; fks = fks + fk + fk + (float)2.; fhs = fhs + fk + fk; fk += (float)1.; tm = abs(a2) * fk; if(etest < tm) { goto L160; } /* L150: */ } goto L310; L160: fk += spi * t1 * sqrt(t2 / caz); fhs = (r__1 = (float).25 - dnu2, abs(r__1)); goto L180; L170: /* ----------------------------------------------------------------------- */ /* COMPUTE BACKWARD INDEX K FOR CABS(Z).LT.R2 */ /* ----------------------------------------------------------------------- */ a2 = sqrt(caz); ak = fpi * ak / (*tol * sqrt(a2)); aa = t1 * (float)3. / (caz + (float)1.); bb = t1 * (float)14.7 / (caz + (float)28.); ak = (log(ak) + caz * cos(aa) / (caz * (float).008 + (float)1.)) / cos(bb); fk = ak * (float).12125 * ak / caz + (float)1.5; L180: k = (int32)fk; /* ----------------------------------------------------------------------- */ /* BACKWARD RECURRENCE LOOP FOR MILLER ALGORITHM */ /* ----------------------------------------------------------------------- */ fk = (float)k; fks = fk * fk; p1.real() = czero.real(), p1.imag() = czero.imag(); q__1.real() = *tol, q__1.imag() = (float)0.; p2.real() = q__1.real(), p2.imag() = q__1.imag(); cs.real() = p2.real(), cs.imag() = p2.imag(); i__1 = k; for(i__ = 1; i__ <= i__1; ++i__) { a1 = fks - fk; a2 = (fks + fk) / (a1 + fhs); rk = (float)2. / (fk + (float)1.); t1 = (fk + xx) * rk; t2 = yy * rk; pt.real() = p2.real(), pt.imag() = p2.imag(); q__4.real() = t1, q__4.imag() = t2; q__3.real() = p2.real() * q__4.real() - p2.imag() * q__4.imag(), q__3.imag() = p2.real() * q__4.imag() + p2.imag() * q__4.real(); q__2.real() = q__3.real() - p1.real(), q__2.imag() = q__3.imag() - p1.imag(); q__5.real() = a2, q__5.imag() = (float)0.; q__1.real() = q__2.real() * q__5.real() - q__2.imag() * q__5.imag(), q__1.imag() = q__2.real() * q__5.imag() + q__2.imag() * q__5.real(); p2.real() = q__1.real(), p2.imag() = q__1.imag(); p1.real() = pt.real(), p1.imag() = pt.imag(); q__1.real() = cs.real() + p2.real(), q__1.imag() = cs.imag() + p2.imag(); cs.real() = q__1.real(), cs.imag() = q__1.imag(); fks = a1 - fk + (float)1.; fk += (float)-1.; /* L190: */ } /* ----------------------------------------------------------------------- */ /* COMPUTE (P2/CS)=(P2/CABS(CS))*(CONJG(CS)/CABS(CS)) FOR BETTER */ /* SCALING */ /* ----------------------------------------------------------------------- */ tm = c_abs(&cs); r__1 = (float)1. / tm; q__1.real() = r__1, q__1.imag() = (float)0.; pt.real() = q__1.real(), pt.imag() = q__1.imag(); q__1.real() = pt.real() * p2.real() - pt.imag() * p2.imag(), q__1.imag() = pt.real() * p2.imag() + pt.imag() * p2.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); r_cnjg(&q__2, &cs); q__1.real() = q__2.real() * pt.real() - q__2.imag() * pt.imag(), q__1.imag() = q__2.real() * pt.imag() + q__2.imag() * pt.real(); cs.real() = q__1.real(), cs.imag() = q__1.imag(); q__2.real() = coef.real() * s1.real() - coef.imag() * s1.imag(), q__2.imag() = coef.real() * s1.imag() + coef.imag() * s1.real(); q__1.real() = q__2.real() * cs.real() - q__2.imag() * cs.imag(), q__1.imag() = q__2.real() * cs.imag() + q__2.imag() * cs.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); if(inu > 0 || *n > 1) { goto L200; } zd.real() = z__->real(), zd.imag() = z__->imag(); if(iflag == 1) { goto L270; } goto L240; L200: /* ----------------------------------------------------------------------- */ /* COMPUTE P1/P2=(P1/CABS(P2)*CONJG(P2)/CABS(P2) FOR SCALING */ /* ----------------------------------------------------------------------- */ tm = c_abs(&p2); r__1 = (float)1. / tm; q__1.real() = r__1, q__1.imag() = (float)0.; pt.real() = q__1.real(), pt.imag() = q__1.imag(); q__1.real() = pt.real() * p1.real() - pt.imag() * p1.imag(), q__1.imag() = pt.real() * p1.imag() + pt.imag() * p1.real(); p1.real() = q__1.real(), p1.imag() = q__1.imag(); r_cnjg(&q__2, &p2); q__1.real() = q__2.real() * pt.real() - q__2.imag() * pt.imag(), q__1.imag() = q__2.real() * pt.imag() + q__2.imag() * pt.real(); p2.real() = q__1.real(), p2.imag() = q__1.imag(); q__1.real() = p1.real() * p2.real() - p1.imag() * p2.imag(), q__1.imag() = p1.real() * p2.imag() + p1.imag() * p2.real(); pt.real() = q__1.real(), pt.imag() = q__1.imag(); r__1 = dnu + (float).5; q__5.real() = r__1, q__5.imag() = (float)0.; q__4.real() = q__5.real() - pt.real(), q__4.imag() = q__5.imag() - pt.imag(); c_div(&q__3, &q__4, z__); q__2.real() = cone.real() + q__3.real(), q__2.imag() = cone.imag() + q__3.imag(); q__1.real() = s1.real() * q__2.real() - s1.imag() * q__2.imag(), q__1.imag() = s1.real() * q__2.imag() + s1.imag() * q__2.real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); /* ----------------------------------------------------------------------- */ /* FORWARD RECURSION ON THE THREE TERM RECURSION RELATION WITH */ /* SCALING NEAR EXPONENT EXTREMES ON KFLAG=1 OR KFLAG=3 */ /* ----------------------------------------------------------------------- */ L210: r__1 = dnu + (float)1.; q__2.real() = r__1, q__2.imag() = (float)0.; q__1.real() = q__2.real() * rz.real() - q__2.imag() * rz.imag(), q__1.imag() = q__2.real() * rz.imag() + q__2.imag() * rz.real(); ck.real() = q__1.real(), ck.imag() = q__1.imag(); if(*n == 1) { --inu; } if(inu > 0) { goto L220; } if(*n == 1) { s1.real() = s2.real(), s1.imag() = s2.imag(); } zd.real() = z__->real(), zd.imag() = z__->imag(); if(iflag == 1) { goto L270; } goto L240; L220: inub = 1; if(iflag == 1) { goto L261; } L225: i__1 = kflag - 1; p1.real() = csr[i__1].real(), p1.imag() = csr[i__1].imag(); ascle = bry[kflag - 1]; i__1 = inu; for(i__ = inub; i__ <= i__1; ++i__) { st.real() = s2.real(), st.imag() = s2.imag(); q__2.real() = ck.real() * s2.real() - ck.imag() * s2.imag(), q__2.imag() = ck.real() * s2.imag() + ck.imag() * s2.real(); q__1.real() = q__2.real() + s1.real(), q__1.imag() = q__2.imag() + s1.imag(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); s1.real() = st.real(), s1.imag() = st.imag(); q__1.real() = ck.real() + rz.real(), q__1.imag() = ck.imag() + rz.imag(); ck.real() = q__1.real(), ck.imag() = q__1.imag(); if(kflag >= 3) { goto L230; } q__1.real() = s2.real() * p1.real() - s2.imag() * p1.imag(), q__1.imag() = s2.real() * p1.imag() + s2.imag() * p1.real(); p2.real() = q__1.real(), p2.imag() = q__1.imag(); p2r = p2.real(); p2i = r_imag(&p2); p2r = abs(p2r); p2i = abs(p2i); p2m = max(p2r, p2i); if(p2m <= ascle) { goto L230; } ++kflag; ascle = bry[kflag - 1]; q__1.real() = s1.real() * p1.real() - s1.imag() * p1.imag(), q__1.imag() = s1.real() * p1.imag() + s1.imag() * p1.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); s2.real() = p2.real(), s2.imag() = p2.imag(); i__2 = kflag - 1; q__1.real() = s1.real() * css[i__2].real() - s1.imag() * css[i__2].imag(), q__1.imag() = s1.real() * css[i__2].imag() + s1.imag() * css[i__2].real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); i__2 = kflag - 1; q__1.real() = s2.real() * css[i__2].real() - s2.imag() * css[i__2].imag(), q__1.imag() = s2.real() * css[i__2].imag() + s2.imag() * css[i__2].real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); i__2 = kflag - 1; p1.real() = csr[i__2].real(), p1.imag() = csr[i__2].imag(); L230:; } if(*n == 1) { s1.real() = s2.real(), s1.imag() = s2.imag(); } L240: i__1 = kflag - 1; q__1.real() = s1.real() * csr[i__1].real() - s1.imag() * csr[i__1].imag(), q__1.imag() = s1.real() * csr[i__1].imag() + s1.imag() * csr[i__1].real(); y[1].real() = q__1.real(), y[1].imag() = q__1.imag(); if(*n == 1) { return 0; } i__1 = kflag - 1; q__1.real() = s2.real() * csr[i__1].real() - s2.imag() * csr[i__1].imag(), q__1.imag() = s2.real() * csr[i__1].imag() + s2.imag() * csr[i__1].real(); y[2].real() = q__1.real(), y[2].imag() = q__1.imag(); if(*n == 2) { return 0; } kk = 2; L250: ++kk; if(kk > *n) { return 0; } i__1 = kflag - 1; p1.real() = csr[i__1].real(), p1.imag() = csr[i__1].imag(); ascle = bry[kflag - 1]; i__1 = *n; for(i__ = kk; i__ <= i__1; ++i__) { p2.real() = s2.real(), p2.imag() = s2.imag(); q__2.real() = ck.real() * s2.real() - ck.imag() * s2.imag(), q__2.imag() = ck.real() * s2.imag() + ck.imag() * s2.real(); q__1.real() = q__2.real() + s1.real(), q__1.imag() = q__2.imag() + s1.imag(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); s1.real() = p2.real(), s1.imag() = p2.imag(); q__1.real() = ck.real() + rz.real(), q__1.imag() = ck.imag() + rz.imag(); ck.real() = q__1.real(), ck.imag() = q__1.imag(); q__1.real() = s2.real() * p1.real() - s2.imag() * p1.imag(), q__1.imag() = s2.real() * p1.imag() + s2.imag() * p1.real(); p2.real() = q__1.real(), p2.imag() = q__1.imag(); i__2 = i__; y[i__2].real() = p2.real(), y[i__2].imag() = p2.imag(); if(kflag >= 3) { goto L260; } p2r = p2.real(); p2i = r_imag(&p2); p2r = abs(p2r); p2i = abs(p2i); p2m = max(p2r, p2i); if(p2m <= ascle) { goto L260; } ++kflag; ascle = bry[kflag - 1]; q__1.real() = s1.real() * p1.real() - s1.imag() * p1.imag(), q__1.imag() = s1.real() * p1.imag() + s1.imag() * p1.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); s2.real() = p2.real(), s2.imag() = p2.imag(); i__2 = kflag - 1; q__1.real() = s1.real() * css[i__2].real() - s1.imag() * css[i__2].imag(), q__1.imag() = s1.real() * css[i__2].imag() + s1.imag() * css[i__2].real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); i__2 = kflag - 1; q__1.real() = s2.real() * css[i__2].real() - s2.imag() * css[i__2].imag(), q__1.imag() = s2.real() * css[i__2].imag() + s2.imag() * css[i__2].real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); i__2 = kflag - 1; p1.real() = csr[i__2].real(), p1.imag() = csr[i__2].imag(); L260:; } return 0; /* ----------------------------------------------------------------------- */ /* IFLAG=1 CASES, FORWARD RECURRENCE ON SCALED VALUES ON UNDERFLOW */ /* ----------------------------------------------------------------------- */ L261: helim = *elim * (float).5; elm = exp(-(*elim)); q__1.real() = elm, q__1.imag() = (float)0.; celm.real() = q__1.real(), celm.imag() = q__1.imag(); ascle = bry[0]; zd.real() = z__->real(), zd.imag() = z__->imag(); xd = xx; yd = yy; ic = -1; j = 2; i__1 = inu; for(i__ = 1; i__ <= i__1; ++i__) { st.real() = s2.real(), st.imag() = s2.imag(); q__2.real() = ck.real() * s2.real() - ck.imag() * s2.imag(), q__2.imag() = ck.real() * s2.imag() + ck.imag() * s2.real(); q__1.real() = q__2.real() + s1.real(), q__1.imag() = q__2.imag() + s1.imag(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); s1.real() = st.real(), s1.imag() = st.imag(); q__1.real() = ck.real() + rz.real(), q__1.imag() = ck.imag() + rz.imag(); ck.real() = q__1.real(), ck.imag() = q__1.imag(); as = c_abs(&s2); alas = log(as); p2r = -xd + alas; if(p2r < -(*elim)) { goto L263; } q__2.real() = -zd.real(), q__2.imag() = -zd.imag(); c_log(&q__3, &s2); q__1.real() = q__2.real() + q__3.real(), q__1.imag() = q__2.imag() + q__3.imag(); p2.real() = q__1.real(), p2.imag() = q__1.imag(); p2r = p2.real(); p2i = r_imag(&p2); p2m = exp(p2r) / *tol; q__2.real() = p2m, q__2.imag() = (float)0.; r__1 = cos(p2i); r__2 = sin(p2i); q__3.real() = r__1, q__3.imag() = r__2; q__1.real() = q__2.real() * q__3.real() - q__2.imag() * q__3.imag(), q__1.imag() = q__2.real() * q__3.imag() + q__2.imag() * q__3.real(); p1.real() = q__1.real(), p1.imag() = q__1.imag(); cuchk_(&p1, &nw, &ascle, tol); if(nw != 0) { goto L263; } j = 3 - j; i__2 = j - 1; cy[i__2].real() = p1.real(), cy[i__2].imag() = p1.imag(); if(ic == i__ - 1) { goto L264; } ic = i__; goto L262; L263: if(alas < helim) { goto L262; } xd -= *elim; q__1.real() = s1.real() * celm.real() - s1.imag() * celm.imag(), q__1.imag() = s1.real() * celm.imag() + s1.imag() * celm.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); q__1.real() = s2.real() * celm.real() - s2.imag() * celm.imag(), q__1.imag() = s2.real() * celm.imag() + s2.imag() * celm.real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); q__1.real() = xd, q__1.imag() = yd; zd.real() = q__1.real(), zd.imag() = q__1.imag(); L262:; } if(*n == 1) { s1.real() = s2.real(), s1.imag() = s2.imag(); } goto L270; L264: kflag = 1; inub = i__ + 1; i__1 = j - 1; s2.real() = cy[i__1].real(), s2.imag() = cy[i__1].imag(); j = 3 - j; i__1 = j - 1; s1.real() = cy[i__1].real(), s1.imag() = cy[i__1].imag(); if(inub <= inu) { goto L225; } if(*n == 1) { s1.real() = s2.real(), s1.imag() = s2.imag(); } goto L240; L270: y[1].real() = s1.real(), y[1].imag() = s1.imag(); if(*n == 1) { goto L280; } y[2].real() = s2.real(), y[2].imag() = s2.imag(); L280: ascle = bry[0]; ckscl_(&zd, fnu, n, &y[1], nz, &rz, &ascle, tol, elim); inu = *n - *nz; if(inu <= 0) { return 0; } kk = *nz + 1; i__1 = kk; s1.real() = y[i__1].real(), s1.imag() = y[i__1].imag(); i__1 = kk; q__1.real() = s1.real() * csr[0].real() - s1.imag() * csr[0].imag(), q__1.imag() = s1.real() * csr[0].imag() + s1.imag() * csr[0].real(); y[i__1].real() = q__1.real(), y[i__1].imag() = q__1.imag(); if(inu == 1) { return 0; } kk = *nz + 2; i__1 = kk; s2.real() = y[i__1].real(), s2.imag() = y[i__1].imag(); i__1 = kk; q__1.real() = s2.real() * csr[0].real() - s2.imag() * csr[0].imag(), q__1.imag() = s2.real() * csr[0].imag() + s2.imag() * csr[0].real(); y[i__1].real() = q__1.real(), y[i__1].imag() = q__1.imag(); if(inu == 2) { return 0; } t2 = *fnu + (float)(kk - 1); q__2.real() = t2, q__2.imag() = (float)0.; q__1.real() = q__2.real() * rz.real() - q__2.imag() * rz.imag(), q__1.imag() = q__2.real() * rz.imag() + q__2.imag() * rz.real(); ck.real() = q__1.real(), ck.imag() = q__1.imag(); kflag = 1; goto L250; L290: /* ----------------------------------------------------------------------- */ /* SCALE BY EXP(Z), IFLAG = 1 CASES */ /* ----------------------------------------------------------------------- */ koded = 2; iflag = 1; kflag = 2; goto L120; /* ----------------------------------------------------------------------- */ /* FNU=HALF ODD INTEGER CASE, DNU=-0.5 */ /* ----------------------------------------------------------------------- */ L300: s1.real() = coef.real(), s1.imag() = coef.imag(); s2.real() = coef.real(), s2.imag() = coef.imag(); goto L210; L310: *nz = -2; return 0; } /* cbknu_ */ int cbuni_(System::Complex<float>* z__, float* fnu, int32* kode, int32* n, System::Complex<float>* y, int32* nz, int32* nui, int32* nlast, float* fnul, float* tol, float* elim, float* alim) { /* System generated locals */ int32 i__1, i__2; float r__1; System::Complex<float> q__1, q__2, q__3, q__4; int32 i__, k; System::Complex<float> s1, s2; float ax, ay; int32 nl; System::Complex<float> cy[2]; int32 nw; System::Complex<float> st, rz; float xx, yy, gnu, bry[3], sti, stm, str; System::Complex<float> cscl, cscr; float dfnu, fnui; int32 iflag; float ascle; int32 iform; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE CBUNI */ /* ***REFER TO CBESI,CBESK */ /* CBUNI COMPUTES THE I BESSEL FUNCTION FOR LARGE CABS(Z).GT. */ /* FNUL AND FNU+N-1.LT.FNUL. THE ORDER IS INCREASED FROM */ /* FNU+N-1 GREATER THAN FNUL BY ADDING NUI AND COMPUTING */ /* ACCORDING TO THE UNIFORM ASYMPTOTIC EXPANSION FOR I(FNU,Z) */ /* ON IFORM=1 AND THE EXPANSION FOR J(FNU,Z) ON IFORM=2 */ /* ***ROUTINES CALLED CUNI1,CUNI2,R1MACH */ /* ***END PROLOGUE CBUNI */ /* Parameter adjustments */ --y; /* Function Body */ *nz = 0; xx = z__->real(); yy = z__->imag(); ax = abs(xx) * (float)1.7321; ay = abs(yy); iform = 1; if(ay > ax) { iform = 2; } if(*nui == 0) { goto L60; } fnui = (float)(*nui); dfnu = *fnu + (float)(*n - 1); gnu = dfnu + fnui; if(iform == 2) { goto L10; } /* ----------------------------------------------------------------------- */ /* ASYMPTOTIC EXPANSION FOR I(FNU,Z) FOR LARGE FNU APPLIED IN */ /* -PI/3.LE.ARG(Z).LE.PI/3 */ /* ----------------------------------------------------------------------- */ cuni1_(z__, &gnu, kode, &c__2, cy, &nw, nlast, fnul, tol, elim, alim); goto L20; L10: /* ----------------------------------------------------------------------- */ /* ASYMPTOTIC EXPANSION FOR J(FNU,Z*EXP(M*HPI)) FOR LARGE FNU */ /* APPLIED IN PI/3.LT.ABS(ARG(Z)).LE.PI/2 WHERE M=+I OR -I */ /* AND HPI=PI/2 */ /* ----------------------------------------------------------------------- */ cuni2_(z__, &gnu, kode, &c__2, cy, &nw, nlast, fnul, tol, elim, alim); L20: if(nw < 0) { goto L50; } if(nw != 0) { goto L90; } ay = c_abs(cy); /* ---------------------------------------------------------------------- */ /* SCALE BACKWARD RECURRENCE, BRY(3) IS DEFINED BUT NEVER USED */ /* ---------------------------------------------------------------------- */ bry[0] = r1mach_(&c__1) * (float)1e3 / *tol; bry[1] = (float)1. / bry[0]; bry[2] = bry[1]; iflag = 2; ascle = bry[1]; ax = (float)1.; q__1.real() = ax, q__1.imag() = (float)0.; cscl.real() = q__1.real(), cscl.imag() = q__1.imag(); if(ay > bry[0]) { goto L21; } iflag = 1; ascle = bry[0]; ax = (float)1. / *tol; q__1.real() = ax, q__1.imag() = (float)0.; cscl.real() = q__1.real(), cscl.imag() = q__1.imag(); goto L25; L21: if(ay < bry[1]) { goto L25; } iflag = 3; ascle = bry[2]; ax = *tol; q__1.real() = ax, q__1.imag() = (float)0.; cscl.real() = q__1.real(), cscl.imag() = q__1.imag(); L25: ay = (float)1. / ax; q__1.real() = ay, q__1.imag() = (float)0.; cscr.real() = q__1.real(), cscr.imag() = q__1.imag(); q__1.real() = cy[1].real() * cscl.real() - cy[1].imag() * cscl.imag(), q__1.imag() = cy[1].real() * cscl.imag() + cy[1].imag() * cscl.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); q__1.real() = cy[0].real() * cscl.real() - cy[0].imag() * cscl.imag(), q__1.imag() = cy[0].real() * cscl.imag() + cy[0].imag() * cscl.real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); c_div(&q__1, &c_b17, z__); rz.real() = q__1.real(), rz.imag() = q__1.imag(); i__1 = *nui; for(i__ = 1; i__ <= i__1; ++i__) { st.real() = s2.real(), st.imag() = s2.imag(); r__1 = dfnu + fnui; q__4.real() = r__1, q__4.imag() = (float)0.; q__3.real() = q__4.real() * rz.real() - q__4.imag() * rz.imag(), q__3.imag() = q__4.real() * rz.imag() + q__4.imag() * rz.real(); q__2.real() = q__3.real() * s2.real() - q__3.imag() * s2.imag(), q__2.imag() = q__3.real() * s2.imag() + q__3.imag() * s2.real(); q__1.real() = q__2.real() + s1.real(), q__1.imag() = q__2.imag() + s1.imag(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); s1.real() = st.real(), s1.imag() = st.imag(); fnui += (float)-1.; if(iflag >= 3) { goto L30; } q__1.real() = s2.real() * cscr.real() - s2.imag() * cscr.imag(), q__1.imag() = s2.real() * cscr.imag() + s2.imag() * cscr.real(); st.real() = q__1.real(), st.imag() = q__1.imag(); str = st.real(); sti = r_imag(&st); str = abs(str); sti = abs(sti); stm = max(str, sti); if(stm <= ascle) { goto L30; } ++iflag; ascle = bry[iflag - 1]; q__1.real() = s1.real() * cscr.real() - s1.imag() * cscr.imag(), q__1.imag() = s1.real() * cscr.imag() + s1.imag() * cscr.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); s2.real() = st.real(), s2.imag() = st.imag(); ax *= *tol; ay = (float)1. / ax; q__1.real() = ax, q__1.imag() = (float)0.; cscl.real() = q__1.real(), cscl.imag() = q__1.imag(); q__1.real() = ay, q__1.imag() = (float)0.; cscr.real() = q__1.real(), cscr.imag() = q__1.imag(); q__1.real() = s1.real() * cscl.real() - s1.imag() * cscl.imag(), q__1.imag() = s1.real() * cscl.imag() + s1.imag() * cscl.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); q__1.real() = s2.real() * cscl.real() - s2.imag() * cscl.imag(), q__1.imag() = s2.real() * cscl.imag() + s2.imag() * cscl.real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); L30:; } i__1 = *n; q__1.real() = s2.real() * cscr.real() - s2.imag() * cscr.imag(), q__1.imag() = s2.real() * cscr.imag() + s2.imag() * cscr.real(); y[i__1].real() = q__1.real(), y[i__1].imag() = q__1.imag(); if(*n == 1) { return 0; } nl = *n - 1; fnui = (float)nl; k = nl; i__1 = nl; for(i__ = 1; i__ <= i__1; ++i__) { st.real() = s2.real(), st.imag() = s2.imag(); r__1 = *fnu + fnui; q__4.real() = r__1, q__4.imag() = (float)0.; q__3.real() = q__4.real() * rz.real() - q__4.imag() * rz.imag(), q__3.imag() = q__4.real() * rz.imag() + q__4.imag() * rz.real(); q__2.real() = q__3.real() * s2.real() - q__3.imag() * s2.imag(), q__2.imag() = q__3.real() * s2.imag() + q__3.imag() * s2.real(); q__1.real() = q__2.real() + s1.real(), q__1.imag() = q__2.imag() + s1.imag(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); s1.real() = st.real(), s1.imag() = st.imag(); q__1.real() = s2.real() * cscr.real() - s2.imag() * cscr.imag(), q__1.imag() = s2.real() * cscr.imag() + s2.imag() * cscr.real(); st.real() = q__1.real(), st.imag() = q__1.imag(); i__2 = k; y[i__2].real() = st.real(), y[i__2].imag() = st.imag(); fnui += (float)-1.; --k; if(iflag >= 3) { goto L40; } str = st.real(); sti = r_imag(&st); str = abs(str); sti = abs(sti); stm = max(str, sti); if(stm <= ascle) { goto L40; } ++iflag; ascle = bry[iflag - 1]; q__1.real() = s1.real() * cscr.real() - s1.imag() * cscr.imag(), q__1.imag() = s1.real() * cscr.imag() + s1.imag() * cscr.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); s2.real() = st.real(), s2.imag() = st.imag(); ax *= *tol; ay = (float)1. / ax; q__1.real() = ax, q__1.imag() = (float)0.; cscl.real() = q__1.real(), cscl.imag() = q__1.imag(); q__1.real() = ay, q__1.imag() = (float)0.; cscr.real() = q__1.real(), cscr.imag() = q__1.imag(); q__1.real() = s1.real() * cscl.real() - s1.imag() * cscl.imag(), q__1.imag() = s1.real() * cscl.imag() + s1.imag() * cscl.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); q__1.real() = s2.real() * cscl.real() - s2.imag() * cscl.imag(), q__1.imag() = s2.real() * cscl.imag() + s2.imag() * cscl.real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); L40:; } return 0; L50: *nz = -1; if(nw == -2) { *nz = -2; } return 0; L60: if(iform == 2) { goto L70; } /* ----------------------------------------------------------------------- */ /* ASYMPTOTIC EXPANSION FOR I(FNU,Z) FOR LARGE FNU APPLIED IN */ /* -PI/3.LE.ARG(Z).LE.PI/3 */ /* ----------------------------------------------------------------------- */ cuni1_(z__, fnu, kode, n, &y[1], &nw, nlast, fnul, tol, elim, alim); goto L80; L70: /* ----------------------------------------------------------------------- */ /* ASYMPTOTIC EXPANSION FOR J(FNU,Z*EXP(M*HPI)) FOR LARGE FNU */ /* APPLIED IN PI/3.LT.ABS(ARG(Z)).LE.PI/2 WHERE M=+I OR -I */ /* AND HPI=PI/2 */ /* ----------------------------------------------------------------------- */ cuni2_(z__, fnu, kode, n, &y[1], &nw, nlast, fnul, tol, elim, alim); L80: if(nw < 0) { goto L50; } *nz = nw; return 0; L90: *nlast = *n; return 0; } /* cbuni_ */ int cbunk_(System::Complex<float>* z__, float* fnu, int32* kode, int32* mr, int32* n, System::Complex<float>* y, int32* nz, float* tol, float* elim, float* alim) { float ax, ay, xx, yy; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE CBUNK */ /* ***REFER TO CBESK,CBESH */ /* CBUNK COMPUTES THE K BESSEL FUNCTION FOR FNU.GT.FNUL. */ /* ACCORDING TO THE UNIFORM ASYMPTOTIC EXPANSION FOR K(FNU,Z) */ /* IN CUNK1 AND THE EXPANSION FOR H(2,FNU,Z) IN CUNK2 */ /* ***ROUTINES CALLED CUNK1,CUNK2 */ /* ***END PROLOGUE CBUNK */ /* Parameter adjustments */ --y; /* Function Body */ *nz = 0; xx = z__->real(); yy = r_imag(z__); ax = abs(xx) * (float)1.7321; ay = abs(yy); if(ay > ax) { goto L10; } /* ----------------------------------------------------------------------- */ /* ASYMPTOTIC EXPANSION FOR K(FNU,Z) FOR LARGE FNU APPLIED IN */ /* -PI/3.LE.ARG(Z).LE.PI/3 */ /* ----------------------------------------------------------------------- */ cunk1_(z__, fnu, kode, mr, n, &y[1], nz, tol, elim, alim); goto L20; L10: /* ----------------------------------------------------------------------- */ /* ASYMPTOTIC EXPANSION FOR H(2,FNU,Z*EXP(M*HPI)) FOR LARGE FNU */ /* APPLIED IN PI/3.LT.ABS(ARG(Z)).LE.PI/2 WHERE M=+I OR -I */ /* AND HPI=PI/2 */ /* ----------------------------------------------------------------------- */ cunk2_(z__, fnu, kode, mr, n, &y[1], nz, tol, elim, alim); L20: return 0; } /* cbunk_ */ int ckscl_(System::Complex<float>* zr, float* fnu, int32* n, System::Complex<float>* y, int32* nz, System::Complex<float>* rz, float* ascle, float* tol, float* elim) { /* Initialized data */ static System::Complex<float> czero = {(float)0., (float)0.}; /* System generated locals */ int32 i__1, i__2; float r__1, r__2; System::Complex<float> q__1, q__2, q__3; int32 i__, k; System::Complex<float> s1, s2; float aa; int32 ic; System::Complex<float> ck; float as, fn; System::Complex<float> cs; int32 kk; System::Complex<float> cy[2]; int32 nn; System::Complex<float> zd; int32 nw; float xx, acs, elm, csi, csr, zri; System::Complex<float> celm; float alas; float helim; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE CKSCL */ /* ***REFER TO CBKNU,CUNK1,CUNK2 */ /* SET K FUNCTIONS TO ZERO ON UNDERFLOW, CONTINUE RECURRENCE */ /* ON SCALED FUNCTIONS UNTIL TWO MEMBERS COME ON SCALE, THEN */ /* RETURN WITH MIN(NZ+2,N) VALUES SCALED BY 1/TOL. */ /* ***ROUTINES CALLED CUCHK */ /* ***END PROLOGUE CKSCL */ /* Parameter adjustments */ --y; /* Function Body */ *nz = 0; ic = 0; xx = zr->real(); nn = std::min(2L, *n); i__1 = nn; for(i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; s1.real() = y[i__2].real(), s1.imag() = y[i__2].imag(); i__2 = i__ - 1; cy[i__2].real() = s1.real(), cy[i__2].imag() = s1.imag(); as = c_abs(&s1); acs = -xx + log(as); ++(*nz); i__2 = i__; y[i__2].real() = czero.real(), y[i__2].imag() = czero.imag(); if(acs < -(*elim)) { goto L10; } q__2.real() = -zr->real(), q__2.imag() = -zr->imag(); c_log(&q__3, &s1); q__1.real() = q__2.real() + q__3.real(), q__1.imag() = q__2.imag() + q__3.imag(); cs.real() = q__1.real(), cs.imag() = q__1.imag(); csr = cs.real(); csi = r_imag(&cs); aa = exp(csr) / *tol; q__2.real() = aa, q__2.imag() = (float)0.; r__1 = cos(csi); r__2 = sin(csi); q__3.real() = r__1, q__3.imag() = r__2; q__1.real() = q__2.real() * q__3.real() - q__2.imag() * q__3.imag(), q__1.imag() = q__2.real() * q__3.imag() + q__2.imag() * q__3.real(); cs.real() = q__1.real(), cs.imag() = q__1.imag(); cuchk_(&cs, &nw, ascle, tol); if(nw != 0) { goto L10; } i__2 = i__; y[i__2].real() = cs.real(), y[i__2].imag() = cs.imag(); --(*nz); ic = i__; L10:; } if(*n == 1) { return 0; } if(ic > 1) { goto L20; } y[1].real() = czero.real(), y[1].imag() = czero.imag(); *nz = 2; L20: if(*n == 2) { return 0; } if(*nz == 0) { return 0; } fn = *fnu + (float)1.; q__2.real() = fn, q__2.imag() = (float)0.; q__1.real() = q__2.real() * rz->real() - q__2.imag() * rz->imag(), q__1.imag() = q__2.real() * rz->imag() + q__2.imag() * rz->real(); ck.real() = q__1.real(), ck.imag() = q__1.imag(); s1.real() = cy[0].real(), s1.imag() = cy[0].imag(); s2.real() = cy[1].real(), s2.imag() = cy[1].imag(); helim = *elim * (float).5; elm = exp(-(*elim)); q__1.real() = elm, q__1.imag() = (float)0.; celm.real() = q__1.real(), celm.imag() = q__1.imag(); zri = r_imag(zr); zd.real() = zr->real(), zd.imag() = zr->imag(); /* FIND TWO CONSECUTIVE Y VALUES ON SCALE. SCALE RECURRENCE IF */ /* S2 GETS LARGER THAN EXP(ELIM/2) */ i__1 = *n; for(i__ = 3; i__ <= i__1; ++i__) { kk = i__; cs.real() = s2.real(), cs.imag() = s2.imag(); q__2.real() = ck.real() * s2.real() - ck.imag() * s2.imag(), q__2.imag() = ck.real() * s2.imag() + ck.imag() * s2.real(); q__1.real() = q__2.real() + s1.real(), q__1.imag() = q__2.imag() + s1.imag(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); s1.real() = cs.real(), s1.imag() = cs.imag(); q__1.real() = ck.real() + rz->real(), q__1.imag() = ck.imag() + rz->imag(); ck.real() = q__1.real(), ck.imag() = q__1.imag(); as = c_abs(&s2); alas = log(as); acs = -xx + alas; ++(*nz); i__2 = i__; y[i__2].real() = czero.real(), y[i__2].imag() = czero.imag(); if(acs < -(*elim)) { goto L25; } q__2.real() = -zd.real(), q__2.imag() = -zd.imag(); c_log(&q__3, &s2); q__1.real() = q__2.real() + q__3.real(), q__1.imag() = q__2.imag() + q__3.imag(); cs.real() = q__1.real(), cs.imag() = q__1.imag(); csr = cs.real(); csi = r_imag(&cs); aa = exp(csr) / *tol; q__2.real() = aa, q__2.imag() = (float)0.; r__1 = cos(csi); r__2 = sin(csi); q__3.real() = r__1, q__3.imag() = r__2; q__1.real() = q__2.real() * q__3.real() - q__2.imag() * q__3.imag(), q__1.imag() = q__2.real() * q__3.imag() + q__2.imag() * q__3.real(); cs.real() = q__1.real(), cs.imag() = q__1.imag(); cuchk_(&cs, &nw, ascle, tol); if(nw != 0) { goto L25; } i__2 = i__; y[i__2].real() = cs.real(), y[i__2].imag() = cs.imag(); --(*nz); if(ic == kk - 1) { goto L40; } ic = kk; goto L30; L25: if(alas < helim) { goto L30; } xx -= *elim; q__1.real() = s1.real() * celm.real() - s1.imag() * celm.imag(), q__1.imag() = s1.real() * celm.imag() + s1.imag() * celm.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); q__1.real() = s2.real() * celm.real() - s2.imag() * celm.imag(), q__1.imag() = s2.real() * celm.imag() + s2.imag() * celm.real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); q__1.real() = xx, q__1.imag() = zri; zd.real() = q__1.real(), zd.imag() = q__1.imag(); L30:; } *nz = *n; if(ic == *n) { *nz = *n - 1; } goto L45; L40: *nz = kk - 2; L45: i__1 = *nz; for(k = 1; k <= i__1; ++k) { i__2 = k; y[i__2].real() = czero.real(), y[i__2].imag() = czero.imag(); /* L50: */ } return 0; } /* ckscl_ */ int cmlri_(System::Complex<float>* z__, float* fnu, int32* kode, int32* n, System::Complex<float>* y, int32* nz, float* tol) { /* Initialized data */ static System::Complex<float> czero = {(float)0., (float)0.}; static System::Complex<float> cone = {(float)1., (float)0.}; static System::Complex<float> ctwo = {(float)2., (float)0.}; /* System generated locals */ int32 i__1, i__2, i__3; float r__1, r__2, r__3; System::Complex<float> q__1, q__2, q__3, q__4, q__5; int32 i__, k, m; float x; System::Complex<float> p1, p2; float ak, bk; System::Complex<float> ck; float ap, at; int32 kk, km; float az; System::Complex<float> pt, rz; float ack, fnf, fkk; int32 iaz; float rho; int32 inu; System::Complex<float> sum; float tst, rho2, flam, fkap, scle, tfnf; int32 idum, ifnu; int32 itime; System::Complex<float> cnorm; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE CMLRI */ /* ***REFER TO CBESI,CBESK */ /* CMLRI COMPUTES THE I BESSEL FUNCTION FOR RE(Z).GE.0.0 BY THE */ /* MILLER ALGORITHM NORMALIZED BY A NEUMANN SERIES. */ /* ***ROUTINES CALLED GAMLN,R1MACH */ /* ***END PROLOGUE CMLRI */ /* Parameter adjustments */ --y; /* Function Body */ scle = (float)1e3 * r1mach_(&c__1) / *tol; *nz = 0; az = c_abs(z__); x = z__->real(); iaz = (int32)az; ifnu = (int32)(*fnu); inu = ifnu + *n - 1; at = (float)iaz + (float)1.; q__2.real() = at, q__2.imag() = (float)0.; c_div(&q__1, &q__2, z__); ck.real() = q__1.real(), ck.imag() = q__1.imag(); c_div(&q__1, &ctwo, z__); rz.real() = q__1.real(), rz.imag() = q__1.imag(); p1.real() = czero.real(), p1.imag() = czero.imag(); p2.real() = cone.real(), p2.imag() = cone.imag(); ack = (at + (float)1.) / az; rho = ack + sqrt(ack * ack - (float)1.); rho2 = rho * rho; tst = (rho2 + rho2) / ((rho2 - (float)1.) * (rho - (float)1.)); tst /= *tol; /* ----------------------------------------------------------------------- */ /* COMPUTE RELATIVE TRUNCATION ERROR INDEX FOR SERIES */ /* ----------------------------------------------------------------------- */ ak = at; for(i__ = 1; i__ <= 80; ++i__) { pt.real() = p2.real(), pt.imag() = p2.imag(); q__2.real() = ck.real() * p2.real() - ck.imag() * p2.imag(), q__2.imag() = ck.real() * p2.imag() + ck.imag() * p2.real(); q__1.real() = p1.real() - q__2.real(), q__1.imag() = p1.imag() - q__2.imag(); p2.real() = q__1.real(), p2.imag() = q__1.imag(); p1.real() = pt.real(), p1.imag() = pt.imag(); q__1.real() = ck.real() + rz.real(), q__1.imag() = ck.imag() + rz.imag(); ck.real() = q__1.real(), ck.imag() = q__1.imag(); ap = c_abs(&p2); if(ap > tst * ak * ak) { goto L20; } ak += (float)1.; /* L10: */ } goto L110; L20: ++i__; k = 0; if(inu < iaz) { goto L40; } /* ----------------------------------------------------------------------- */ /* COMPUTE RELATIVE TRUNCATION ERROR FOR RATIOS */ /* ----------------------------------------------------------------------- */ p1.real() = czero.real(), p1.imag() = czero.imag(); p2.real() = cone.real(), p2.imag() = cone.imag(); at = (float)inu + (float)1.; q__2.real() = at, q__2.imag() = (float)0.; c_div(&q__1, &q__2, z__); ck.real() = q__1.real(), ck.imag() = q__1.imag(); ack = at / az; tst = sqrt(ack / *tol); itime = 1; for(k = 1; k <= 80; ++k) { pt.real() = p2.real(), pt.imag() = p2.imag(); q__2.real() = ck.real() * p2.real() - ck.imag() * p2.imag(), q__2.imag() = ck.real() * p2.imag() + ck.imag() * p2.real(); q__1.real() = p1.real() - q__2.real(), q__1.imag() = p1.imag() - q__2.imag(); p2.real() = q__1.real(), p2.imag() = q__1.imag(); p1.real() = pt.real(), p1.imag() = pt.imag(); q__1.real() = ck.real() + rz.real(), q__1.imag() = ck.imag() + rz.imag(); ck.real() = q__1.real(), ck.imag() = q__1.imag(); ap = c_abs(&p2); if(ap < tst) { goto L30; } if(itime == 2) { goto L40; } ack = c_abs(&ck); flam = ack + sqrt(ack * ack - (float)1.); fkap = ap / c_abs(&p1); rho = std::min(flam, fkap); tst *= sqrt(rho / (rho * rho - (float)1.)); itime = 2; L30:; } goto L110; L40: /* ----------------------------------------------------------------------- */ /* BACKWARD RECURRENCE AND SUM NORMALIZING RELATION */ /* ----------------------------------------------------------------------- */ ++k; /* Computing MAX */ i__1 = i__ + iaz, i__2 = k + inu; kk = max(i__1, i__2); fkk = (float)kk; p1.real() = czero.real(), p1.imag() = czero.imag(); /* ----------------------------------------------------------------------- */ /* SCALE P2 AND SUM BY SCLE */ /* ----------------------------------------------------------------------- */ q__1.real() = scle, q__1.imag() = (float)0.; p2.real() = q__1.real(), p2.imag() = q__1.imag(); fnf = *fnu - (float)ifnu; tfnf = fnf + fnf; r__1 = fkk + tfnf + (float)1.; r__2 = fkk + (float)1.; r__3 = tfnf + (float)1.; bk = gamln_(&r__1, &idum) - gamln_(&r__2, &idum) - gamln_(&r__3, &idum); bk = exp(bk); sum.real() = czero.real(), sum.imag() = czero.imag(); km = kk - inu; i__1 = km; for(i__ = 1; i__ <= i__1; ++i__) { pt.real() = p2.real(), pt.imag() = p2.imag(); r__1 = fkk + fnf; q__4.real() = r__1, q__4.imag() = (float)0.; q__3.real() = q__4.real() * rz.real() - q__4.imag() * rz.imag(), q__3.imag() = q__4.real() * rz.imag() + q__4.imag() * rz.real(); q__2.real() = q__3.real() * p2.real() - q__3.imag() * p2.imag(), q__2.imag() = q__3.real() * p2.imag() + q__3.imag() * p2.real(); q__1.real() = p1.real() + q__2.real(), q__1.imag() = p1.imag() + q__2.imag(); p2.real() = q__1.real(), p2.imag() = q__1.imag(); p1.real() = pt.real(), p1.imag() = pt.imag(); ak = (float)1. - tfnf / (fkk + tfnf); ack = bk * ak; r__1 = ack + bk; q__3.real() = r__1, q__3.imag() = (float)0.; q__2.real() = q__3.real() * p1.real() - q__3.imag() * p1.imag(), q__2.imag() = q__3.real() * p1.imag() + q__3.imag() * p1.real(); q__1.real() = sum.real() + q__2.real(), q__1.imag() = sum.imag() + q__2.imag(); sum.real() = q__1.real(), sum.imag() = q__1.imag(); bk = ack; fkk += (float)-1.; /* L50: */ } i__1 = *n; y[i__1].real() = p2.real(), y[i__1].imag() = p2.imag(); if(*n == 1) { goto L70; } i__1 = *n; for(i__ = 2; i__ <= i__1; ++i__) { pt.real() = p2.real(), pt.imag() = p2.imag(); r__1 = fkk + fnf; q__4.real() = r__1, q__4.imag() = (float)0.; q__3.real() = q__4.real() * rz.real() - q__4.imag() * rz.imag(), q__3.imag() = q__4.real() * rz.imag() + q__4.imag() * rz.real(); q__2.real() = q__3.real() * p2.real() - q__3.imag() * p2.imag(), q__2.imag() = q__3.real() * p2.imag() + q__3.imag() * p2.real(); q__1.real() = p1.real() + q__2.real(), q__1.imag() = p1.imag() + q__2.imag(); p2.real() = q__1.real(), p2.imag() = q__1.imag(); p1.real() = pt.real(), p1.imag() = pt.imag(); ak = (float)1. - tfnf / (fkk + tfnf); ack = bk * ak; r__1 = ack + bk; q__3.real() = r__1, q__3.imag() = (float)0.; q__2.real() = q__3.real() * p1.real() - q__3.imag() * p1.imag(), q__2.imag() = q__3.real() * p1.imag() + q__3.imag() * p1.real(); q__1.real() = sum.real() + q__2.real(), q__1.imag() = sum.imag() + q__2.imag(); sum.real() = q__1.real(), sum.imag() = q__1.imag(); bk = ack; fkk += (float)-1.; m = *n - i__ + 1; i__2 = m; y[i__2].real() = p2.real(), y[i__2].imag() = p2.imag(); /* L60: */ } L70: if(ifnu <= 0) { goto L90; } i__1 = ifnu; for(i__ = 1; i__ <= i__1; ++i__) { pt.real() = p2.real(), pt.imag() = p2.imag(); r__1 = fkk + fnf; q__4.real() = r__1, q__4.imag() = (float)0.; q__3.real() = q__4.real() * rz.real() - q__4.imag() * rz.imag(), q__3.imag() = q__4.real() * rz.imag() + q__4.imag() * rz.real(); q__2.real() = q__3.real() * p2.real() - q__3.imag() * p2.imag(), q__2.imag() = q__3.real() * p2.imag() + q__3.imag() * p2.real(); q__1.real() = p1.real() + q__2.real(), q__1.imag() = p1.imag() + q__2.imag(); p2.real() = q__1.real(), p2.imag() = q__1.imag(); p1.real() = pt.real(), p1.imag() = pt.imag(); ak = (float)1. - tfnf / (fkk + tfnf); ack = bk * ak; r__1 = ack + bk; q__3.real() = r__1, q__3.imag() = (float)0.; q__2.real() = q__3.real() * p1.real() - q__3.imag() * p1.imag(), q__2.imag() = q__3.real() * p1.imag() + q__3.imag() * p1.real(); q__1.real() = sum.real() + q__2.real(), q__1.imag() = sum.imag() + q__2.imag(); sum.real() = q__1.real(), sum.imag() = q__1.imag(); bk = ack; fkk += (float)-1.; /* L80: */ } L90: pt.real() = z__->real(), pt.imag() = z__->imag(); if(*kode == 2) { q__2.real() = x, q__2.imag() = (float)0.; q__1.real() = pt.real() - q__2.real(), q__1.imag() = pt.imag() - q__2.imag(); pt.real() = q__1.real(), pt.imag() = q__1.imag(); } q__4.real() = fnf, q__4.imag() = (float)0.; q__3.real() = -q__4.real(), q__3.imag() = -q__4.imag(); c_log(&q__5, &rz); q__2.real() = q__3.real() * q__5.real() - q__3.imag() * q__5.imag(), q__2.imag() = q__3.real() * q__5.imag() + q__3.imag() * q__5.real(); q__1.real() = q__2.real() + pt.real(), q__1.imag() = q__2.imag() + pt.imag(); p1.real() = q__1.real(), p1.imag() = q__1.imag(); r__1 = fnf + (float)1.; ap = gamln_(&r__1, &idum); q__2.real() = ap, q__2.imag() = (float)0.; q__1.real() = p1.real() - q__2.real(), q__1.imag() = p1.imag() - q__2.imag(); pt.real() = q__1.real(), pt.imag() = q__1.imag(); /* ----------------------------------------------------------------------- */ /* THE DIVISION CEXP(PT)/(SUM+P2) IS ALTERED TO AVOID OVERFLOW */ /* IN THE DENOMINATOR BY SQUARING LARGE QUANTITIES */ /* ----------------------------------------------------------------------- */ q__1.real() = p2.real() + sum.real(), q__1.imag() = p2.imag() + sum.imag(); p2.real() = q__1.real(), p2.imag() = q__1.imag(); ap = c_abs(&p2); r__1 = (float)1. / ap; q__1.real() = r__1, q__1.imag() = (float)0.; p1.real() = q__1.real(), p1.imag() = q__1.imag(); c_exp(&q__2, &pt); q__1.real() = q__2.real() * p1.real() - q__2.imag() * p1.imag(), q__1.imag() = q__2.real() * p1.imag() + q__2.imag() * p1.real(); ck.real() = q__1.real(), ck.imag() = q__1.imag(); r_cnjg(&q__2, &p2); q__1.real() = q__2.real() * p1.real() - q__2.imag() * p1.imag(), q__1.imag() = q__2.real() * p1.imag() + q__2.imag() * p1.real(); pt.real() = q__1.real(), pt.imag() = q__1.imag(); q__1.real() = ck.real() * pt.real() - ck.imag() * pt.imag(), q__1.imag() = ck.real() * pt.imag() + ck.imag() * pt.real(); cnorm.real() = q__1.real(), cnorm.imag() = q__1.imag(); i__1 = *n; for(i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; i__3 = i__; q__1.real() = y[i__3].real() * cnorm.real() - y[i__3].imag() * cnorm.imag(), q__1.imag() = y[i__3].real() * cnorm.imag() + y[i__3].imag() * cnorm.real(); y[i__2].real() = q__1.real(), y[i__2].imag() = q__1.imag(); /* L100: */ } return 0; L110: *nz = -2; return 0; } /* cmlri_ */ int crati_(System::Complex<float>* z__, float* fnu, int32* n, System::Complex<float>* cy, float* tol) { /* Initialized data */ static System::Complex<float> czero = {(float)0., (float)0.}; static System::Complex<float> cone = {(float)1., (float)0.}; /* System generated locals */ int32 i__1, i__2; float r__1; System::Complex<float> q__1, q__2, q__3, q__4; int32 i__, k; System::Complex<float> p1, p2, t1; float ak; int32 id, kk; float az; System::Complex<float> pt, rz; float ap1, ap2, arg, rho; int32 inu; float rap1, flam, dfnu, fdnu; int32 magz, idnu; float fnup, test, test1; System::Complex<float> cdfnu; float amagz; int32 itime; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE CRATI */ /* ***REFER TO CBESI,CBESK,CBESH */ /* CRATI COMPUTES RATIOS OF I BESSEL FUNCTIONS BY BACKWARD */ /* RECURRENCE. THE STARTING INDEX IS DETERMINED BY FORWARD */ /* RECURRENCE AS DESCRIBED IN J. RES. OF NAT. BUR. OF STANDARDS-B, */ /* MATHEMATICAL SCIENCES, VOL 77B, P111-114, SEPTEMBER, 1973, */ /* BESSEL FUNCTIONS I AND J OF COMPLEX ARGUMENT AND INTEGER ORDER, */ /* BY D. J. SOOKNE. */ /* ***ROUTINES CALLED (NONE) */ /* ***END PROLOGUE CRATI */ /* Parameter adjustments */ --cy; /* Function Body */ az = c_abs(z__); inu = (int32)(*fnu); idnu = inu + *n - 1; fdnu = (float)idnu; magz = (int32)az; amagz = (float)(magz + 1); fnup = max(amagz, fdnu); id = idnu - magz - 1; itime = 1; k = 1; q__2.real() = cone.real() + cone.real(), q__2.imag() = cone.imag() + cone.imag(); c_div(&q__1, &q__2, z__); rz.real() = q__1.real(), rz.imag() = q__1.imag(); q__2.real() = fnup, q__2.imag() = (float)0.; q__1.real() = q__2.real() * rz.real() - q__2.imag() * rz.imag(), q__1.imag() = q__2.real() * rz.imag() + q__2.imag() * rz.real(); t1.real() = q__1.real(), t1.imag() = q__1.imag(); q__1.real() = -t1.real(), q__1.imag() = -t1.imag(); p2.real() = q__1.real(), p2.imag() = q__1.imag(); p1.real() = cone.real(), p1.imag() = cone.imag(); q__1.real() = t1.real() + rz.real(), q__1.imag() = t1.imag() + rz.imag(); t1.real() = q__1.real(), t1.imag() = q__1.imag(); if(id > 0) { id = 0; } ap2 = c_abs(&p2); ap1 = c_abs(&p1); /* ----------------------------------------------------------------------- */ /* THE OVERFLOW TEST ON K(FNU+I-1,Z) BEFORE THE CALL TO CBKNX */ /* GUARANTEES THAT P2 IS ON SCALE. SCALE TEST1 AND ALL SUBSEQUENT */ /* P2 VALUES BY AP1 TO ENSURE THAT AN OVERFLOW DOES NOT OCCUR */ /* PREMATURELY. */ /* ----------------------------------------------------------------------- */ arg = (ap2 + ap2) / (ap1 * *tol); test1 = sqrt(arg); test = test1; rap1 = (float)1. / ap1; q__2.real() = rap1, q__2.imag() = (float)0.; q__1.real() = p1.real() * q__2.real() - p1.imag() * q__2.imag(), q__1.imag() = p1.real() * q__2.imag() + p1.imag() * q__2.real(); p1.real() = q__1.real(), p1.imag() = q__1.imag(); q__2.real() = rap1, q__2.imag() = (float)0.; q__1.real() = p2.real() * q__2.real() - p2.imag() * q__2.imag(), q__1.imag() = p2.real() * q__2.imag() + p2.imag() * q__2.real(); p2.real() = q__1.real(), p2.imag() = q__1.imag(); ap2 *= rap1; L10: ++k; ap1 = ap2; pt.real() = p2.real(), pt.imag() = p2.imag(); q__2.real() = t1.real() * p2.real() - t1.imag() * p2.imag(), q__2.imag() = t1.real() * p2.imag() + t1.imag() * p2.real(); q__1.real() = p1.real() - q__2.real(), q__1.imag() = p1.imag() - q__2.imag(); p2.real() = q__1.real(), p2.imag() = q__1.imag(); p1.real() = pt.real(), p1.imag() = pt.imag(); q__1.real() = t1.real() + rz.real(), q__1.imag() = t1.imag() + rz.imag(); t1.real() = q__1.real(), t1.imag() = q__1.imag(); ap2 = c_abs(&p2); if(ap1 <= test) { goto L10; } if(itime == 2) { goto L20; } ak = c_abs(&t1) * (float).5; flam = ak + sqrt(ak * ak - (float)1.); /* Computing MIN */ r__1 = ap2 / ap1; rho = std::min(r__1, flam); test = test1 * sqrt(rho / (rho * rho - (float)1.)); itime = 2; goto L10; L20: kk = k + 1 - id; ak = (float)kk; dfnu = *fnu + (float)(*n - 1); q__1.real() = dfnu, q__1.imag() = (float)0.; cdfnu.real() = q__1.real(), cdfnu.imag() = q__1.imag(); q__1.real() = ak, q__1.imag() = (float)0.; t1.real() = q__1.real(), t1.imag() = q__1.imag(); r__1 = (float)1. / ap2; q__1.real() = r__1, q__1.imag() = (float)0.; p1.real() = q__1.real(), p1.imag() = q__1.imag(); p2.real() = czero.real(), p2.imag() = czero.imag(); i__1 = kk; for(i__ = 1; i__ <= i__1; ++i__) { pt.real() = p1.real(), pt.imag() = p1.imag(); q__4.real() = cdfnu.real() + t1.real(), q__4.imag() = cdfnu.imag() + t1.imag(); q__3.real() = rz.real() * q__4.real() - rz.imag() * q__4.imag(), q__3.imag() = rz.real() * q__4.imag() + rz.imag() * q__4.real(); q__2.real() = q__3.real() * p1.real() - q__3.imag() * p1.imag(), q__2.imag() = q__3.real() * p1.imag() + q__3.imag() * p1.real(); q__1.real() = q__2.real() + p2.real(), q__1.imag() = q__2.imag() + p2.imag(); p1.real() = q__1.real(), p1.imag() = q__1.imag(); p2.real() = pt.real(), p2.imag() = pt.imag(); q__1.real() = t1.real() - cone.real(), q__1.imag() = t1.imag() - cone.imag(); t1.real() = q__1.real(), t1.imag() = q__1.imag(); /* L30: */ } if(p1.real() != (float)0. || r_imag(&p1) != (float)0.) { goto L40; } q__1.real() = *tol, q__1.imag() = *tol; p1.real() = q__1.real(), p1.imag() = q__1.imag(); L40: i__1 = *n; c_div(&q__1, &p2, &p1); cy[i__1].real() = q__1.real(), cy[i__1].imag() = q__1.imag(); if(*n == 1) { return 0; } k = *n - 1; ak = (float)k; q__1.real() = ak, q__1.imag() = (float)0.; t1.real() = q__1.real(), t1.imag() = q__1.imag(); q__2.real() = *fnu, q__2.imag() = (float)0.; q__1.real() = q__2.real() * rz.real() - q__2.imag() * rz.imag(), q__1.imag() = q__2.real() * rz.imag() + q__2.imag() * rz.real(); cdfnu.real() = q__1.real(), cdfnu.imag() = q__1.imag(); i__1 = *n; for(i__ = 2; i__ <= i__1; ++i__) { q__3.real() = t1.real() * rz.real() - t1.imag() * rz.imag(), q__3.imag() = t1.real() * rz.imag() + t1.imag() * rz.real(); q__2.real() = cdfnu.real() + q__3.real(), q__2.imag() = cdfnu.imag() + q__3.imag(); i__2 = k + 1; q__1.real() = q__2.real() + cy[i__2].real(), q__1.imag() = q__2.imag() + cy[i__2].imag(); pt.real() = q__1.real(), pt.imag() = q__1.imag(); if(pt.real() != (float)0. || r_imag(&pt) != (float)0.) { goto L50; } q__1.real() = *tol, q__1.imag() = *tol; pt.real() = q__1.real(), pt.imag() = q__1.imag(); L50: i__2 = k; c_div(&q__1, &cone, &pt); cy[i__2].real() = q__1.real(), cy[i__2].imag() = q__1.imag(); q__1.real() = t1.real() - cone.real(), q__1.imag() = t1.imag() - cone.imag(); t1.real() = q__1.real(), t1.imag() = q__1.imag(); --k; /* L60: */ } return 0; } /* crati_ */ int cs1s2_(System::Complex<float>* zr, System::Complex<float>* s1, System::Complex<float>* s2, int32* nz, float* ascle, float* alim, int32* iuf) { /* Initialized data */ static System::Complex<float> czero = {(float)0., (float)0.}; /* System generated locals */ System::Complex<float> q__1, q__2, q__3; /* functions */ , r_imag(System::Complex<float>*); , c_exp(System::Complex<float>*, System::Complex<float>*); System::Complex<float> c1; float aa, xx, as1, as2; System::Complex<float> s1d; float aln; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE CS1S2 */ /* ***REFER TO CBESK,CAIRY */ /* CS1S2 TESTS FOR A POSSIBLE UNDERFLOW RESULTING FROM THE */ /* ADDITION OF THE I AND K FUNCTIONS IN THE ANALYTIC CON- */ /* TINUATION FORMULA WHERE S1=K FUNCTION AND S2=I FUNCTION. */ /* ON KODE=1 THE I AND K FUNCTIONS ARE DIFFERENT ORDERS OF */ /* MAGNITUDE, BUT FOR KODE=2 THEY CAN BE OF THE SAME ORDER */ /* OF MAGNITUDE AND THE MAXIMUM MUST BE AT LEAST ONE */ /* PRECISION ABOVE THE UNDERFLOW LIMIT. */ /* ***ROUTINES CALLED (NONE) */ /* ***END PROLOGUE CS1S2 */ *nz = 0; as1 = c_abs(s1); as2 = c_abs(s2); aa = s1->real(); aln = r_imag(s1); if(aa == (float)0. && aln == (float)0.) { goto L10; } if(as1 == (float)0.) { goto L10; } xx = zr->real(); aln = -xx - xx + log(as1); s1d.real() = s1->real(), s1d.imag() = s1->imag(); s1->real() = czero.real(), s1->imag() = czero.imag(); as1 = (float)0.; if(aln < -(*alim)) { goto L10; } c_log(&q__3, &s1d); q__2.real() = q__3.real() - zr->real(), q__2.imag() = q__3.imag() - zr->imag(); q__1.real() = q__2.real() - zr->real(), q__1.imag() = q__2.imag() - zr->imag(); c1.real() = q__1.real(), c1.imag() = q__1.imag(); c_exp(&q__1, &c1); s1->real() = q__1.real(), s1->imag() = q__1.imag(); as1 = c_abs(s1); ++(*iuf); L10: aa = max(as1, as2); if(aa > *ascle) { return 0; } s1->real() = czero.real(), s1->imag() = czero.imag(); s2->real() = czero.real(), s2->imag() = czero.imag(); *nz = 1; *iuf = 0; return 0; } /* cs1s2_ */ int cseri_(System::Complex<float>* z__, float* fnu, int32* kode, int32* n, System::Complex<float>* y, int32* nz, float* tol, float* elim, float* alim) { /* Initialized data */ static System::Complex<float> czero = {(float)0., (float)0.}; static System::Complex<float> cone = {(float)1., (float)0.}; /* System generated locals */ int32 i__1, i__2, i__3, i__4; float r__1, r__2; System::Complex<float> q__1, q__2, q__3, q__4; int32 i__, k, l, m; float s; System::Complex<float> w[2]; float x; System::Complex<float> s1, s2; float aa; int32 ib; float ak; System::Complex<float> ck; int32 il; float az; int32 nn; System::Complex<float> cz, hz; float rs, ss; int32 nw; System::Complex<float> rz, ak1; float acz, arm, rak1, rtr1; System::Complex<float> coef, crsc; float dfnu; int32 idum; float atol, fnup; int32 iflag; float ascle; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE CSERI */ /* ***REFER TO CBESI,CBESK */ /* CSERI COMPUTES THE I BESSEL FUNCTION FOR REAL(Z).GE.0.0 BY */ /* MEANS OF THE POWER SERIES FOR LARGE CABS(Z) IN THE */ /* REGION CABS(Z).LE.2*SQRT(FNU+1). NZ=0 IS A NORMAL RETURN. */ /* NZ.GT.0 MEANS THAT THE LAST NZ COMPONENTS WERE SET TO ZERO */ /* DUE TO UNDERFLOW. NZ.LT.0 MEANS UNDERFLOW OCCURRED, BUT THE */ /* CONDITION CABS(Z).LE.2*SQRT(FNU+1) WAS VIOLATED AND THE */ /* COMPUTATION MUST BE COMPLETED IN ANOTHER ROUTINE WITH N=N-ABS(NZ). */ /* ***ROUTINES CALLED CUCHK,GAMLN,R1MACH */ /* ***END PROLOGUE CSERI */ /* Parameter adjustments */ --y; /* Function Body */ *nz = 0; az = c_abs(z__); if(az == (float)0.) { goto L150; } x = z__->real(); arm = r1mach_(&c__1) * (float)1e3; rtr1 = sqrt(arm); crsc.real() = (float)1., crsc.imag() = (float)0.; iflag = 0; if(az < arm) { goto L140; } q__1.real() = z__->real() * (float).5 - z__->imag() * (float)0., q__1.imag() = z__->real() * (float)0. + z__->imag() * (float).5; hz.real() = q__1.real(), hz.imag() = q__1.imag(); cz.real() = czero.real(), cz.imag() = czero.imag(); if(az > rtr1) { q__1.real() = hz.real() * hz.real() - hz.imag() * hz.imag(), q__1.imag() = hz.real() * hz.imag() + hz.imag() * hz.real(); cz.real() = q__1.real(), cz.imag() = q__1.imag(); } acz = c_abs(&cz); nn = *n; c_log(&q__1, &hz); ck.real() = q__1.real(), ck.imag() = q__1.imag(); L10: dfnu = *fnu + (float)(nn - 1); fnup = dfnu + (float)1.; /* ----------------------------------------------------------------------- */ /* UNDERFLOW TEST */ /* ----------------------------------------------------------------------- */ q__2.real() = dfnu, q__2.imag() = (float)0.; q__1.real() = ck.real() * q__2.real() - ck.imag() * q__2.imag(), q__1.imag() = ck.real() * q__2.imag() + ck.imag() * q__2.real(); ak1.real() = q__1.real(), ak1.imag() = q__1.imag(); ak = gamln_(&fnup, &idum); q__2.real() = ak, q__2.imag() = (float)0.; q__1.real() = ak1.real() - q__2.real(), q__1.imag() = ak1.imag() - q__2.imag(); ak1.real() = q__1.real(), ak1.imag() = q__1.imag(); if(*kode == 2) { q__2.real() = x, q__2.imag() = (float)0.; q__1.real() = ak1.real() - q__2.real(), q__1.imag() = ak1.imag() - q__2.imag(); ak1.real() = q__1.real(), ak1.imag() = q__1.imag(); } rak1 = ak1.real(); if(rak1 > -(*elim)) { goto L30; } L20: ++(*nz); i__1 = nn; y[i__1].real() = czero.real(), y[i__1].imag() = czero.imag(); if(acz > dfnu) { goto L170; } --nn; if(nn == 0) { return 0; } goto L10; L30: if(rak1 > -(*alim)) { goto L40; } iflag = 1; ss = (float)1. / *tol; q__1.real() = *tol, q__1.imag() = (float)0.; crsc.real() = q__1.real(), crsc.imag() = q__1.imag(); ascle = arm * ss; L40: ak = r_imag(&ak1); aa = exp(rak1); if(iflag == 1) { aa *= ss; } q__2.real() = aa, q__2.imag() = (float)0.; r__1 = cos(ak); r__2 = sin(ak); q__3.real() = r__1, q__3.imag() = r__2; q__1.real() = q__2.real() * q__3.real() - q__2.imag() * q__3.imag(), q__1.imag() = q__2.real() * q__3.imag() + q__2.imag() * q__3.real(); coef.real() = q__1.real(), coef.imag() = q__1.imag(); atol = *tol * acz / fnup; il = std::min(2L, nn); i__1 = il; for(i__ = 1; i__ <= i__1; ++i__) { dfnu = *fnu + (float)(nn - i__); fnup = dfnu + (float)1.; s1.real() = cone.real(), s1.imag() = cone.imag(); if(acz < *tol * fnup) { goto L60; } ak1.real() = cone.real(), ak1.imag() = cone.imag(); ak = fnup + (float)2.; s = fnup; aa = (float)2.; L50: rs = (float)1. / s; q__2.real() = ak1.real() * cz.real() - ak1.imag() * cz.imag(), q__2.imag() = ak1.real() * cz.imag() + ak1.imag() * cz.real(); q__3.real() = rs, q__3.imag() = (float)0.; q__1.real() = q__2.real() * q__3.real() - q__2.imag() * q__3.imag(), q__1.imag() = q__2.real() * q__3.imag() + q__2.imag() * q__3.real(); ak1.real() = q__1.real(), ak1.imag() = q__1.imag(); q__1.real() = s1.real() + ak1.real(), q__1.imag() = s1.imag() + ak1.imag(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); s += ak; ak += (float)2.; aa = aa * acz * rs; if(aa > atol) { goto L50; } L60: m = nn - i__ + 1; q__1.real() = s1.real() * coef.real() - s1.imag() * coef.imag(), q__1.imag() = s1.real() * coef.imag() + s1.imag() * coef.real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); i__2 = i__ - 1; w[i__2].real() = s2.real(), w[i__2].imag() = s2.imag(); if(iflag == 0) { goto L70; } cuchk_(&s2, &nw, &ascle, tol); if(nw != 0) { goto L20; } L70: i__2 = m; q__1.real() = s2.real() * crsc.real() - s2.imag() * crsc.imag(), q__1.imag() = s2.real() * crsc.imag() + s2.imag() * crsc.real(); y[i__2].real() = q__1.real(), y[i__2].imag() = q__1.imag(); if(i__ != il) { q__3.real() = dfnu, q__3.imag() = (float)0.; q__2.real() = coef.real() * q__3.real() - coef.imag() * q__3.imag(), q__2.imag() = coef.real() * q__3.imag() + coef.imag() * q__3.real(); c_div(&q__1, &q__2, &hz); coef.real() = q__1.real(), coef.imag() = q__1.imag(); } /* L80: */ } if(nn <= 2) { return 0; } k = nn - 2; ak = (float)k; q__2.real() = cone.real() + cone.real(), q__2.imag() = cone.imag() + cone.imag(); c_div(&q__1, &q__2, z__); rz.real() = q__1.real(), rz.imag() = q__1.imag(); if(iflag == 1) { goto L110; } ib = 3; L90: i__1 = nn; for(i__ = ib; i__ <= i__1; ++i__) { i__2 = k; r__1 = ak + *fnu; q__4.real() = r__1, q__4.imag() = (float)0.; q__3.real() = q__4.real() * rz.real() - q__4.imag() * rz.imag(), q__3.imag() = q__4.real() * rz.imag() + q__4.imag() * rz.real(); i__3 = k + 1; q__2.real() = q__3.real() * y[i__3].real() - q__3.imag() * y[i__3].imag(), q__2.imag() = q__3.real() * y[i__3].imag() + q__3.imag() * y[i__3].real(); i__4 = k + 2; q__1.real() = q__2.real() + y[i__4].real(), q__1.imag() = q__2.imag() + y[i__4].imag(); y[i__2].real() = q__1.real(), y[i__2].imag() = q__1.imag(); ak += (float)-1.; --k; /* L100: */ } return 0; /* ----------------------------------------------------------------------- */ /* RECUR BACKWARD WITH SCALED VALUES */ /* ----------------------------------------------------------------------- */ L110: /* ----------------------------------------------------------------------- */ /* EXP(-ALIM)=EXP(-ELIM)/TOL=APPROX. ONE PRECISION ABOVE THE */ /* UNDERFLOW LIMIT = ASCLE = R1MACH(1)*CSCL*1.0E+3 */ /* ----------------------------------------------------------------------- */ s1.real() = w[0].real(), s1.imag() = w[0].imag(); s2.real() = w[1].real(), s2.imag() = w[1].imag(); i__1 = nn; for(l = 3; l <= i__1; ++l) { ck.real() = s2.real(), ck.imag() = s2.imag(); r__1 = ak + *fnu; q__4.real() = r__1, q__4.imag() = (float)0.; q__3.real() = q__4.real() * rz.real() - q__4.imag() * rz.imag(), q__3.imag() = q__4.real() * rz.imag() + q__4.imag() * rz.real(); q__2.real() = q__3.real() * s2.real() - q__3.imag() * s2.imag(), q__2.imag() = q__3.real() * s2.imag() + q__3.imag() * s2.real(); q__1.real() = s1.real() + q__2.real(), q__1.imag() = s1.imag() + q__2.imag(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); s1.real() = ck.real(), s1.imag() = ck.imag(); q__1.real() = s2.real() * crsc.real() - s2.imag() * crsc.imag(), q__1.imag() = s2.real() * crsc.imag() + s2.imag() * crsc.real(); ck.real() = q__1.real(), ck.imag() = q__1.imag(); i__2 = k; y[i__2].real() = ck.real(), y[i__2].imag() = ck.imag(); ak += (float)-1.; --k; if(c_abs(&ck) > ascle) { goto L130; } /* L120: */ } return 0; L130: ib = l + 1; if(ib > nn) { return 0; } goto L90; L140: *nz = *n; if(*fnu == (float)0.) { --(*nz); } L150: y[1].real() = czero.real(), y[1].imag() = czero.imag(); if(*fnu == (float)0.) { y[1].real() = cone.real(), y[1].imag() = cone.imag(); } if(*n == 1) { return 0; } i__1 = *n; for(i__ = 2; i__ <= i__1; ++i__) { i__2 = i__; y[i__2].real() = czero.real(), y[i__2].imag() = czero.imag(); /* L160: */ } return 0; /* ----------------------------------------------------------------------- */ /* RETURN WITH NZ.LT.0 IF CABS(Z*Z/4).GT.FNU+N-NZ-1 COMPLETE */ /* THE CALCULATION IN CBINU WITH N=N-IABS(NZ) */ /* ----------------------------------------------------------------------- */ L170: *nz = -(*nz); return 0; } /* cseri_ */ int cshch_(System::Complex<float>* z__, System::Complex<float>* csh, System::Complex<float>* cch) { /* System generated locals */ System::Complex<float> q__1; float x, y, ch, cn, sh, sn, cchi, cchr, cshi, cshr; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE CSHCH */ /* ***REFER TO CBESK,CBESH */ /* CSHCH COMPUTES THE COMPLEX HYPERBOLIC FUNCTIONS CSH=SINH(X+I*Y) */ /* AND CCH=COSH(X+I*Y), WHERE I**2=-1. */ /* ***ROUTINES CALLED (NONE) */ /* ***END PROLOGUE CSHCH */ x = z__->real(); y = r_imag(z__); sh = sinh(x); ch = cosh(x); sn = sin(y); cn = cos(y); cshr = sh * cn; cshi = ch * sn; q__1.real() = cshr, q__1.imag() = cshi; csh->real() = q__1.real(), csh->imag() = q__1.imag(); cchr = ch * cn; cchi = sh * sn; q__1.real() = cchr, q__1.imag() = cchi; cch->real() = q__1.real(), cch->imag() = q__1.imag(); return 0; } /* cshch_ */ int cuchk_(System::Complex<float>* y, int32* nz, float* ascle, float* tol) { float yi, ss, st, yr; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE CUCHK */ /* ***REFER TO CSERI,CUOIK,CUNK1,CUNK2,CUNI1,CUNI2,CKSCL */ /* Y ENTERS AS A SCALED QUANTITY WHOSE MAGNITUDE IS GREATER THAN */ /* EXP(-ALIM)=ASCLE=1.0E+3*R1MACH(1)/TOL. THE TEST IS MADE TO SEE */ /* IF THE MAGNITUDE OF THE REAL OR IMAGINARY PART WOULD UNDER FLOW */ /* WHEN Y IS SCALED (BY TOL) TO ITS PROPER VALUE. Y IS ACCEPTED */ /* IF THE UNDERFLOW IS AT LEAST ONE PRECISION BELOW THE MAGNITUDE */ /* OF THE LARGEST COMPONENT; OTHERWISE THE PHASE ANGLE DOES NOT HAVE */ /* ABSOLUTE ACCURACY AND AN UNDERFLOW IS ASSUMED. */ /* ***ROUTINES CALLED (NONE) */ /* ***END PROLOGUE CUCHK */ *nz = 0; yr = y->real(); yi = r_imag(y); yr = abs(yr); yi = abs(yi); st = std::min(yr, yi); if(st > *ascle) { return 0; } ss = max(yr, yi); st /= *tol; if(ss < st) { *nz = 1; } return 0; } /* cuchk_ */ int cunhj_(System::Complex<float>* z__, float* fnu, int32* ipmtr, float* tol, System::Complex<float>* phi, System::Complex<float>* arg, System::Complex<float>* zeta1, System::Complex<float>* zeta2, System::Complex<float>* asum, System::Complex<float>* bsum) { /* Initialized data */ static float ar[14] = {(float)1., (float).104166666666666667, (float).0835503472222222222, (float).12822657455632716, (float).291849026464140464, (float).881627267443757652, (float)3.32140828186276754, (float)14.9957629868625547, (float)78.9230130115865181, (float)474.451538868264323, (float)3207.49009089066193, (float)24086.5496408740049, (float)198923.119169509794, (float)1791902.00777534383}; static float br[14] = {(float)1., (float)-.145833333333333333, (float)-.0987413194444444444, (float)-.143312053915895062, (float)-.317227202678413548, (float)-.942429147957120249, (float)-3.51120304082635426, (float)-15.7272636203680451, (float)-82.2814390971859444, (float)-492.355370523670524, (float)-3316.21856854797251, (float)-24827.6742452085896, (float)-204526.587315129788, (float)-1838444.9170682099}; static float c__[105] = {(float)1., (float)-.208333333333333333, (float).125, (float).334201388888888889, (float)-.401041666666666667, (float).0703125, (float)-1.02581259645061728, (float)1.84646267361111111, (float)-.8912109375, (float).0732421875, (float)4.66958442342624743, (float)-11.2070026162229938, (float)8.78912353515625, (float)-2.3640869140625, (float).112152099609375, (float)-28.2120725582002449, (float)84.6362176746007346, (float)-91.8182415432400174, (float)42.5349987453884549, (float)-7.3687943594796317, (float).227108001708984375, (float)212.570130039217123, (float)-765.252468141181642, (float)1059.99045252799988, (float)-699.579627376132541, (float)218.19051174421159, (float)-26.4914304869515555, (float).572501420974731445, (float)-1919.457662318407, (float)8061.72218173730938, (float)-13586.5500064341374, (float)11655.3933368645332, (float)-5305.64697861340311, (float)1200.90291321635246, (float)-108.090919788394656, (float)1.7277275025844574, (float)20204.2913309661486, (float)-96980.5983886375135, (float)192547.001232531532, (float)-203400.177280415534, (float)122200.46498301746, (float)-41192.6549688975513, (float)7109.51430248936372, (float)-493.915304773088012, (float)6.07404200127348304, (float)-242919.187900551333, (float)1311763.6146629772, (float)-2998015.91853810675, (float)3763271.297656404, (float)-2813563.22658653411, (float)1268365.27332162478, (float)-331645.172484563578, (float)45218.7689813627263, (float)-2499.83048181120962, (float)24.3805296995560639, (float)3284469.85307203782, (float)-19706819.1184322269, (float)50952602.4926646422, (float)-74105148.2115326577, (float)66344512.2747290267, (float)-37567176.6607633513, (float)13288767.1664218183, (float)-2785618.12808645469, (float)308186.404612662398, (float)-13886.0897537170405, (float)110.017140269246738, (float)-49329253.664509962, (float)325573074.185765749, (float)-939462359.681578403, (float)1553596899.57058006, (float)-1621080552.10833708, (float)1106842816.82301447, (float)-495889784.275030309, (float)142062907.797533095, (float)-24474062.7257387285, (float)2243768.17792244943, (float)-84005.4336030240853, (float)551.335896122020586, (float)814789096.118312115, (float)-5866481492.05184723, (float)18688207509.2958249, (float)-34632043388.1587779, (float)41280185579.753974, (float)-33026599749.8007231, (float)17954213731.1556001, (float)-6563293792.61928433, (float)1559279864.87925751, (float)-225105661.889415278, (float)17395107.5539781645, (float)-549842.327572288687, (float)3038.09051092238427, (float)-14679261247.6956167, (float)114498237732.02581, (float)-399096175224.466498, (float)819218669548.577329, (float)-1098375156081.22331, (float)1008158106865.38209, (float)-645364869245.376503, (float)287900649906.150589, (float)-87867072178.0232657, (float)17634730606.8349694, (float)-2167164983.22379509, (float)143157876.718888981, (float)-3871833.44257261262, (float)18257.7554742931747}; static float alfa[180] = { (float)-.00444444444444444444, (float)-9.22077922077922078e-4, (float)-8.84892884892884893e-5, (float)1.65927687832449737e-4, (float)2.4669137274179291e-4, (float)2.6599558934625478e-4, (float)2.61824297061500945e-4, (float)2.48730437344655609e-4, (float)2.32721040083232098e-4, (float)2.16362485712365082e-4, (float)2.00738858762752355e-4, (float)1.86267636637545172e-4, (float)1.73060775917876493e-4, (float)1.61091705929015752e-4, (float)1.50274774160908134e-4, (float)1.40503497391269794e-4, (float)1.31668816545922806e-4, (float)1.23667445598253261e-4, (float)1.16405271474737902e-4, (float)1.09798298372713369e-4, (float)1.03772410422992823e-4, (float)9.82626078369363448e-5, (float)9.32120517249503256e-5, (float)8.85710852478711718e-5, (float)8.42963105715700223e-5, (float)8.03497548407791151e-5, (float)7.66981345359207388e-5, (float)7.33122157481777809e-5, (float)7.01662625163141333e-5, (float)6.72375633790160292e-5, (float)6.93735541354588974e-4, (float)2.32241745182921654e-4, (float)-1.41986273556691197e-5, (float)-1.1644493167204864e-4, (float)-1.50803558053048762e-4, (float)-1.55121924918096223e-4, (float)-1.46809756646465549e-4, (float)-1.33815503867491367e-4, (float)-1.19744975684254051e-4, (float)-1.0618431920797402e-4, (float)-9.37699549891194492e-5, (float)-8.26923045588193274e-5, (float)-7.29374348155221211e-5, (float)-6.44042357721016283e-5, (float)-5.69611566009369048e-5, (float)-5.04731044303561628e-5, (float)-4.48134868008882786e-5, (float)-3.98688727717598864e-5, (float)-3.55400532972042498e-5, (float)-3.1741425660902248e-5, (float)-2.83996793904174811e-5, (float)-2.54522720634870566e-5, (float)-2.28459297164724555e-5, (float)-2.05352753106480604e-5, (float)-1.84816217627666085e-5, (float)-1.66519330021393806e-5, (float)-1.50179412980119482e-5, (float)-1.35554031379040526e-5, (float)-1.22434746473858131e-5, (float)-1.10641884811308169e-5, (float)-3.54211971457743841e-4, (float)-1.56161263945159416e-4, (float)3.0446550359493641e-5, (float)1.30198655773242693e-4, (float)1.67471106699712269e-4, (float)1.70222587683592569e-4, (float)1.56501427608594704e-4, (float)1.3633917097744512e-4, (float)1.14886692029825128e-4, (float)9.45869093034688111e-5, (float)7.64498419250898258e-5, (float)6.07570334965197354e-5, (float)4.74394299290508799e-5, (float)3.62757512005344297e-5, (float)2.69939714979224901e-5, (float)1.93210938247939253e-5, (float)1.30056674793963203e-5, (float)7.82620866744496661e-6, (float)3.59257485819351583e-6, (float)1.44040049814251817e-7, (float)-2.65396769697939116e-6, (float)-4.9134686709848591e-6, (float)-6.72739296091248287e-6, (float)-8.17269379678657923e-6, (float)-9.31304715093561232e-6, (float)-1.02011418798016441e-5, (float)-1.0880596251059288e-5, (float)-1.13875481509603555e-5, (float)-1.17519675674556414e-5, (float)-1.19987364870944141e-5, (float)3.78194199201772914e-4, (float)2.02471952761816167e-4, (float)-6.37938506318862408e-5, (float)-2.38598230603005903e-4, (float)-3.10916256027361568e-4, (float)-3.13680115247576316e-4, (float)-2.78950273791323387e-4, (float)-2.28564082619141374e-4, (float)-1.75245280340846749e-4, (float)-1.25544063060690348e-4, (float)-8.22982872820208365e-5, (float)-4.62860730588116458e-5, (float)-1.72334302366962267e-5, (float)5.60690482304602267e-6, (float)2.313954431482868e-5, (float)3.62642745856793957e-5, (float)4.58006124490188752e-5, (float)5.2459529495911405e-5, (float)5.68396208545815266e-5, (float)5.94349820393104052e-5, (float)6.06478527578421742e-5, (float)6.08023907788436497e-5, (float)6.01577894539460388e-5, (float)5.891996573446985e-5, (float)5.72515823777593053e-5, (float)5.52804375585852577e-5, (float)5.3106377380288017e-5, (float)5.08069302012325706e-5, (float)4.84418647620094842e-5, (float)4.6056858160747537e-5, (float)-6.91141397288294174e-4, (float)-4.29976633058871912e-4, (float)1.83067735980039018e-4, (float)6.60088147542014144e-4, (float)8.75964969951185931e-4, (float)8.77335235958235514e-4, (float)7.49369585378990637e-4, (float)5.63832329756980918e-4, (float)3.68059319971443156e-4, (float)1.88464535514455599e-4, (float)3.70663057664904149e-5, (float)-8.28520220232137023e-5, (float)-1.72751952869172998e-4, (float)-2.36314873605872983e-4, (float)-2.77966150694906658e-4, (float)-3.02079514155456919e-4, (float)-3.12594712643820127e-4, (float)-3.12872558758067163e-4, (float)-3.05678038466324377e-4, (float)-2.93226470614557331e-4, (float)-2.77255655582934777e-4, (float)-2.59103928467031709e-4, (float)-2.39784014396480342e-4, (float)-2.20048260045422848e-4, (float)-2.00443911094971498e-4, (float)-1.81358692210970687e-4, (float)-1.63057674478657464e-4, (float)-1.45712672175205844e-4, (float)-1.29425421983924587e-4, (float)-1.14245691942445952e-4, (float).00192821964248775885, (float).00135592576302022234, (float)-7.17858090421302995e-4, (float)-.00258084802575270346, (float)-.00349271130826168475, (float)-.00346986299340960628, (float)-.00282285233351310182, (float)-.00188103076404891354, (float)-8.895317183839476e-4, (float)3.87912102631035228e-6, (float)7.28688540119691412e-4, (float).00126566373053457758, (float).00162518158372674427, (float).00183203153216373172, (float).00191588388990527909, (float).00190588846755546138, (float).00182798982421825727, (float).0017038950642112153, (float).00155097127171097686, (float).00138261421852276159, (float).00120881424230064774, (float).00103676532638344962, (float)8.71437918068619115e-4, (float)7.16080155297701002e-4, (float)5.72637002558129372e-4, (float)4.42089819465802277e-4, (float)3.24724948503090564e-4, (float)2.20342042730246599e-4, (float)1.28412898401353882e-4, (float)4.82005924552095464e-5}; static float beta[210] = { (float).0179988721413553309, (float).00559964911064388073, (float).00288501402231132779, (float).00180096606761053941, (float).00124753110589199202, (float)9.22878876572938311e-4, (float)7.14430421727287357e-4, (float)5.71787281789704872e-4, (float)4.69431007606481533e-4, (float)3.93232835462916638e-4, (float)3.34818889318297664e-4, (float)2.88952148495751517e-4, (float)2.52211615549573284e-4, (float)2.22280580798883327e-4, (float)1.97541838033062524e-4, (float)1.76836855019718004e-4, (float)1.59316899661821081e-4, (float)1.44347930197333986e-4, (float)1.31448068119965379e-4, (float)1.20245444949302884e-4, (float)1.10449144504599392e-4, (float)1.01828770740567258e-4, (float)9.41998224204237509e-5, (float)8.74130545753834437e-5, (float)8.13466262162801467e-5, (float)7.59002269646219339e-5, (float)7.09906300634153481e-5, (float)6.65482874842468183e-5, (float)6.25146958969275078e-5, (float)5.88403394426251749e-5, (float)-.00149282953213429172, (float)-8.78204709546389328e-4, (float)-5.02916549572034614e-4, (float)-2.94822138512746025e-4, (float)-1.75463996970782828e-4, (float)-1.04008550460816434e-4, (float)-5.96141953046457895e-5, (float)-3.1203892907609834e-5, (float)-1.26089735980230047e-5, (float)-2.42892608575730389e-7, (float)8.05996165414273571e-6, (float)1.36507009262147391e-5, (float)1.73964125472926261e-5, (float)1.9867297884213378e-5, (float)2.14463263790822639e-5, (float)2.23954659232456514e-5, (float)2.28967783814712629e-5, (float)2.30785389811177817e-5, (float)2.30321976080909144e-5, (float)2.28236073720348722e-5, (float)2.25005881105292418e-5, (float)2.20981015361991429e-5, (float)2.16418427448103905e-5, (float)2.11507649256220843e-5, (float)2.06388749782170737e-5, (float)2.01165241997081666e-5, (float)1.95913450141179244e-5, (float)1.9068936791043674e-5, (float)1.85533719641636667e-5, (float)1.80475722259674218e-5, (float)5.5221307672129279e-4, (float)4.47932581552384646e-4, (float)2.79520653992020589e-4, (float)1.52468156198446602e-4, (float)6.93271105657043598e-5, (float)1.76258683069991397e-5, (float)-1.35744996343269136e-5, (float)-3.17972413350427135e-5, (float)-4.18861861696693365e-5, (float)-4.69004889379141029e-5, (float)-4.87665447413787352e-5, (float)-4.87010031186735069e-5, (float)-4.74755620890086638e-5, (float)-4.55813058138628452e-5, (float)-4.33309644511266036e-5, (float)-4.09230193157750364e-5, (float)-3.84822638603221274e-5, (float)-3.60857167535410501e-5, (float)-3.37793306123367417e-5, (float)-3.15888560772109621e-5, (float)-2.95269561750807315e-5, (float)-2.75978914828335759e-5, (float)-2.58006174666883713e-5, (float)-2.413083567612802e-5, (float)-2.25823509518346033e-5, (float)-2.11479656768912971e-5, (float)-1.98200638885294927e-5, (float)-1.85909870801065077e-5, (float)-1.74532699844210224e-5, (float)-1.63997823854497997e-5, (float)-4.74617796559959808e-4, (float)-4.77864567147321487e-4, (float)-3.20390228067037603e-4, (float)-1.61105016119962282e-4, (float)-4.25778101285435204e-5, (float)3.44571294294967503e-5, (float)7.97092684075674924e-5, (float)1.031382367082722e-4, (float)1.12466775262204158e-4, (float)1.13103642108481389e-4, (float)1.08651634848774268e-4, (float)1.01437951597661973e-4, (float)9.29298396593363896e-5, (float)8.40293133016089978e-5, (float)7.52727991349134062e-5, (float)6.69632521975730872e-5, (float)5.92564547323194704e-5, (float)5.22169308826975567e-5, (float)4.58539485165360646e-5, (float)4.01445513891486808e-5, (float)3.50481730031328081e-5, (float)3.05157995034346659e-5, (float)2.64956119950516039e-5, (float)2.29363633690998152e-5, (float)1.97893056664021636e-5, (float)1.70091984636412623e-5, (float)1.45547428261524004e-5, (float)1.23886640995878413e-5, (float)1.04775876076583236e-5, (float)8.79179954978479373e-6, (float)7.36465810572578444e-4, (float)8.72790805146193976e-4, (float)6.22614862573135066e-4, (float)2.85998154194304147e-4, (float)3.84737672879366102e-6, (float)-1.87906003636971558e-4, (float)-2.97603646594554535e-4, (float)-3.45998126832656348e-4, (float)-3.53382470916037712e-4, (float)-3.35715635775048757e-4, (float)-3.04321124789039809e-4, (float)-2.66722723047612821e-4, (float)-2.27654214122819527e-4, (float)-1.89922611854562356e-4, (float)-1.5505891859909387e-4, (float)-1.2377824076187363e-4, (float)-9.62926147717644187e-5, (float)-7.25178327714425337e-5, (float)-5.22070028895633801e-5, (float)-3.50347750511900522e-5, (float)-2.06489761035551757e-5, (float)-8.70106096849767054e-6, (float)1.1369868667510029e-6, (float)9.16426474122778849e-6, (float)1.5647778542887262e-5, (float)2.08223629482466847e-5, (float)2.48923381004595156e-5, (float)2.80340509574146325e-5, (float)3.03987774629861915e-5, (float)3.21156731406700616e-5, (float)-.00180182191963885708, (float)-.00243402962938042533, (float)-.00183422663549856802, (float)-7.62204596354009765e-4, (float)2.39079475256927218e-4, (float)9.49266117176881141e-4, (float).00134467449701540359, (float).00148457495259449178, (float).00144732339830617591, (float).00130268261285657186, (float).00110351597375642682, (float)8.86047440419791759e-4, (float)6.73073208165665473e-4, (float)4.77603872856582378e-4, (float)3.05991926358789362e-4, (float)1.6031569459472163e-4, (float)4.00749555270613286e-5, (float)-5.66607461635251611e-5, (float)-1.32506186772982638e-4, (float)-1.90296187989614057e-4, (float)-2.32811450376937408e-4, (float)-2.62628811464668841e-4, (float)-2.82050469867598672e-4, (float)-2.93081563192861167e-4, (float)-2.97435962176316616e-4, (float)-2.96557334239348078e-4, (float)-2.91647363312090861e-4, (float)-2.83696203837734166e-4, (float)-2.73512317095673346e-4, (float)-2.6175015580676858e-4, (float).00638585891212050914, (float).00962374215806377941, (float).00761878061207001043, (float).00283219055545628054, (float)-.0020984135201272009, (float)-.00573826764216626498, (float)-.0077080424449541462, (float)-.00821011692264844401, (float)-.00765824520346905413, (float)-.00647209729391045177, (float)-.00499132412004966473, (float)-.0034561228971313328, (float)-.00201785580014170775, (float)-7.59430686781961401e-4, (float)2.84173631523859138e-4, (float).00110891667586337403, (float).00172901493872728771, (float).00216812590802684701, (float).00245357710494539735, (float).00261281821058334862, (float).00267141039656276912, (float).0026520307339598043, (float).00257411652877287315, (float).00245389126236094427, (float).00230460058071795494, (float).00213684837686712662, (float).00195896528478870911, (float).00177737008679454412, (float).00159690280765839059, (float).00142111975664438546}; static float gama[30] = {(float).629960524947436582, (float).251984209978974633, (float).154790300415655846, (float).110713062416159013, (float).0857309395527394825, (float).0697161316958684292, (float).0586085671893713576, (float).0504698873536310685, (float).0442600580689154809, (float).0393720661543509966, (float).0354283195924455368, (float).0321818857502098231, (float).0294646240791157679, (float).0271581677112934479, (float).0251768272973861779, (float).0234570755306078891, (float).0219508390134907203, (float).020621082823564624, (float).0194388240897880846, (float).0183810633800683158, (float).0174293213231963172, (float).0165685837786612353, (float).0157865285987918445, (float).0150729501494095594, (float).0144193250839954639, (float).0138184805735341786, (float).0132643378994276568, (float).0127517121970498651, (float).0122761545318762767, (float).0118338262398482403}; static float ex1 = (float).333333333333333333; static float ex2 = (float).666666666666666667; static float hpi = (float)1.57079632679489662; static float pi = (float)3.14159265358979324; static float thpi = (float)4.71238898038468986; static System::Complex<float> czero = {(float)0., (float)0.}; static System::Complex<float> cone = {(float)1., (float)0.}; /* System generated locals */ int32 i__1, i__2, i__3; float r__1; double d__1, d__2; System::Complex<float> q__1, q__2, q__3, q__4, q__5; int32 j, k, l, m; System::Complex<float> p[30], w; int32 l1, l2; System::Complex<float> t2, w2; float ac, ap[30]; System::Complex<float> cr[14], dr[14], za, zb, zc; int32 is, jr; float pp, wi; int32 ju, ks, lr; System::Complex<float> up[14]; float wr, aw2; int32 kp1; float ang, fn13, fn23; int32 ias, ibs; float zci; System::Complex<float> tfn; float zcr; System::Complex<float> zth; int32 lrp1; System::Complex<float> rfn13, cfnu; float atol, btol; int32 kmax; System::Complex<float> zeta, ptfn, suma, sumb; float azth, rfnu, zthi, test, tsti; System::Complex<float> rzth; float zthr, tstr, rfnu2, zetai, asumi, bsumi, zetar, asumr, bsumr; System::Complex<float> rtzta, przth; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE CUNHJ */ /* ***REFER TO CBESI,CBESK */ /* REFERENCES */ /* HANDBOOK OF MATHEMATICAL FUNCTIONS BY M. ABRAMOWITZ AND I.A. */ /* STEGUN, AMS55, NATIONAL BUREAU OF STANDARDS, 1965, CHAPTER 9. */ /* ASYMPTOTICS AND SPECIAL FUNCTIONS BY F.W.J. OLVER, ACADEMIC */ /* PRESS, N.Y., 1974, PAGE 420 */ /* ABSTRACT */ /* CUNHJ COMPUTES PARAMETERS FOR BESSEL FUNCTIONS C(FNU,Z) = */ /* J(FNU,Z), Y(FNU,Z) OR H(I,FNU,Z) I=1,2 FOR LARGE ORDERS FNU */ /* BY MEANS OF THE UNIFORM ASYMPTOTIC EXPANSION */ /* C(FNU,Z)=C1*PHI*( ASUM*AIRY(ARG) + C2*BSUM*DAIRY(ARG) ) */ /* FOR PROPER CHOICES OF C1, C2, AIRY AND DAIRY WHERE AIRY IS */ /* AN AIRY FUNCTION AND DAIRY IS ITS DERIVATIVE. */ /* (2/3)*FNU*ZETA**1.5 = ZETA1-ZETA2, */ /* ZETA1=0.5*FNU*CLOG((1+W)/(1-W)), ZETA2=FNU*W FOR SCALING */ /* PURPOSES IN AIRY FUNCTIONS FROM CAIRY OR CBIRY. */ /* MCONJ=SIGN OF AIMAG(Z), BUT IS AMBIGUOUS WHEN Z IS REAL AND */ /* MUST BE SPECIFIED. IPMTR=0 RETURNS ALL PARAMETERS. IPMTR= */ /* 1 COMPUTES ALL EXCEPT ASUM AND BSUM. */ /* ***ROUTINES CALLED (NONE) */ /* ***END PROLOGUE CUNHJ */ rfnu = (float)1. / *fnu; /* ZB = Z*CMPLX(RFNU,0.0E0) */ /* ----------------------------------------------------------------------- */ /* OVERFLOW TEST (Z/FNU TOO SMALL) */ /* ----------------------------------------------------------------------- */ tstr = z__->real(); tsti = r_imag(z__); test = r1mach_(&c__1) * (float)1e3; ac = *fnu * test; if(abs(tstr) > ac || abs(tsti) > ac) { goto L15; } ac = (r__1 = log(test), abs(r__1)) * (float)2. + *fnu; q__1.real() = ac, q__1.imag() = (float)0.; zeta1->real() = q__1.real(), zeta1->imag() = q__1.imag(); q__1.real() = *fnu, q__1.imag() = (float)0.; zeta2->real() = q__1.real(), zeta2->imag() = q__1.imag(); phi->real() = cone.real(), phi->imag() = cone.imag(); arg->real() = cone.real(), arg->imag() = cone.imag(); return 0; L15: q__2.real() = rfnu, q__2.imag() = (float)0.; q__1.real() = z__->real() * q__2.real() - z__->imag() * q__2.imag(), q__1.imag() = z__->real() * q__2.imag() + z__->imag() * q__2.real(); zb.real() = q__1.real(), zb.imag() = q__1.imag(); rfnu2 = rfnu * rfnu; /* ----------------------------------------------------------------------- */ /* COMPUTE IN THE FOURTH QUADRANT */ /* ----------------------------------------------------------------------- */ d__1 = (double)(*fnu); d__2 = (double)ex1; fn13 = pow_dd(&d__1, &d__2); fn23 = fn13 * fn13; r__1 = (float)1. / fn13; q__1.real() = r__1, q__1.imag() = (float)0.; rfn13.real() = q__1.real(), rfn13.imag() = q__1.imag(); q__2.real() = zb.real() * zb.real() - zb.imag() * zb.imag(), q__2.imag() = zb.real() * zb.imag() + zb.imag() * zb.real(); q__1.real() = cone.real() - q__2.real(), q__1.imag() = cone.imag() - q__2.imag(); w2.real() = q__1.real(), w2.imag() = q__1.imag(); aw2 = c_abs(&w2); if(aw2 > (float).25) { goto L130; } /* ----------------------------------------------------------------------- */ /* POWER SERIES FOR CABS(W2).LE.0.25E0 */ /* ----------------------------------------------------------------------- */ k = 1; p[0].real() = cone.real(), p[0].imag() = cone.imag(); q__1.real() = gama[0], q__1.imag() = (float)0.; suma.real() = q__1.real(), suma.imag() = q__1.imag(); ap[0] = (float)1.; if(aw2 < *tol) { goto L20; } for(k = 2; k <= 30; ++k) { i__1 = k - 1; i__2 = k - 2; q__1.real() = p[i__2].real() * w2.real() - p[i__2].imag() * w2.imag(), q__1.imag() = p[i__2].real() * w2.imag() + p[i__2].imag() * w2.real(); p[i__1].real() = q__1.real(), p[i__1].imag() = q__1.imag(); i__1 = k - 1; i__2 = k - 1; q__3.real() = gama[i__2], q__3.imag() = (float)0.; q__2.real() = p[i__1].real() * q__3.real() - p[i__1].imag() * q__3.imag(), q__2.imag() = p[i__1].real() * q__3.imag() + p[i__1].imag() * q__3.real(); q__1.real() = suma.real() + q__2.real(), q__1.imag() = suma.imag() + q__2.imag(); suma.real() = q__1.real(), suma.imag() = q__1.imag(); ap[k - 1] = ap[k - 2] * aw2; if(ap[k - 1] < *tol) { goto L20; } /* L10: */ } k = 30; L20: kmax = k; q__1.real() = w2.real() * suma.real() - w2.imag() * suma.imag(), q__1.imag() = w2.real() * suma.imag() + w2.imag() * suma.real(); zeta.real() = q__1.real(), zeta.imag() = q__1.imag(); q__2.real() = fn23, q__2.imag() = (float)0.; q__1.real() = zeta.real() * q__2.real() - zeta.imag() * q__2.imag(), q__1.imag() = zeta.real() * q__2.imag() + zeta.imag() * q__2.real(); arg->real() = q__1.real(), arg->imag() = q__1.imag(); c_sqrt(&q__1, &suma); za.real() = q__1.real(), za.imag() = q__1.imag(); c_sqrt(&q__2, &w2); q__3.real() = *fnu, q__3.imag() = (float)0.; q__1.real() = q__2.real() * q__3.real() - q__2.imag() * q__3.imag(), q__1.imag() = q__2.real() * q__3.imag() + q__2.imag() * q__3.real(); zeta2->real() = q__1.real(), zeta2->imag() = q__1.imag(); q__4.real() = zeta.real() * za.real() - zeta.imag() * za.imag(), q__4.imag() = zeta.real() * za.imag() + zeta.imag() * za.real(); q__5.real() = ex2, q__5.imag() = (float)0.; q__3.real() = q__4.real() * q__5.real() - q__4.imag() * q__5.imag(), q__3.imag() = q__4.real() * q__5.imag() + q__4.imag() * q__5.real(); q__2.real() = cone.real() + q__3.real(), q__2.imag() = cone.imag() + q__3.imag(); q__1.real() = zeta2->real() * q__2.real() - zeta2->imag() * q__2.imag(), q__1.imag() = zeta2->real() * q__2.imag() + zeta2->imag() * q__2.real(); zeta1->real() = q__1.real(), zeta1->imag() = q__1.imag(); q__1.real() = za.real() + za.real(), q__1.imag() = za.imag() + za.imag(); za.real() = q__1.real(), za.imag() = q__1.imag(); c_sqrt(&q__2, &za); q__1.real() = q__2.real() * rfn13.real() - q__2.imag() * rfn13.imag(), q__1.imag() = q__2.real() * rfn13.imag() + q__2.imag() * rfn13.real(); phi->real() = q__1.real(), phi->imag() = q__1.imag(); if(*ipmtr == 1) { goto L120; } /* ----------------------------------------------------------------------- */ /* SUM SERIES FOR ASUM AND BSUM */ /* ----------------------------------------------------------------------- */ sumb.real() = czero.real(), sumb.imag() = czero.imag(); i__1 = kmax; for(k = 1; k <= i__1; ++k) { i__2 = k - 1; i__3 = k - 1; q__3.real() = beta[i__3], q__3.imag() = (float)0.; q__2.real() = p[i__2].real() * q__3.real() - p[i__2].imag() * q__3.imag(), q__2.imag() = p[i__2].real() * q__3.imag() + p[i__2].imag() * q__3.real(); q__1.real() = sumb.real() + q__2.real(), q__1.imag() = sumb.imag() + q__2.imag(); sumb.real() = q__1.real(), sumb.imag() = q__1.imag(); /* L30: */ } asum->real() = czero.real(), asum->imag() = czero.imag(); bsum->real() = sumb.real(), bsum->imag() = sumb.imag(); l1 = 0; l2 = 30; btol = *tol * c_abs(bsum); atol = *tol; pp = (float)1.; ias = 0; ibs = 0; if(rfnu2 < *tol) { goto L110; } for(is = 2; is <= 7; ++is) { atol /= rfnu2; pp *= rfnu2; if(ias == 1) { goto L60; } suma.real() = czero.real(), suma.imag() = czero.imag(); i__1 = kmax; for(k = 1; k <= i__1; ++k) { m = l1 + k; i__2 = k - 1; i__3 = m - 1; q__3.real() = alfa[i__3], q__3.imag() = (float)0.; q__2.real() = p[i__2].real() * q__3.real() - p[i__2].imag() * q__3.imag(), q__2.imag() = p[i__2].real() * q__3.imag() + p[i__2].imag() * q__3.real(); q__1.real() = suma.real() + q__2.real(), q__1.imag() = suma.imag() + q__2.imag(); suma.real() = q__1.real(), suma.imag() = q__1.imag(); if(ap[k - 1] < atol) { goto L50; } /* L40: */ } L50: q__3.real() = pp, q__3.imag() = (float)0.; q__2.real() = suma.real() * q__3.real() - suma.imag() * q__3.imag(), q__2.imag() = suma.real() * q__3.imag() + suma.imag() * q__3.real(); q__1.real() = asum->real() + q__2.real(), q__1.imag() = asum->imag() + q__2.imag(); asum->real() = q__1.real(), asum->imag() = q__1.imag(); if(pp < *tol) { ias = 1; } L60: if(ibs == 1) { goto L90; } sumb.real() = czero.real(), sumb.imag() = czero.imag(); i__1 = kmax; for(k = 1; k <= i__1; ++k) { m = l2 + k; i__2 = k - 1; i__3 = m - 1; q__3.real() = beta[i__3], q__3.imag() = (float)0.; q__2.real() = p[i__2].real() * q__3.real() - p[i__2].imag() * q__3.imag(), q__2.imag() = p[i__2].real() * q__3.imag() + p[i__2].imag() * q__3.real(); q__1.real() = sumb.real() + q__2.real(), q__1.imag() = sumb.imag() + q__2.imag(); sumb.real() = q__1.real(), sumb.imag() = q__1.imag(); if(ap[k - 1] < atol) { goto L80; } /* L70: */ } L80: q__3.real() = pp, q__3.imag() = (float)0.; q__2.real() = sumb.real() * q__3.real() - sumb.imag() * q__3.imag(), q__2.imag() = sumb.real() * q__3.imag() + sumb.imag() * q__3.real(); q__1.real() = bsum->real() + q__2.real(), q__1.imag() = bsum->imag() + q__2.imag(); bsum->real() = q__1.real(), bsum->imag() = q__1.imag(); if(pp < btol) { ibs = 1; } L90: if(ias == 1 && ibs == 1) { goto L110; } l1 += 30; l2 += 30; /* L100: */ } L110: q__1.real() = asum->real() + cone.real(), q__1.imag() = asum->imag() + cone.imag(); asum->real() = q__1.real(), asum->imag() = q__1.imag(); pp = rfnu * rfn13.real(); q__2.real() = pp, q__2.imag() = (float)0.; q__1.real() = bsum->real() * q__2.real() - bsum->imag() * q__2.imag(), q__1.imag() = bsum->real() * q__2.imag() + bsum->imag() * q__2.real(); bsum->real() = q__1.real(), bsum->imag() = q__1.imag(); L120: return 0; /* ----------------------------------------------------------------------- */ /* CABS(W2).GT.0.25E0 */ /* ----------------------------------------------------------------------- */ L130: c_sqrt(&q__1, &w2); w.real() = q__1.real(), w.imag() = q__1.imag(); wr = w.real(); wi = r_imag(&w); if(wr < (float)0.) { wr = (float)0.; } if(wi < (float)0.) { wi = (float)0.; } q__1.real() = wr, q__1.imag() = wi; w.real() = q__1.real(), w.imag() = q__1.imag(); q__2.real() = cone.real() + w.real(), q__2.imag() = cone.imag() + w.imag(); c_div(&q__1, &q__2, &zb); za.real() = q__1.real(), za.imag() = q__1.imag(); c_log(&q__1, &za); zc.real() = q__1.real(), zc.imag() = q__1.imag(); zcr = zc.real(); zci = r_imag(&zc); if(zci < (float)0.) { zci = (float)0.; } if(zci > hpi) { zci = hpi; } if(zcr < (float)0.) { zcr = (float)0.; } q__1.real() = zcr, q__1.imag() = zci; zc.real() = q__1.real(), zc.imag() = q__1.imag(); q__2.real() = zc.real() - w.real(), q__2.imag() = zc.imag() - w.imag(); q__1.real() = q__2.real() * (float)1.5 - q__2.imag() * (float)0., q__1.imag() = q__2.real() * (float)0. + q__2.imag() * (float)1.5; zth.real() = q__1.real(), zth.imag() = q__1.imag(); q__1.real() = *fnu, q__1.imag() = (float)0.; cfnu.real() = q__1.real(), cfnu.imag() = q__1.imag(); q__1.real() = zc.real() * cfnu.real() - zc.imag() * cfnu.imag(), q__1.imag() = zc.real() * cfnu.imag() + zc.imag() * cfnu.real(); zeta1->real() = q__1.real(), zeta1->imag() = q__1.imag(); q__1.real() = w.real() * cfnu.real() - w.imag() * cfnu.imag(), q__1.imag() = w.real() * cfnu.imag() + w.imag() * cfnu.real(); zeta2->real() = q__1.real(), zeta2->imag() = q__1.imag(); azth = c_abs(&zth); zthr = zth.real(); zthi = r_imag(&zth); ang = thpi; if(zthr >= (float)0. && zthi < (float)0.) { goto L140; } ang = hpi; if(zthr == (float)0.) { goto L140; } ang = atan(zthi / zthr); if(zthr < (float)0.) { ang += pi; } L140: d__1 = (double)azth; d__2 = (double)ex2; pp = pow_dd(&d__1, &d__2); ang *= ex2; zetar = pp * cos(ang); zetai = pp * sin(ang); if(zetai < (float)0.) { zetai = (float)0.; } q__1.real() = zetar, q__1.imag() = zetai; zeta.real() = q__1.real(), zeta.imag() = q__1.imag(); q__2.real() = fn23, q__2.imag() = (float)0.; q__1.real() = zeta.real() * q__2.real() - zeta.imag() * q__2.imag(), q__1.imag() = zeta.real() * q__2.imag() + zeta.imag() * q__2.real(); arg->real() = q__1.real(), arg->imag() = q__1.imag(); c_div(&q__1, &zth, &zeta); rtzta.real() = q__1.real(), rtzta.imag() = q__1.imag(); c_div(&q__1, &rtzta, &w); za.real() = q__1.real(), za.imag() = q__1.imag(); q__3.real() = za.real() + za.real(), q__3.imag() = za.imag() + za.imag(); c_sqrt(&q__2, &q__3); q__1.real() = q__2.real() * rfn13.real() - q__2.imag() * rfn13.imag(), q__1.imag() = q__2.real() * rfn13.imag() + q__2.imag() * rfn13.real(); phi->real() = q__1.real(), phi->imag() = q__1.imag(); if(*ipmtr == 1) { goto L120; } q__2.real() = rfnu, q__2.imag() = (float)0.; c_div(&q__1, &q__2, &w); tfn.real() = q__1.real(), tfn.imag() = q__1.imag(); q__2.real() = rfnu, q__2.imag() = (float)0.; c_div(&q__1, &q__2, &zth); rzth.real() = q__1.real(), rzth.imag() = q__1.imag(); q__2.real() = ar[1], q__2.imag() = (float)0.; q__1.real() = rzth.real() * q__2.real() - rzth.imag() * q__2.imag(), q__1.imag() = rzth.real() * q__2.imag() + rzth.imag() * q__2.real(); zc.real() = q__1.real(), zc.imag() = q__1.imag(); c_div(&q__1, &cone, &w2); t2.real() = q__1.real(), t2.imag() = q__1.imag(); q__4.real() = c__[1], q__4.imag() = (float)0.; q__3.real() = t2.real() * q__4.real() - t2.imag() * q__4.imag(), q__3.imag() = t2.real() * q__4.imag() + t2.imag() * q__4.real(); q__5.real() = c__[2], q__5.imag() = (float)0.; q__2.real() = q__3.real() + q__5.real(), q__2.imag() = q__3.imag() + q__5.imag(); q__1.real() = q__2.real() * tfn.real() - q__2.imag() * tfn.imag(), q__1.imag() = q__2.real() * tfn.imag() + q__2.imag() * tfn.real(); up[1].real() = q__1.real(), up[1].imag() = q__1.imag(); q__1.real() = up[1].real() + zc.real(), q__1.imag() = up[1].imag() + zc.imag(); bsum->real() = q__1.real(), bsum->imag() = q__1.imag(); asum->real() = czero.real(), asum->imag() = czero.imag(); if(rfnu < *tol) { goto L220; } przth.real() = rzth.real(), przth.imag() = rzth.imag(); ptfn.real() = tfn.real(), ptfn.imag() = tfn.imag(); up[0].real() = cone.real(), up[0].imag() = cone.imag(); pp = (float)1.; bsumr = bsum->real(); bsumi = r_imag(bsum); btol = *tol * (abs(bsumr) + abs(bsumi)); ks = 0; kp1 = 2; l = 3; ias = 0; ibs = 0; for(lr = 2; lr <= 12; lr += 2) { lrp1 = lr + 1; /* ----------------------------------------------------------------------- */ /* COMPUTE TWO ADDITIONAL CR, DR, AND UP FOR TWO MORE TERMS IN */ /* NEXT SUMA AND SUMB */ /* ----------------------------------------------------------------------- */ i__1 = lrp1; for(k = lr; k <= i__1; ++k) { ++ks; ++kp1; ++l; i__2 = l - 1; q__1.real() = c__[i__2], q__1.imag() = (float)0.; za.real() = q__1.real(), za.imag() = q__1.imag(); i__2 = kp1; for(j = 2; j <= i__2; ++j) { ++l; q__2.real() = za.real() * t2.real() - za.imag() * t2.imag(), q__2.imag() = za.real() * t2.imag() + za.imag() * t2.real(); i__3 = l - 1; q__3.real() = c__[i__3], q__3.imag() = (float)0.; q__1.real() = q__2.real() + q__3.real(), q__1.imag() = q__2.imag() + q__3.imag(); za.real() = q__1.real(), za.imag() = q__1.imag(); /* L150: */ } q__1.real() = ptfn.real() * tfn.real() - ptfn.imag() * tfn.imag(), q__1.imag() = ptfn.real() * tfn.imag() + ptfn.imag() * tfn.real(); ptfn.real() = q__1.real(), ptfn.imag() = q__1.imag(); i__2 = kp1 - 1; q__1.real() = ptfn.real() * za.real() - ptfn.imag() * za.imag(), q__1.imag() = ptfn.real() * za.imag() + ptfn.imag() * za.real(); up[i__2].real() = q__1.real(), up[i__2].imag() = q__1.imag(); i__2 = ks - 1; i__3 = ks; q__2.real() = br[i__3], q__2.imag() = (float)0.; q__1.real() = przth.real() * q__2.real() - przth.imag() * q__2.imag(), q__1.imag() = przth.real() * q__2.imag() + przth.imag() * q__2.real(); cr[i__2].real() = q__1.real(), cr[i__2].imag() = q__1.imag(); q__1.real() = przth.real() * rzth.real() - przth.imag() * rzth.imag(), q__1.imag() = przth.real() * rzth.imag() + przth.imag() * rzth.real(); przth.real() = q__1.real(), przth.imag() = q__1.imag(); i__2 = ks - 1; i__3 = ks + 1; q__2.real() = ar[i__3], q__2.imag() = (float)0.; q__1.real() = przth.real() * q__2.real() - przth.imag() * q__2.imag(), q__1.imag() = przth.real() * q__2.imag() + przth.imag() * q__2.real(); dr[i__2].real() = q__1.real(), dr[i__2].imag() = q__1.imag(); /* L160: */ } pp *= rfnu2; if(ias == 1) { goto L180; } i__1 = lrp1 - 1; suma.real() = up[i__1].real(), suma.imag() = up[i__1].imag(); ju = lrp1; i__1 = lr; for(jr = 1; jr <= i__1; ++jr) { --ju; i__2 = jr - 1; i__3 = ju - 1; q__2.real() = cr[i__2].real() * up[i__3].real() - cr[i__2].imag() * up[i__3].imag(), q__2.imag() = cr[i__2].real() * up[i__3].imag() + cr[i__2].imag() * up[i__3].real(); q__1.real() = suma.real() + q__2.real(), q__1.imag() = suma.imag() + q__2.imag(); suma.real() = q__1.real(), suma.imag() = q__1.imag(); /* L170: */ } q__1.real() = asum->real() + suma.real(), q__1.imag() = asum->imag() + suma.imag(); asum->real() = q__1.real(), asum->imag() = q__1.imag(); asumr = asum->real(); asumi = r_imag(asum); test = abs(asumr) + abs(asumi); if(pp < *tol && test < *tol) { ias = 1; } L180: if(ibs == 1) { goto L200; } i__1 = lr + 1; i__2 = lrp1 - 1; q__2.real() = up[i__2].real() * zc.real() - up[i__2].imag() * zc.imag(), q__2.imag() = up[i__2].real() * zc.imag() + up[i__2].imag() * zc.real(); q__1.real() = up[i__1].real() + q__2.real(), q__1.imag() = up[i__1].imag() + q__2.imag(); sumb.real() = q__1.real(), sumb.imag() = q__1.imag(); ju = lrp1; i__1 = lr; for(jr = 1; jr <= i__1; ++jr) { --ju; i__2 = jr - 1; i__3 = ju - 1; q__2.real() = dr[i__2].real() * up[i__3].real() - dr[i__2].imag() * up[i__3].imag(), q__2.imag() = dr[i__2].real() * up[i__3].imag() + dr[i__2].imag() * up[i__3].real(); q__1.real() = sumb.real() + q__2.real(), q__1.imag() = sumb.imag() + q__2.imag(); sumb.real() = q__1.real(), sumb.imag() = q__1.imag(); /* L190: */ } q__1.real() = bsum->real() + sumb.real(), q__1.imag() = bsum->imag() + sumb.imag(); bsum->real() = q__1.real(), bsum->imag() = q__1.imag(); bsumr = bsum->real(); bsumi = r_imag(bsum); test = abs(bsumr) + abs(bsumi); if(pp < btol && test < *tol) { ibs = 1; } L200: if(ias == 1 && ibs == 1) { goto L220; } /* L210: */ } L220: q__1.real() = asum->real() + cone.real(), q__1.imag() = asum->imag() + cone.imag(); asum->real() = q__1.real(), asum->imag() = q__1.imag(); q__3.real() = -bsum->real(), q__3.imag() = -bsum->imag(); q__2.real() = q__3.real() * rfn13.real() - q__3.imag() * rfn13.imag(), q__2.imag() = q__3.real() * rfn13.imag() + q__3.imag() * rfn13.real(); c_div(&q__1, &q__2, &rtzta); bsum->real() = q__1.real(), bsum->imag() = q__1.imag(); goto L120; } /* cunhj_ */ int cuni1_(System::Complex<float>* z__, float* fnu, int32* kode, int32* n, System::Complex<float>* y, int32* nz, int32* nlast, float* fnul, float* tol, float* elim, float* alim) { /* Initialized data */ static System::Complex<float> czero = {(float)0., (float)0.}; static System::Complex<float> cone = {(float)1., (float)0.}; /* System generated locals */ int32 i__1, i__2, i__3; float r__1, r__2; System::Complex<float> q__1, q__2, q__3, q__4, q__5, q__6, q__7; int32 i__, k, m; System::Complex<float> c1, c2, s1, s2; int32 nd; float fn; System::Complex<float> cy[2]; int32 nn, nw; System::Complex<float> rz; float yy, c2i, c2m, c2r, rs1; System::Complex<float> cfn, phi, csr[3], css[3]; int32 nuf; float bry[3]; System::Complex<float> sum; float aphi; System::Complex<float> cscl, crsc; int32 init; System::Complex<float> cwrk[16], zeta1, zeta2; int32 iflag; float ascle; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE CUNI1 */ /* ***REFER TO CBESI,CBESK */ /* CUNI1 COMPUTES I(FNU,Z) BY MEANS OF THE UNIFORM ASYMPTOTIC */ /* EXPANSION FOR I(FNU,Z) IN -PI/3.LE.ARG Z.LE.PI/3. */ /* FNUL IS THE SMALLEST ORDER PERMITTED FOR THE ASYMPTOTIC */ /* EXPANSION. NLAST=0 MEANS ALL OF THE Y VALUES WERE SET. */ /* NLAST.NE.0 IS THE NUMBER LEFT TO BE COMPUTED BY ANOTHER */ /* FORMULA FOR ORDERS FNU TO FNU+NLAST-1 BECAUSE FNU+NLAST-1.LT.FNUL. */ /* Y(I)=CZERO FOR I=NLAST+1,N */ /* ***ROUTINES CALLED CUCHK,CUNIK,CUOIK,R1MACH */ /* ***END PROLOGUE CUNI1 */ /* Parameter adjustments */ --y; /* Function Body */ *nz = 0; nd = *n; *nlast = 0; /* ----------------------------------------------------------------------- */ /* COMPUTED VALUES WITH EXPONENTS BETWEEN ALIM AND ELIM IN MAG- */ /* NITUDE ARE SCALED TO KEEP INTERMEDIATE ARITHMETIC ON SCALE, */ /* EXP(ALIM)=EXP(ELIM)*TOL */ /* ----------------------------------------------------------------------- */ r__1 = (float)1. / *tol; q__1.real() = r__1, q__1.imag() = (float)0.; cscl.real() = q__1.real(), cscl.imag() = q__1.imag(); q__1.real() = *tol, q__1.imag() = (float)0.; crsc.real() = q__1.real(), crsc.imag() = q__1.imag(); css[0].real() = cscl.real(), css[0].imag() = cscl.imag(); css[1].real() = cone.real(), css[1].imag() = cone.imag(); css[2].real() = crsc.real(), css[2].imag() = crsc.imag(); csr[0].real() = crsc.real(), csr[0].imag() = crsc.imag(); csr[1].real() = cone.real(), csr[1].imag() = cone.imag(); csr[2].real() = cscl.real(), csr[2].imag() = cscl.imag(); bry[0] = r1mach_(&c__1) * (float)1e3 / *tol; /* ----------------------------------------------------------------------- */ /* CHECK FOR UNDERFLOW AND OVERFLOW ON FIRST MEMBER */ /* ----------------------------------------------------------------------- */ fn = max(*fnu, (float)1.); init = 0; cunik_(z__, &fn, &c__1, &c__1, tol, &init, &phi, &zeta1, &zeta2, &sum, cwrk); if(*kode == 1) { goto L10; } q__1.real() = fn, q__1.imag() = (float)0.; cfn.real() = q__1.real(), cfn.imag() = q__1.imag(); q__2.real() = -zeta1.real(), q__2.imag() = -zeta1.imag(); q__5.real() = z__->real() + zeta2.real(), q__5.imag() = z__->imag() + zeta2.imag(); c_div(&q__4, &cfn, &q__5); q__3.real() = cfn.real() * q__4.real() - cfn.imag() * q__4.imag(), q__3.imag() = cfn.real() * q__4.imag() + cfn.imag() * q__4.real(); q__1.real() = q__2.real() + q__3.real(), q__1.imag() = q__2.imag() + q__3.imag(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); goto L20; L10: q__2.real() = -zeta1.real(), q__2.imag() = -zeta1.imag(); q__1.real() = q__2.real() + zeta2.real(), q__1.imag() = q__2.imag() + zeta2.imag(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); L20: rs1 = s1.real(); if(abs(rs1) > *elim) { goto L130; } L30: nn = std::min(2L, nd); i__1 = nn; for(i__ = 1; i__ <= i__1; ++i__) { fn = *fnu + (float)(nd - i__); init = 0; cunik_(z__, &fn, &c__1, &c__0, tol, &init, &phi, &zeta1, &zeta2, &sum, cwrk); if(*kode == 1) { goto L40; } q__1.real() = fn, q__1.imag() = (float)0.; cfn.real() = q__1.real(), cfn.imag() = q__1.imag(); yy = r_imag(z__); q__3.real() = -zeta1.real(), q__3.imag() = -zeta1.imag(); q__6.real() = z__->real() + zeta2.real(), q__6.imag() = z__->imag() + zeta2.imag(); c_div(&q__5, &cfn, &q__6); q__4.real() = cfn.real() * q__5.real() - cfn.imag() * q__5.imag(), q__4.imag() = cfn.real() * q__5.imag() + cfn.imag() * q__5.real(); q__2.real() = q__3.real() + q__4.real(), q__2.imag() = q__3.imag() + q__4.imag(); q__7.real() = (float)0., q__7.imag() = yy; q__1.real() = q__2.real() + q__7.real(), q__1.imag() = q__2.imag() + q__7.imag(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); goto L50; L40: q__2.real() = -zeta1.real(), q__2.imag() = -zeta1.imag(); q__1.real() = q__2.real() + zeta2.real(), q__1.imag() = q__2.imag() + zeta2.imag(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); L50: /* ----------------------------------------------------------------------- */ /* TEST FOR UNDERFLOW AND OVERFLOW */ /* ----------------------------------------------------------------------- */ rs1 = s1.real(); if(abs(rs1) > *elim) { goto L110; } if(i__ == 1) { iflag = 2; } if(abs(rs1) < *alim) { goto L60; } /* ----------------------------------------------------------------------- */ /* REFINE TEST AND SCALE */ /* ----------------------------------------------------------------------- */ aphi = c_abs(&phi); rs1 += log(aphi); if(abs(rs1) > *elim) { goto L110; } if(i__ == 1) { iflag = 1; } if(rs1 < (float)0.) { goto L60; } if(i__ == 1) { iflag = 3; } L60: /* ----------------------------------------------------------------------- */ /* SCALE S1 IF CABS(S1).LT.ASCLE */ /* ----------------------------------------------------------------------- */ q__1.real() = phi.real() * sum.real() - phi.imag() * sum.imag(), q__1.imag() = phi.real() * sum.imag() + phi.imag() * sum.real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); c2r = s1.real(); c2i = r_imag(&s1); i__2 = iflag - 1; c2m = exp(c2r) * css[i__2].real(); q__2.real() = c2m, q__2.imag() = (float)0.; r__1 = cos(c2i); r__2 = sin(c2i); q__3.real() = r__1, q__3.imag() = r__2; q__1.real() = q__2.real() * q__3.real() - q__2.imag() * q__3.imag(), q__1.imag() = q__2.real() * q__3.imag() + q__2.imag() * q__3.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); q__1.real() = s2.real() * s1.real() - s2.imag() * s1.imag(), q__1.imag() = s2.real() * s1.imag() + s2.imag() * s1.real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); if(iflag != 1) { goto L70; } cuchk_(&s2, &nw, bry, tol); if(nw != 0) { goto L110; } L70: m = nd - i__ + 1; i__2 = i__ - 1; cy[i__2].real() = s2.real(), cy[i__2].imag() = s2.imag(); i__2 = m; i__3 = iflag - 1; q__1.real() = s2.real() * csr[i__3].real() - s2.imag() * csr[i__3].imag(), q__1.imag() = s2.real() * csr[i__3].imag() + s2.imag() * csr[i__3].real(); y[i__2].real() = q__1.real(), y[i__2].imag() = q__1.imag(); /* L80: */ } if(nd <= 2) { goto L100; } c_div(&q__1, &c_b17, z__); rz.real() = q__1.real(), rz.imag() = q__1.imag(); bry[1] = (float)1. / bry[0]; bry[2] = r1mach_(&c__2); s1.real() = cy[0].real(), s1.imag() = cy[0].imag(); s2.real() = cy[1].real(), s2.imag() = cy[1].imag(); i__1 = iflag - 1; c1.real() = csr[i__1].real(), c1.imag() = csr[i__1].imag(); ascle = bry[iflag - 1]; k = nd - 2; fn = (float)k; i__1 = nd; for(i__ = 3; i__ <= i__1; ++i__) { c2.real() = s2.real(), c2.imag() = s2.imag(); r__1 = *fnu + fn; q__4.real() = r__1, q__4.imag() = (float)0.; q__3.real() = q__4.real() * rz.real() - q__4.imag() * rz.imag(), q__3.imag() = q__4.real() * rz.imag() + q__4.imag() * rz.real(); q__2.real() = q__3.real() * s2.real() - q__3.imag() * s2.imag(), q__2.imag() = q__3.real() * s2.imag() + q__3.imag() * s2.real(); q__1.real() = s1.real() + q__2.real(), q__1.imag() = s1.imag() + q__2.imag(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); s1.real() = c2.real(), s1.imag() = c2.imag(); q__1.real() = s2.real() * c1.real() - s2.imag() * c1.imag(), q__1.imag() = s2.real() * c1.imag() + s2.imag() * c1.real(); c2.real() = q__1.real(), c2.imag() = q__1.imag(); i__2 = k; y[i__2].real() = c2.real(), y[i__2].imag() = c2.imag(); --k; fn += (float)-1.; if(iflag >= 3) { goto L90; } c2r = c2.real(); c2i = r_imag(&c2); c2r = abs(c2r); c2i = abs(c2i); c2m = max(c2r, c2i); if(c2m <= ascle) { goto L90; } ++iflag; ascle = bry[iflag - 1]; q__1.real() = s1.real() * c1.real() - s1.imag() * c1.imag(), q__1.imag() = s1.real() * c1.imag() + s1.imag() * c1.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); s2.real() = c2.real(), s2.imag() = c2.imag(); i__2 = iflag - 1; q__1.real() = s1.real() * css[i__2].real() - s1.imag() * css[i__2].imag(), q__1.imag() = s1.real() * css[i__2].imag() + s1.imag() * css[i__2].real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); i__2 = iflag - 1; q__1.real() = s2.real() * css[i__2].real() - s2.imag() * css[i__2].imag(), q__1.imag() = s2.real() * css[i__2].imag() + s2.imag() * css[i__2].real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); i__2 = iflag - 1; c1.real() = csr[i__2].real(), c1.imag() = csr[i__2].imag(); L90:; } L100: return 0; /* ----------------------------------------------------------------------- */ /* SET UNDERFLOW AND UPDATE PARAMETERS */ /* ----------------------------------------------------------------------- */ L110: if(rs1 > (float)0.) { goto L120; } i__1 = nd; y[i__1].real() = czero.real(), y[i__1].imag() = czero.imag(); ++(*nz); --nd; if(nd == 0) { goto L100; } cuoik_(z__, fnu, kode, &c__1, &nd, &y[1], &nuf, tol, elim, alim); if(nuf < 0) { goto L120; } nd -= nuf; *nz += nuf; if(nd == 0) { goto L100; } fn = *fnu + (float)(nd - 1); if(fn >= *fnul) { goto L30; } *nlast = nd; return 0; L120: *nz = -1; return 0; L130: if(rs1 > (float)0.) { goto L120; } *nz = *n; i__1 = *n; for(i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; y[i__2].real() = czero.real(), y[i__2].imag() = czero.imag(); /* L140: */ } return 0; } /* cuni1_ */ int cuni2_(System::Complex<float>* z__, float* fnu, int32* kode, int32* n, System::Complex<float>* y, int32* nz, int32* nlast, float* fnul, float* tol, float* elim, float* alim) { /* Initialized data */ static System::Complex<float> czero = {(float)0., (float)0.}; static System::Complex<float> cone = {(float)1., (float)0.}; static System::Complex<float> ci = {(float)0., (float)1.}; static System::Complex<float> cip[4] = {{(float)1., (float)0.}, {(float)0., (float)1.}, {(float)-1., (float)0.}, {(float)0., (float)-1.}}; static float hpi = (float)1.57079632679489662; static float aic = (float)1.265512123484645396; /* System generated locals */ int32 i__1, i__2, i__3; float r__1, r__2; System::Complex<float> q__1, q__2, q__3, q__4, q__5, q__6, q__7; int32 i__, j, k; System::Complex<float> c1, c2, s1, s2, ai; int32 nd; float fn; int32 in; float ay; System::Complex<float> cy[2], zb; int32 nn, nw; System::Complex<float> zn, rz; float yy, c2i, c2m, c2r, rs1; System::Complex<float> dai, cid; float ang; System::Complex<float> cfn; float car; int32 nai; System::Complex<float> arg, phi; float sar; System::Complex<float> csr[3], css[3]; int32 nuf, inu; System::Complex<float> zar; float bry[3], aarg; int32 ndai; float aphi; System::Complex<float> cscl, crsc; int32 idum; System::Complex<float> asum, bsum, zeta1, zeta2; int32 iflag; float ascle; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE CUNI2 */ /* ***REFER TO CBESI,CBESK */ /* CUNI2 COMPUTES I(FNU,Z) IN THE RIGHT HALF PLANE BY MEANS OF */ /* UNIFORM ASYMPTOTIC EXPANSION FOR J(FNU,ZN) WHERE ZN IS Z*I */ /* OR -Z*I AND ZN IS IN THE RIGHT HALF PLANE ALSO. */ /* FNUL IS THE SMALLEST ORDER PERMITTED FOR THE ASYMPTOTIC */ /* EXPANSION. NLAST=0 MEANS ALL OF THE Y VALUES WERE SET. */ /* NLAST.NE.0 IS THE NUMBER LEFT TO BE COMPUTED BY ANOTHER */ /* FORMULA FOR ORDERS FNU TO FNU+NLAST-1 BECAUSE FNU+NLAST-1.LT.FNUL. */ /* Y(I)=CZERO FOR I=NLAST+1,N */ /* ***ROUTINES CALLED CAIRY,CUCHK,CUNHJ,CUOIK,R1MACH */ /* ***END PROLOGUE CUNI2 */ /* Parameter adjustments */ --y; /* Function Body */ *nz = 0; nd = *n; *nlast = 0; /* ----------------------------------------------------------------------- */ /* COMPUTED VALUES WITH EXPONENTS BETWEEN ALIM AND ELIM IN MAG- */ /* NITUDE ARE SCALED TO KEEP INTERMEDIATE ARITHMETIC ON SCALE, */ /* EXP(ALIM)=EXP(ELIM)*TOL */ /* ----------------------------------------------------------------------- */ r__1 = (float)1. / *tol; q__1.real() = r__1, q__1.imag() = (float)0.; cscl.real() = q__1.real(), cscl.imag() = q__1.imag(); q__1.real() = *tol, q__1.imag() = (float)0.; crsc.real() = q__1.real(), crsc.imag() = q__1.imag(); css[0].real() = cscl.real(), css[0].imag() = cscl.imag(); css[1].real() = cone.real(), css[1].imag() = cone.imag(); css[2].real() = crsc.real(), css[2].imag() = crsc.imag(); csr[0].real() = crsc.real(), csr[0].imag() = crsc.imag(); csr[1].real() = cone.real(), csr[1].imag() = cone.imag(); csr[2].real() = cscl.real(), csr[2].imag() = cscl.imag(); bry[0] = r1mach_(&c__1) * (float)1e3 / *tol; yy = r_imag(z__); /* ----------------------------------------------------------------------- */ /* ZN IS IN THE RIGHT HALF PLANE AFTER ROTATION BY CI OR -CI */ /* ----------------------------------------------------------------------- */ q__2.real() = -z__->real(), q__2.imag() = -z__->imag(); q__1.real() = q__2.real() * ci.real() - q__2.imag() * ci.imag(), q__1.imag() = q__2.real() * ci.imag() + q__2.imag() * ci.real(); zn.real() = q__1.real(), zn.imag() = q__1.imag(); zb.real() = z__->real(), zb.imag() = z__->imag(); q__1.real() = -ci.real(), q__1.imag() = -ci.imag(); cid.real() = q__1.real(), cid.imag() = q__1.imag(); inu = (int32)(*fnu); ang = hpi * (*fnu - (float)inu); car = cos(ang); sar = sin(ang); q__1.real() = car, q__1.imag() = sar; c2.real() = q__1.real(), c2.imag() = q__1.imag(); zar.real() = c2.real(), zar.imag() = c2.imag(); in = inu + *n - 1; in %= 4; i__1 = in; q__1.real() = c2.real() * cip[i__1].real() - c2.imag() * cip[i__1].imag(), q__1.imag() = c2.real() * cip[i__1].imag() + c2.imag() * cip[i__1].real(); c2.real() = q__1.real(), c2.imag() = q__1.imag(); if(yy > (float)0.) { goto L10; } q__2.real() = -zn.real(), q__2.imag() = -zn.imag(); r_cnjg(&q__1, &q__2); zn.real() = q__1.real(), zn.imag() = q__1.imag(); r_cnjg(&q__1, &zb); zb.real() = q__1.real(), zb.imag() = q__1.imag(); q__1.real() = -cid.real(), q__1.imag() = -cid.imag(); cid.real() = q__1.real(), cid.imag() = q__1.imag(); r_cnjg(&q__1, &c2); c2.real() = q__1.real(), c2.imag() = q__1.imag(); L10: /* ----------------------------------------------------------------------- */ /* CHECK FOR UNDERFLOW AND OVERFLOW ON FIRST MEMBER */ /* ----------------------------------------------------------------------- */ fn = max(*fnu, (float)1.); cunhj_(&zn, &fn, &c__1, tol, &phi, &arg, &zeta1, &zeta2, &asum, &bsum); if(*kode == 1) { goto L20; } q__1.real() = *fnu, q__1.imag() = (float)0.; cfn.real() = q__1.real(), cfn.imag() = q__1.imag(); q__2.real() = -zeta1.real(), q__2.imag() = -zeta1.imag(); q__5.real() = zb.real() + zeta2.real(), q__5.imag() = zb.imag() + zeta2.imag(); c_div(&q__4, &cfn, &q__5); q__3.real() = cfn.real() * q__4.real() - cfn.imag() * q__4.imag(), q__3.imag() = cfn.real() * q__4.imag() + cfn.imag() * q__4.real(); q__1.real() = q__2.real() + q__3.real(), q__1.imag() = q__2.imag() + q__3.imag(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); goto L30; L20: q__2.real() = -zeta1.real(), q__2.imag() = -zeta1.imag(); q__1.real() = q__2.real() + zeta2.real(), q__1.imag() = q__2.imag() + zeta2.imag(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); L30: rs1 = s1.real(); if(abs(rs1) > *elim) { goto L150; } L40: nn = std::min(2L, nd); i__1 = nn; for(i__ = 1; i__ <= i__1; ++i__) { fn = *fnu + (float)(nd - i__); cunhj_(&zn, &fn, &c__0, tol, &phi, &arg, &zeta1, &zeta2, &asum, &bsum); if(*kode == 1) { goto L50; } q__1.real() = fn, q__1.imag() = (float)0.; cfn.real() = q__1.real(), cfn.imag() = q__1.imag(); ay = abs(yy); q__3.real() = -zeta1.real(), q__3.imag() = -zeta1.imag(); q__6.real() = zb.real() + zeta2.real(), q__6.imag() = zb.imag() + zeta2.imag(); c_div(&q__5, &cfn, &q__6); q__4.real() = cfn.real() * q__5.real() - cfn.imag() * q__5.imag(), q__4.imag() = cfn.real() * q__5.imag() + cfn.imag() * q__5.real(); q__2.real() = q__3.real() + q__4.real(), q__2.imag() = q__3.imag() + q__4.imag(); q__7.real() = (float)0., q__7.imag() = ay; q__1.real() = q__2.real() + q__7.real(), q__1.imag() = q__2.imag() + q__7.imag(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); goto L60; L50: q__2.real() = -zeta1.real(), q__2.imag() = -zeta1.imag(); q__1.real() = q__2.real() + zeta2.real(), q__1.imag() = q__2.imag() + zeta2.imag(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); L60: /* ----------------------------------------------------------------------- */ /* TEST FOR UNDERFLOW AND OVERFLOW */ /* ----------------------------------------------------------------------- */ rs1 = s1.real(); if(abs(rs1) > *elim) { goto L120; } if(i__ == 1) { iflag = 2; } if(abs(rs1) < *alim) { goto L70; } /* ----------------------------------------------------------------------- */ /* REFINE TEST AND SCALE */ /* ----------------------------------------------------------------------- */ /* ----------------------------------------------------------------------- */ aphi = c_abs(&phi); aarg = c_abs(&arg); rs1 = rs1 + log(aphi) - log(aarg) * (float).25 - aic; if(abs(rs1) > *elim) { goto L120; } if(i__ == 1) { iflag = 1; } if(rs1 < (float)0.) { goto L70; } if(i__ == 1) { iflag = 3; } L70: /* ----------------------------------------------------------------------- */ /* SCALE S1 TO KEEP INTERMEDIATE ARITHMETIC ON SCALE NEAR */ /* EXPONENT EXTREMES */ /* ----------------------------------------------------------------------- */ cairy_(&arg, &c__0, &c__2, &ai, &nai, &idum); cairy_(&arg, &c__1, &c__2, &dai, &ndai, &idum); q__3.real() = ai.real() * asum.real() - ai.imag() * asum.imag(), q__3.imag() = ai.real() * asum.imag() + ai.imag() * asum.real(); q__4.real() = dai.real() * bsum.real() - dai.imag() * bsum.imag(), q__4.imag() = dai.real() * bsum.imag() + dai.imag() * bsum.real(); q__2.real() = q__3.real() + q__4.real(), q__2.imag() = q__3.imag() + q__4.imag(); q__1.real() = phi.real() * q__2.real() - phi.imag() * q__2.imag(), q__1.imag() = phi.real() * q__2.imag() + phi.imag() * q__2.real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); c2r = s1.real(); c2i = r_imag(&s1); i__2 = iflag - 1; c2m = exp(c2r) * css[i__2].real(); q__2.real() = c2m, q__2.imag() = (float)0.; r__1 = cos(c2i); r__2 = sin(c2i); q__3.real() = r__1, q__3.imag() = r__2; q__1.real() = q__2.real() * q__3.real() - q__2.imag() * q__3.imag(), q__1.imag() = q__2.real() * q__3.imag() + q__2.imag() * q__3.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); q__1.real() = s2.real() * s1.real() - s2.imag() * s1.imag(), q__1.imag() = s2.real() * s1.imag() + s2.imag() * s1.real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); if(iflag != 1) { goto L80; } cuchk_(&s2, &nw, bry, tol); if(nw != 0) { goto L120; } L80: if(yy <= (float)0.) { r_cnjg(&q__1, &s2); s2.real() = q__1.real(), s2.imag() = q__1.imag(); } j = nd - i__ + 1; q__1.real() = s2.real() * c2.real() - s2.imag() * c2.imag(), q__1.imag() = s2.real() * c2.imag() + s2.imag() * c2.real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); i__2 = i__ - 1; cy[i__2].real() = s2.real(), cy[i__2].imag() = s2.imag(); i__2 = j; i__3 = iflag - 1; q__1.real() = s2.real() * csr[i__3].real() - s2.imag() * csr[i__3].imag(), q__1.imag() = s2.real() * csr[i__3].imag() + s2.imag() * csr[i__3].real(); y[i__2].real() = q__1.real(), y[i__2].imag() = q__1.imag(); q__1.real() = c2.real() * cid.real() - c2.imag() * cid.imag(), q__1.imag() = c2.real() * cid.imag() + c2.imag() * cid.real(); c2.real() = q__1.real(), c2.imag() = q__1.imag(); /* L90: */ } if(nd <= 2) { goto L110; } c_div(&q__1, &c_b17, z__); rz.real() = q__1.real(), rz.imag() = q__1.imag(); bry[1] = (float)1. / bry[0]; bry[2] = r1mach_(&c__2); s1.real() = cy[0].real(), s1.imag() = cy[0].imag(); s2.real() = cy[1].real(), s2.imag() = cy[1].imag(); i__1 = iflag - 1; c1.real() = csr[i__1].real(), c1.imag() = csr[i__1].imag(); ascle = bry[iflag - 1]; k = nd - 2; fn = (float)k; i__1 = nd; for(i__ = 3; i__ <= i__1; ++i__) { c2.real() = s2.real(), c2.imag() = s2.imag(); r__1 = *fnu + fn; q__4.real() = r__1, q__4.imag() = (float)0.; q__3.real() = q__4.real() * rz.real() - q__4.imag() * rz.imag(), q__3.imag() = q__4.real() * rz.imag() + q__4.imag() * rz.real(); q__2.real() = q__3.real() * s2.real() - q__3.imag() * s2.imag(), q__2.imag() = q__3.real() * s2.imag() + q__3.imag() * s2.real(); q__1.real() = s1.real() + q__2.real(), q__1.imag() = s1.imag() + q__2.imag(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); s1.real() = c2.real(), s1.imag() = c2.imag(); q__1.real() = s2.real() * c1.real() - s2.imag() * c1.imag(), q__1.imag() = s2.real() * c1.imag() + s2.imag() * c1.real(); c2.real() = q__1.real(), c2.imag() = q__1.imag(); i__2 = k; y[i__2].real() = c2.real(), y[i__2].imag() = c2.imag(); --k; fn += (float)-1.; if(iflag >= 3) { goto L100; } c2r = c2.real(); c2i = r_imag(&c2); c2r = abs(c2r); c2i = abs(c2i); c2m = max(c2r, c2i); if(c2m <= ascle) { goto L100; } ++iflag; ascle = bry[iflag - 1]; q__1.real() = s1.real() * c1.real() - s1.imag() * c1.imag(), q__1.imag() = s1.real() * c1.imag() + s1.imag() * c1.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); s2.real() = c2.real(), s2.imag() = c2.imag(); i__2 = iflag - 1; q__1.real() = s1.real() * css[i__2].real() - s1.imag() * css[i__2].imag(), q__1.imag() = s1.real() * css[i__2].imag() + s1.imag() * css[i__2].real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); i__2 = iflag - 1; q__1.real() = s2.real() * css[i__2].real() - s2.imag() * css[i__2].imag(), q__1.imag() = s2.real() * css[i__2].imag() + s2.imag() * css[i__2].real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); i__2 = iflag - 1; c1.real() = csr[i__2].real(), c1.imag() = csr[i__2].imag(); L100:; } L110: return 0; L120: if(rs1 > (float)0.) { goto L140; } /* ----------------------------------------------------------------------- */ /* SET UNDERFLOW AND UPDATE PARAMETERS */ /* ----------------------------------------------------------------------- */ i__1 = nd; y[i__1].real() = czero.real(), y[i__1].imag() = czero.imag(); ++(*nz); --nd; if(nd == 0) { goto L110; } cuoik_(z__, fnu, kode, &c__1, &nd, &y[1], &nuf, tol, elim, alim); if(nuf < 0) { goto L140; } nd -= nuf; *nz += nuf; if(nd == 0) { goto L110; } fn = *fnu + (float)(nd - 1); if(fn < *fnul) { goto L130; } /* FN = AIMAG(CID) */ /* J = NUF + 1 */ /* K = MOD(J,4) + 1 */ /* S1 = CIP(K) */ /* IF (FN.LT.0.0E0) S1 = CONJG(S1) */ /* C2 = C2*S1 */ in = inu + nd - 1; in = in % 4 + 1; i__1 = in - 1; q__1.real() = zar.real() * cip[i__1].real() - zar.imag() * cip[i__1].imag(), q__1.imag() = zar.real() * cip[i__1].imag() + zar.imag() * cip[i__1].real(); c2.real() = q__1.real(), c2.imag() = q__1.imag(); if(yy <= (float)0.) { r_cnjg(&q__1, &c2); c2.real() = q__1.real(), c2.imag() = q__1.imag(); } goto L40; L130: *nlast = nd; return 0; L140: *nz = -1; return 0; L150: if(rs1 > (float)0.) { goto L140; } *nz = *n; i__1 = *n; for(i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; y[i__2].real() = czero.real(), y[i__2].imag() = czero.imag(); /* L160: */ } return 0; } /* cuni2_ */ int cunik_(System::Complex<float>* zr, float* fnu, int32* ikflg, int32* ipmtr, float* tol, int32* init, System::Complex<float>* phi, System::Complex<float>* zeta1, System::Complex<float>* zeta2, System::Complex<float>* sum, System::Complex<float>* cwrk) { /* Initialized data */ static System::Complex<float> czero = {(float)0., (float)0.}; static System::Complex<float> cone = {(float)1., (float)0.}; static System::Complex<float> con[2] = {{(float).398942280401432678, (float)0.}, {(float)1.25331413731550025, (float)0.}}; static float c__[120] = {(float)1., (float)-.208333333333333333, (float).125, (float).334201388888888889, (float)-.401041666666666667, (float).0703125, (float)-1.02581259645061728, (float)1.84646267361111111, (float)-.8912109375, (float).0732421875, (float)4.66958442342624743, (float)-11.2070026162229938, (float)8.78912353515625, (float)-2.3640869140625, (float).112152099609375, (float)-28.2120725582002449, (float)84.6362176746007346, (float)-91.8182415432400174, (float)42.5349987453884549, (float)-7.3687943594796317, (float).227108001708984375, (float)212.570130039217123, (float)-765.252468141181642, (float)1059.99045252799988, (float)-699.579627376132541, (float)218.19051174421159, (float)-26.4914304869515555, (float).572501420974731445, (float)-1919.457662318407, (float)8061.72218173730938, (float)-13586.5500064341374, (float)11655.3933368645332, (float)-5305.64697861340311, (float)1200.90291321635246, (float)-108.090919788394656, (float)1.7277275025844574, (float)20204.2913309661486, (float)-96980.5983886375135, (float)192547.001232531532, (float)-203400.177280415534, (float)122200.46498301746, (float)-41192.6549688975513, (float)7109.51430248936372, (float)-493.915304773088012, (float)6.07404200127348304, (float)-242919.187900551333, (float)1311763.6146629772, (float)-2998015.91853810675, (float)3763271.297656404, (float)-2813563.22658653411, (float)1268365.27332162478, (float)-331645.172484563578, (float)45218.7689813627263, (float)-2499.83048181120962, (float)24.3805296995560639, (float)3284469.85307203782, (float)-19706819.1184322269, (float)50952602.4926646422, (float)-74105148.2115326577, (float)66344512.2747290267, (float)-37567176.6607633513, (float)13288767.1664218183, (float)-2785618.12808645469, (float)308186.404612662398, (float)-13886.0897537170405, (float)110.017140269246738, (float)-49329253.664509962, (float)325573074.185765749, (float)-939462359.681578403, (float)1553596899.57058006, (float)-1621080552.10833708, (float)1106842816.82301447, (float)-495889784.275030309, (float)142062907.797533095, (float)-24474062.7257387285, (float)2243768.17792244943, (float)-84005.4336030240853, (float)551.335896122020586, (float)814789096.118312115, (float)-5866481492.05184723, (float)18688207509.2958249, (float)-34632043388.1587779, (float)41280185579.753974, (float)-33026599749.8007231, (float)17954213731.1556001, (float)-6563293792.61928433, (float)1559279864.87925751, (float)-225105661.889415278, (float)17395107.5539781645, (float)-549842.327572288687, (float)3038.09051092238427, (float)-14679261247.6956167, (float)114498237732.02581, (float)-399096175224.466498, (float)819218669548.577329, (float)-1098375156081.22331, (float)1008158106865.38209, (float)-645364869245.376503, (float)287900649906.150589, (float)-87867072178.0232657, (float)17634730606.8349694, (float)-2167164983.22379509, (float)143157876.718888981, (float)-3871833.44257261262, (float)18257.7554742931747, (float)286464035717.679043, (float)-2406297900028.50396, (float)9109341185239.89896, (float)-20516899410934.4374, (float)30565125519935.3206, (float)-31667088584785.1584, (float)23348364044581.8409, (float)-12320491305598.2872, (float)4612725780849.13197, (float)-1196552880196.1816, (float)205914503232.410016, (float)-21822927757.5292237, (float)1247009293.51271032, (float)-29188388.1222208134, (float)118838.426256783253}; /* System generated locals */ int32 i__1, i__2; float r__1; System::Complex<float> q__1, q__2, q__3; int32 i__, j, k, l; System::Complex<float> s, t, t2; float ac; System::Complex<float> sr, zn, cfn; float rfn; System::Complex<float> crfn; float test, tsti, tstr; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE CUNIK */ /* ***REFER TO CBESI,CBESK */ /* CUNIK COMPUTES PARAMETERS FOR THE UNIFORM ASYMPTOTIC */ /* EXPANSIONS OF THE I AND K FUNCTIONS ON IKFLG= 1 OR 2 */ /* RESPECTIVELY BY */ /* W(FNU,ZR) = PHI*EXP(ZETA)*SUM */ /* WHERE ZETA=-ZETA1 + ZETA2 OR */ /* ZETA1 - ZETA2 */ /* THE FIRST CALL MUST HAVE INIT=0. SUBSEQUENT CALLS WITH THE */ /* SAME ZR AND FNU WILL RETURN THE I OR K FUNCTION ON IKFLG= */ /* 1 OR 2 WITH NO CHANGE IN INIT. CWRK IS A COMPLEX WORK */ /* ARRAY. IPMTR=0 COMPUTES ALL PARAMETERS. IPMTR=1 COMPUTES PHI, */ /* ZETA1,ZETA2. */ /* ***ROUTINES CALLED (NONE) */ /* ***END PROLOGUE CUNIK */ /* Parameter adjustments */ --cwrk; /* Function Body */ if(*init != 0) { goto L40; } /* ----------------------------------------------------------------------- */ /* INITIALIZE ALL VARIABLES */ /* ----------------------------------------------------------------------- */ rfn = (float)1. / *fnu; q__1.real() = rfn, q__1.imag() = (float)0.; crfn.real() = q__1.real(), crfn.imag() = q__1.imag(); /* T = ZR*CRFN */ /* ----------------------------------------------------------------------- */ /* OVERFLOW TEST (ZR/FNU TOO SMALL) */ /* ----------------------------------------------------------------------- */ tstr = zr->real(); tsti = r_imag(zr); test = r1mach_(&c__1) * (float)1e3; ac = *fnu * test; if(abs(tstr) > ac || abs(tsti) > ac) { goto L15; } ac = (r__1 = log(test), abs(r__1)) * (float)2. + *fnu; q__1.real() = ac, q__1.imag() = (float)0.; zeta1->real() = q__1.real(), zeta1->imag() = q__1.imag(); q__1.real() = *fnu, q__1.imag() = (float)0.; zeta2->real() = q__1.real(), zeta2->imag() = q__1.imag(); phi->real() = cone.real(), phi->imag() = cone.imag(); return 0; L15: q__1.real() = zr->real() * crfn.real() - zr->imag() * crfn.imag(), q__1.imag() = zr->real() * crfn.imag() + zr->imag() * crfn.real(); t.real() = q__1.real(), t.imag() = q__1.imag(); q__2.real() = t.real() * t.real() - t.imag() * t.imag(), q__2.imag() = t.real() * t.imag() + t.imag() * t.real(); q__1.real() = cone.real() + q__2.real(), q__1.imag() = cone.imag() + q__2.imag(); s.real() = q__1.real(), s.imag() = q__1.imag(); c_sqrt(&q__1, &s); sr.real() = q__1.real(), sr.imag() = q__1.imag(); q__1.real() = *fnu, q__1.imag() = (float)0.; cfn.real() = q__1.real(), cfn.imag() = q__1.imag(); q__2.real() = cone.real() + sr.real(), q__2.imag() = cone.imag() + sr.imag(); c_div(&q__1, &q__2, &t); zn.real() = q__1.real(), zn.imag() = q__1.imag(); c_log(&q__2, &zn); q__1.real() = cfn.real() * q__2.real() - cfn.imag() * q__2.imag(), q__1.imag() = cfn.real() * q__2.imag() + cfn.imag() * q__2.real(); zeta1->real() = q__1.real(), zeta1->imag() = q__1.imag(); q__1.real() = cfn.real() * sr.real() - cfn.imag() * sr.imag(), q__1.imag() = cfn.real() * sr.imag() + cfn.imag() * sr.real(); zeta2->real() = q__1.real(), zeta2->imag() = q__1.imag(); c_div(&q__1, &cone, &sr); t.real() = q__1.real(), t.imag() = q__1.imag(); q__1.real() = t.real() * crfn.real() - t.imag() * crfn.imag(), q__1.imag() = t.real() * crfn.imag() + t.imag() * crfn.real(); sr.real() = q__1.real(), sr.imag() = q__1.imag(); c_sqrt(&q__1, &sr); cwrk[16].real() = q__1.real(), cwrk[16].imag() = q__1.imag(); i__1 = *ikflg - 1; q__1.real() = cwrk[16].real() * con[i__1].real() - cwrk[16].imag() * con[i__1].imag(), q__1.imag() = cwrk[16].real() * con[i__1].imag() + cwrk[16].imag() * con[i__1].real(); phi->real() = q__1.real(), phi->imag() = q__1.imag(); if(*ipmtr != 0) { return 0; } c_div(&q__1, &cone, &s); t2.real() = q__1.real(), t2.imag() = q__1.imag(); cwrk[1].real() = cone.real(), cwrk[1].imag() = cone.imag(); crfn.real() = cone.real(), crfn.imag() = cone.imag(); ac = (float)1.; l = 1; for(k = 2; k <= 15; ++k) { s.real() = czero.real(), s.imag() = czero.imag(); i__1 = k; for(j = 1; j <= i__1; ++j) { ++l; q__2.real() = s.real() * t2.real() - s.imag() * t2.imag(), q__2.imag() = s.real() * t2.imag() + s.imag() * t2.real(); i__2 = l - 1; q__3.real() = c__[i__2], q__3.imag() = (float)0.; q__1.real() = q__2.real() + q__3.real(), q__1.imag() = q__2.imag() + q__3.imag(); s.real() = q__1.real(), s.imag() = q__1.imag(); /* L10: */ } q__1.real() = crfn.real() * sr.real() - crfn.imag() * sr.imag(), q__1.imag() = crfn.real() * sr.imag() + crfn.imag() * sr.real(); crfn.real() = q__1.real(), crfn.imag() = q__1.imag(); i__1 = k; q__1.real() = crfn.real() * s.real() - crfn.imag() * s.imag(), q__1.imag() = crfn.real() * s.imag() + crfn.imag() * s.real(); cwrk[i__1].real() = q__1.real(), cwrk[i__1].imag() = q__1.imag(); ac *= rfn; i__1 = k; tstr = cwrk[i__1].real(); tsti = r_imag(&cwrk[k]); test = abs(tstr) + abs(tsti); if(ac < *tol && test < *tol) { goto L30; } /* L20: */ } k = 15; L30: *init = k; L40: if(*ikflg == 2) { goto L60; } /* ----------------------------------------------------------------------- */ /* COMPUTE SUM FOR THE I FUNCTION */ /* ----------------------------------------------------------------------- */ s.real() = czero.real(), s.imag() = czero.imag(); i__1 = *init; for(i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; q__1.real() = s.real() + cwrk[i__2].real(), q__1.imag() = s.imag() + cwrk[i__2].imag(); s.real() = q__1.real(), s.imag() = q__1.imag(); /* L50: */ } sum->real() = s.real(), sum->imag() = s.imag(); q__1.real() = cwrk[16].real() * con[0].real() - cwrk[16].imag() * con[0].imag(), q__1.imag() = cwrk[16].real() * con[0].imag() + cwrk[16].imag() * con[0].real(); phi->real() = q__1.real(), phi->imag() = q__1.imag(); return 0; L60: /* ----------------------------------------------------------------------- */ /* COMPUTE SUM FOR THE K FUNCTION */ /* ----------------------------------------------------------------------- */ s.real() = czero.real(), s.imag() = czero.imag(); t.real() = cone.real(), t.imag() = cone.imag(); i__1 = *init; for(i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; q__2.real() = t.real() * cwrk[i__2].real() - t.imag() * cwrk[i__2].imag(), q__2.imag() = t.real() * cwrk[i__2].imag() + t.imag() * cwrk[i__2].real(); q__1.real() = s.real() + q__2.real(), q__1.imag() = s.imag() + q__2.imag(); s.real() = q__1.real(), s.imag() = q__1.imag(); q__1.real() = -t.real(), q__1.imag() = -t.imag(); t.real() = q__1.real(), t.imag() = q__1.imag(); /* L70: */ } sum->real() = s.real(), sum->imag() = s.imag(); q__1.real() = cwrk[16].real() * con[1].real() - cwrk[16].imag() * con[1].imag(), q__1.imag() = cwrk[16].real() * con[1].imag() + cwrk[16].imag() * con[1].real(); phi->real() = q__1.real(), phi->imag() = q__1.imag(); return 0; } /* cunik_ */ int cunk1_(System::Complex<float>* z__, float* fnu, int32* kode, int32* mr, int32* n, System::Complex<float>* y, int32* nz, float* tol, float* elim, float* alim) { /* Initialized data */ static System::Complex<float> czero = {(float)0., (float)0.}; static System::Complex<float> cone = {(float)1., (float)0.}; static float pi = (float)3.14159265358979324; /* System generated locals */ int32 i__1, i__2, i__3; float r__1, r__2; System::Complex<float> q__1, q__2, q__3, q__4, q__5; int32 i__, j, k, m; float x; System::Complex<float> c1, c2, s1, s2; int32 ib, ic; System::Complex<float> ck; float fn; int32 il; System::Complex<float> cs; int32 kk; System::Complex<float> cy[2]; int32 nw; System::Complex<float> rz, zr; float c2i, c2m, c2r, rs1, ang; System::Complex<float> cfn; float asc, fnf; int32 ifn; System::Complex<float> phi[2]; float cpn; int32 iuf; float fmr; System::Complex<float> csr[3], css[3]; float sgn; int32 inu; float bry[3], spn; System::Complex<float> sum[2]; float aphi; System::Complex<float> cscl, phid, crsc, csgn; System::Complex<float> cspn; int32 init[2]; System::Complex<float> cwrk[48] /* was [16][3] */, sumd, zeta1[2], zeta2[2]; int32 iflag, kflag; float ascle; int32 kdflg; int32 ipard, initd; System::Complex<float> zeta1d, zeta2d; #define cwrk_subscr(a_1, a_2) (a_2) * 16 + a_1 - 17 #define cwrk_ref(a_1, a_2) cwrk[cwrk_subscr(a_1, a_2)] /* *********************************************************************72 */ /* ***BEGIN PROLOGUE CUNK1 */ /* ***REFER TO CBESK */ /* CUNK1 COMPUTES K(FNU,Z) AND ITS ANALYTIC CONTINUATION FROM THE */ /* RIGHT HALF PLANE TO THE LEFT HALF PLANE BY MEANS OF THE */ /* UNIFORM ASYMPTOTIC EXPANSION. */ /* MR INDICATES THE DIRECTION OF ROTATION FOR ANALYTIC CONTINUATION. */ /* NZ=-1 MEANS AN OVERFLOW WILL OCCUR */ /* ***ROUTINES CALLED CS1S2,CUCHK,CUNIK,R1MACH */ /* ***END PROLOGUE CUNK1 */ /* Parameter adjustments */ --y; /* Function Body */ kdflg = 1; *nz = 0; /* ----------------------------------------------------------------------- */ /* EXP(-ALIM)=EXP(-ELIM)/TOL=APPROX. ONE PRECISION GREATER THAN */ /* THE UNDERFLOW LIMIT */ /* ----------------------------------------------------------------------- */ r__1 = (float)1. / *tol; q__1.real() = r__1, q__1.imag() = (float)0.; cscl.real() = q__1.real(), cscl.imag() = q__1.imag(); q__1.real() = *tol, q__1.imag() = (float)0.; crsc.real() = q__1.real(), crsc.imag() = q__1.imag(); css[0].real() = cscl.real(), css[0].imag() = cscl.imag(); css[1].real() = cone.real(), css[1].imag() = cone.imag(); css[2].real() = crsc.real(), css[2].imag() = crsc.imag(); csr[0].real() = crsc.real(), csr[0].imag() = crsc.imag(); csr[1].real() = cone.real(), csr[1].imag() = cone.imag(); csr[2].real() = cscl.real(), csr[2].imag() = cscl.imag(); bry[0] = r1mach_(&c__1) * (float)1e3 / *tol; bry[1] = (float)1. / bry[0]; bry[2] = r1mach_(&c__2); x = z__->real(); zr.real() = z__->real(), zr.imag() = z__->imag(); if(x < (float)0.) { q__1.real() = -z__->real(), q__1.imag() = -z__->imag(); zr.real() = q__1.real(), zr.imag() = q__1.imag(); } j = 2; i__1 = *n; for(i__ = 1; i__ <= i__1; ++i__) { /* ----------------------------------------------------------------------- */ /* J FLIP FLOPS BETWEEN 1 AND 2 IN J = 3 - J */ /* ----------------------------------------------------------------------- */ j = 3 - j; fn = *fnu + (float)(i__ - 1); init[j - 1] = 0; cunik_(&zr, &fn, &c__2, &c__0, tol, &init[j - 1], &phi[j - 1], &zeta1[j - 1], &zeta2[j - 1], &sum[j - 1], &cwrk_ref(1, j)); if(*kode == 1) { goto L20; } q__1.real() = fn, q__1.imag() = (float)0.; cfn.real() = q__1.real(), cfn.imag() = q__1.imag(); i__2 = j - 1; i__3 = j - 1; q__4.real() = zr.real() + zeta2[i__3].real(), q__4.imag() = zr.imag() + zeta2[i__3].imag(); c_div(&q__3, &cfn, &q__4); q__2.real() = cfn.real() * q__3.real() - cfn.imag() * q__3.imag(), q__2.imag() = cfn.real() * q__3.imag() + cfn.imag() * q__3.real(); q__1.real() = zeta1[i__2].real() - q__2.real(), q__1.imag() = zeta1[i__2].imag() - q__2.imag(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); goto L30; L20: i__2 = j - 1; i__3 = j - 1; q__1.real() = zeta1[i__2].real() - zeta2[i__3].real(), q__1.imag() = zeta1[i__2].imag() - zeta2[i__3].imag(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); L30: /* ----------------------------------------------------------------------- */ /* TEST FOR UNDERFLOW AND OVERFLOW */ /* ----------------------------------------------------------------------- */ rs1 = s1.real(); if(abs(rs1) > *elim) { goto L60; } if(kdflg == 1) { kflag = 2; } if(abs(rs1) < *alim) { goto L40; } /* ----------------------------------------------------------------------- */ /* REFINE TEST AND SCALE */ /* ----------------------------------------------------------------------- */ aphi = c_abs(&phi[j - 1]); rs1 += log(aphi); if(abs(rs1) > *elim) { goto L60; } if(kdflg == 1) { kflag = 1; } if(rs1 < (float)0.) { goto L40; } if(kdflg == 1) { kflag = 3; } L40: /* ----------------------------------------------------------------------- */ /* SCALE S1 TO KEEP INTERMEDIATE ARITHMETIC ON SCALE NEAR */ /* EXPONENT EXTREMES */ /* ----------------------------------------------------------------------- */ i__2 = j - 1; i__3 = j - 1; q__1.real() = phi[i__2].real() * sum[i__3].real() - phi[i__2].imag() * sum[i__3].imag(), q__1.imag() = phi[i__2].real() * sum[i__3].imag() + phi[i__2].imag() * sum[i__3].real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); c2r = s1.real(); c2i = r_imag(&s1); i__2 = kflag - 1; c2m = exp(c2r) * css[i__2].real(); q__2.real() = c2m, q__2.imag() = (float)0.; r__1 = cos(c2i); r__2 = sin(c2i); q__3.real() = r__1, q__3.imag() = r__2; q__1.real() = q__2.real() * q__3.real() - q__2.imag() * q__3.imag(), q__1.imag() = q__2.real() * q__3.imag() + q__2.imag() * q__3.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); q__1.real() = s2.real() * s1.real() - s2.imag() * s1.imag(), q__1.imag() = s2.real() * s1.imag() + s2.imag() * s1.real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); if(kflag != 1) { goto L50; } cuchk_(&s2, &nw, bry, tol); if(nw != 0) { goto L60; } L50: i__2 = kdflg - 1; cy[i__2].real() = s2.real(), cy[i__2].imag() = s2.imag(); i__2 = i__; i__3 = kflag - 1; q__1.real() = s2.real() * csr[i__3].real() - s2.imag() * csr[i__3].imag(), q__1.imag() = s2.real() * csr[i__3].imag() + s2.imag() * csr[i__3].real(); y[i__2].real() = q__1.real(), y[i__2].imag() = q__1.imag(); if(kdflg == 2) { goto L75; } kdflg = 2; goto L70; L60: if(rs1 > (float)0.) { goto L290; } /* ----------------------------------------------------------------------- */ /* FOR X.LT.0.0, THE I FUNCTION TO BE ADDED WILL OVERFLOW */ /* ----------------------------------------------------------------------- */ if(x < (float)0.) { goto L290; } kdflg = 1; i__2 = i__; y[i__2].real() = czero.real(), y[i__2].imag() = czero.imag(); ++(*nz); if(i__ == 1) { goto L70; } i__2 = i__ - 1; if(y[i__2].real() == czero.real() && y[i__2].imag() == czero.imag()) { goto L70; } i__2 = i__ - 1; y[i__2].real() = czero.real(), y[i__2].imag() = czero.imag(); ++(*nz); L70:; } i__ = *n; L75: c_div(&q__1, &c_b17, &zr); rz.real() = q__1.real(), rz.imag() = q__1.imag(); q__2.real() = fn, q__2.imag() = (float)0.; q__1.real() = q__2.real() * rz.real() - q__2.imag() * rz.imag(), q__1.imag() = q__2.real() * rz.imag() + q__2.imag() * rz.real(); ck.real() = q__1.real(), ck.imag() = q__1.imag(); ib = i__ + 1; if(*n < ib) { goto L160; } /* ----------------------------------------------------------------------- */ /* TEST LAST MEMBER FOR UNDERFLOW AND OVERFLOW, SET SEQUENCE TO ZERO */ /* ON UNDERFLOW */ /* ----------------------------------------------------------------------- */ fn = *fnu + (float)(*n - 1); ipard = 1; if(*mr != 0) { ipard = 0; } initd = 0; cunik_(&zr, &fn, &c__2, &ipard, tol, &initd, &phid, &zeta1d, &zeta2d, &sumd, &cwrk_ref(1, 3)); if(*kode == 1) { goto L80; } q__1.real() = fn, q__1.imag() = (float)0.; cfn.real() = q__1.real(), cfn.imag() = q__1.imag(); q__4.real() = zr.real() + zeta2d.real(), q__4.imag() = zr.imag() + zeta2d.imag(); c_div(&q__3, &cfn, &q__4); q__2.real() = cfn.real() * q__3.real() - cfn.imag() * q__3.imag(), q__2.imag() = cfn.real() * q__3.imag() + cfn.imag() * q__3.real(); q__1.real() = zeta1d.real() - q__2.real(), q__1.imag() = zeta1d.imag() - q__2.imag(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); goto L90; L80: q__1.real() = zeta1d.real() - zeta2d.real(), q__1.imag() = zeta1d.imag() - zeta2d.imag(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); L90: rs1 = s1.real(); if(abs(rs1) > *elim) { goto L95; } if(abs(rs1) < *alim) { goto L100; } /* ----------------------------------------------------------------------- */ /* REFINE ESTIMATE AND TEST */ /* ----------------------------------------------------------------------- */ aphi = c_abs(&phid); rs1 += log(aphi); if(abs(rs1) < *elim) { goto L100; } L95: if(rs1 > (float)0.) { goto L290; } /* ----------------------------------------------------------------------- */ /* FOR X.LT.0.0, THE I FUNCTION TO BE ADDED WILL OVERFLOW */ /* ----------------------------------------------------------------------- */ if(x < (float)0.) { goto L290; } *nz = *n; i__1 = *n; for(i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; y[i__2].real() = czero.real(), y[i__2].imag() = czero.imag(); /* L96: */ } return 0; L100: /* ----------------------------------------------------------------------- */ /* RECUR FORWARD FOR REMAINDER OF THE SEQUENCE */ /* ----------------------------------------------------------------------- */ s1.real() = cy[0].real(), s1.imag() = cy[0].imag(); s2.real() = cy[1].real(), s2.imag() = cy[1].imag(); i__1 = kflag - 1; c1.real() = csr[i__1].real(), c1.imag() = csr[i__1].imag(); ascle = bry[kflag - 1]; i__1 = *n; for(i__ = ib; i__ <= i__1; ++i__) { c2.real() = s2.real(), c2.imag() = s2.imag(); q__2.real() = ck.real() * s2.real() - ck.imag() * s2.imag(), q__2.imag() = ck.real() * s2.imag() + ck.imag() * s2.real(); q__1.real() = q__2.real() + s1.real(), q__1.imag() = q__2.imag() + s1.imag(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); s1.real() = c2.real(), s1.imag() = c2.imag(); q__1.real() = ck.real() + rz.real(), q__1.imag() = ck.imag() + rz.imag(); ck.real() = q__1.real(), ck.imag() = q__1.imag(); q__1.real() = s2.real() * c1.real() - s2.imag() * c1.imag(), q__1.imag() = s2.real() * c1.imag() + s2.imag() * c1.real(); c2.real() = q__1.real(), c2.imag() = q__1.imag(); i__2 = i__; y[i__2].real() = c2.real(), y[i__2].imag() = c2.imag(); if(kflag >= 3) { goto L120; } c2r = c2.real(); c2i = r_imag(&c2); c2r = abs(c2r); c2i = abs(c2i); c2m = max(c2r, c2i); if(c2m <= ascle) { goto L120; } ++kflag; ascle = bry[kflag - 1]; q__1.real() = s1.real() * c1.real() - s1.imag() * c1.imag(), q__1.imag() = s1.real() * c1.imag() + s1.imag() * c1.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); s2.real() = c2.real(), s2.imag() = c2.imag(); i__2 = kflag - 1; q__1.real() = s1.real() * css[i__2].real() - s1.imag() * css[i__2].imag(), q__1.imag() = s1.real() * css[i__2].imag() + s1.imag() * css[i__2].real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); i__2 = kflag - 1; q__1.real() = s2.real() * css[i__2].real() - s2.imag() * css[i__2].imag(), q__1.imag() = s2.real() * css[i__2].imag() + s2.imag() * css[i__2].real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); i__2 = kflag - 1; c1.real() = csr[i__2].real(), c1.imag() = csr[i__2].imag(); L120:; } L160: if(*mr == 0) { return 0; } /* ----------------------------------------------------------------------- */ /* ANALYTIC CONTINUATION FOR RE(Z).LT.0.0E0 */ /* ----------------------------------------------------------------------- */ *nz = 0; fmr = (float)(*mr); sgn = -r_sign(&pi, &fmr); /* ----------------------------------------------------------------------- */ /* CSPN AND CSGN ARE COEFF OF K AND I FUNCIONS RESP. */ /* ----------------------------------------------------------------------- */ q__1.real() = (float)0., q__1.imag() = sgn; csgn.real() = q__1.real(), csgn.imag() = q__1.imag(); inu = (int32)(*fnu); fnf = *fnu - (float)inu; ifn = inu + *n - 1; ang = fnf * sgn; cpn = cos(ang); spn = sin(ang); q__1.real() = cpn, q__1.imag() = spn; cspn.real() = q__1.real(), cspn.imag() = q__1.imag(); if(ifn % 2 == 1) { q__1.real() = -cspn.real(), q__1.imag() = -cspn.imag(); cspn.real() = q__1.real(), cspn.imag() = q__1.imag(); } asc = bry[0]; kk = *n; iuf = 0; kdflg = 1; --ib; ic = ib - 1; i__1 = *n; for(k = 1; k <= i__1; ++k) { fn = *fnu + (float)(kk - 1); /* ----------------------------------------------------------------------- */ /* LOGIC TO SORT OUT CASES WHOSE PARAMETERS WERE SET FOR THE K */ /* FUNCTION ABOVE */ /* ----------------------------------------------------------------------- */ m = 3; if(*n > 2) { goto L175; } L170: initd = init[j - 1]; i__2 = j - 1; phid.real() = phi[i__2].real(), phid.imag() = phi[i__2].imag(); i__2 = j - 1; zeta1d.real() = zeta1[i__2].real(), zeta1d.imag() = zeta1[i__2].imag(); i__2 = j - 1; zeta2d.real() = zeta2[i__2].real(), zeta2d.imag() = zeta2[i__2].imag(); i__2 = j - 1; sumd.real() = sum[i__2].real(), sumd.imag() = sum[i__2].imag(); m = j; j = 3 - j; goto L180; L175: if(kk == *n && ib < *n) { goto L180; } if(kk == ib || kk == ic) { goto L170; } initd = 0; L180: cunik_(&zr, &fn, &c__1, &c__0, tol, &initd, &phid, &zeta1d, &zeta2d, &sumd, &cwrk_ref(1, m)); if(*kode == 1) { goto L190; } q__1.real() = fn, q__1.imag() = (float)0.; cfn.real() = q__1.real(), cfn.imag() = q__1.imag(); q__2.real() = -zeta1d.real(), q__2.imag() = -zeta1d.imag(); q__5.real() = zr.real() + zeta2d.real(), q__5.imag() = zr.imag() + zeta2d.imag(); c_div(&q__4, &cfn, &q__5); q__3.real() = cfn.real() * q__4.real() - cfn.imag() * q__4.imag(), q__3.imag() = cfn.real() * q__4.imag() + cfn.imag() * q__4.real(); q__1.real() = q__2.real() + q__3.real(), q__1.imag() = q__2.imag() + q__3.imag(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); goto L200; L190: q__2.real() = -zeta1d.real(), q__2.imag() = -zeta1d.imag(); q__1.real() = q__2.real() + zeta2d.real(), q__1.imag() = q__2.imag() + zeta2d.imag(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); L200: /* ----------------------------------------------------------------------- */ /* TEST FOR UNDERFLOW AND OVERFLOW */ /* ----------------------------------------------------------------------- */ rs1 = s1.real(); if(abs(rs1) > *elim) { goto L250; } if(kdflg == 1) { iflag = 2; } if(abs(rs1) < *alim) { goto L210; } /* ----------------------------------------------------------------------- */ /* REFINE TEST AND SCALE */ /* ----------------------------------------------------------------------- */ aphi = c_abs(&phid); rs1 += log(aphi); if(abs(rs1) > *elim) { goto L250; } if(kdflg == 1) { iflag = 1; } if(rs1 < (float)0.) { goto L210; } if(kdflg == 1) { iflag = 3; } L210: q__2.real() = csgn.real() * phid.real() - csgn.imag() * phid.imag(), q__2.imag() = csgn.real() * phid.imag() + csgn.imag() * phid.real(); q__1.real() = q__2.real() * sumd.real() - q__2.imag() * sumd.imag(), q__1.imag() = q__2.real() * sumd.imag() + q__2.imag() * sumd.real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); c2r = s1.real(); c2i = r_imag(&s1); i__2 = iflag - 1; c2m = exp(c2r) * css[i__2].real(); q__2.real() = c2m, q__2.imag() = (float)0.; r__1 = cos(c2i); r__2 = sin(c2i); q__3.real() = r__1, q__3.imag() = r__2; q__1.real() = q__2.real() * q__3.real() - q__2.imag() * q__3.imag(), q__1.imag() = q__2.real() * q__3.imag() + q__2.imag() * q__3.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); q__1.real() = s2.real() * s1.real() - s2.imag() * s1.imag(), q__1.imag() = s2.real() * s1.imag() + s2.imag() * s1.real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); if(iflag != 1) { goto L220; } cuchk_(&s2, &nw, bry, tol); if(nw != 0) { s2.real() = (float)0., s2.imag() = (float)0.; } L220: i__2 = kdflg - 1; cy[i__2].real() = s2.real(), cy[i__2].imag() = s2.imag(); c2.real() = s2.real(), c2.imag() = s2.imag(); i__2 = iflag - 1; q__1.real() = s2.real() * csr[i__2].real() - s2.imag() * csr[i__2].imag(), q__1.imag() = s2.real() * csr[i__2].imag() + s2.imag() * csr[i__2].real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); /* ----------------------------------------------------------------------- */ /* ADD I AND K FUNCTIONS, K SEQUENCE IN Y(I), I=1,N */ /* ----------------------------------------------------------------------- */ i__2 = kk; s1.real() = y[i__2].real(), s1.imag() = y[i__2].imag(); if(*kode == 1) { goto L240; } cs1s2_(&zr, &s1, &s2, &nw, &asc, alim, &iuf); *nz += nw; L240: i__2 = kk; q__2.real() = s1.real() * cspn.real() - s1.imag() * cspn.imag(), q__2.imag() = s1.real() * cspn.imag() + s1.imag() * cspn.real(); q__1.real() = q__2.real() + s2.real(), q__1.imag() = q__2.imag() + s2.imag(); y[i__2].real() = q__1.real(), y[i__2].imag() = q__1.imag(); --kk; q__1.real() = -cspn.real(), q__1.imag() = -cspn.imag(); cspn.real() = q__1.real(), cspn.imag() = q__1.imag(); if(c2.real() != czero.real() || c2.imag() != czero.imag()) { goto L245; } kdflg = 1; goto L260; L245: if(kdflg == 2) { goto L265; } kdflg = 2; goto L260; L250: if(rs1 > (float)0.) { goto L290; } s2.real() = czero.real(), s2.imag() = czero.imag(); goto L220; L260:; } k = *n; L265: il = *n - k; if(il == 0) { return 0; } /* ----------------------------------------------------------------------- */ /* RECUR BACKWARD FOR REMAINDER OF I SEQUENCE AND ADD IN THE */ /* K FUNCTIONS, SCALING THE I SEQUENCE DURING RECURRENCE TO KEEP */ /* INTERMEDIATE ARITHMETIC ON SCALE NEAR EXPONENT EXTREMES. */ /* ----------------------------------------------------------------------- */ s1.real() = cy[0].real(), s1.imag() = cy[0].imag(); s2.real() = cy[1].real(), s2.imag() = cy[1].imag(); i__1 = iflag - 1; cs.real() = csr[i__1].real(), cs.imag() = csr[i__1].imag(); ascle = bry[iflag - 1]; fn = (float)(inu + il); i__1 = il; for(i__ = 1; i__ <= i__1; ++i__) { c2.real() = s2.real(), c2.imag() = s2.imag(); r__1 = fn + fnf; q__4.real() = r__1, q__4.imag() = (float)0.; q__3.real() = q__4.real() * rz.real() - q__4.imag() * rz.imag(), q__3.imag() = q__4.real() * rz.imag() + q__4.imag() * rz.real(); q__2.real() = q__3.real() * s2.real() - q__3.imag() * s2.imag(), q__2.imag() = q__3.real() * s2.imag() + q__3.imag() * s2.real(); q__1.real() = s1.real() + q__2.real(), q__1.imag() = s1.imag() + q__2.imag(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); s1.real() = c2.real(), s1.imag() = c2.imag(); fn += (float)-1.; q__1.real() = s2.real() * cs.real() - s2.imag() * cs.imag(), q__1.imag() = s2.real() * cs.imag() + s2.imag() * cs.real(); c2.real() = q__1.real(), c2.imag() = q__1.imag(); ck.real() = c2.real(), ck.imag() = c2.imag(); i__2 = kk; c1.real() = y[i__2].real(), c1.imag() = y[i__2].imag(); if(*kode == 1) { goto L270; } cs1s2_(&zr, &c1, &c2, &nw, &asc, alim, &iuf); *nz += nw; L270: i__2 = kk; q__2.real() = c1.real() * cspn.real() - c1.imag() * cspn.imag(), q__2.imag() = c1.real() * cspn.imag() + c1.imag() * cspn.real(); q__1.real() = q__2.real() + c2.real(), q__1.imag() = q__2.imag() + c2.imag(); y[i__2].real() = q__1.real(), y[i__2].imag() = q__1.imag(); --kk; q__1.real() = -cspn.real(), q__1.imag() = -cspn.imag(); cspn.real() = q__1.real(), cspn.imag() = q__1.imag(); if(iflag >= 3) { goto L280; } c2r = ck.real(); c2i = r_imag(&ck); c2r = abs(c2r); c2i = abs(c2i); c2m = max(c2r, c2i); if(c2m <= ascle) { goto L280; } ++iflag; ascle = bry[iflag - 1]; q__1.real() = s1.real() * cs.real() - s1.imag() * cs.imag(), q__1.imag() = s1.real() * cs.imag() + s1.imag() * cs.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); s2.real() = ck.real(), s2.imag() = ck.imag(); i__2 = iflag - 1; q__1.real() = s1.real() * css[i__2].real() - s1.imag() * css[i__2].imag(), q__1.imag() = s1.real() * css[i__2].imag() + s1.imag() * css[i__2].real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); i__2 = iflag - 1; q__1.real() = s2.real() * css[i__2].real() - s2.imag() * css[i__2].imag(), q__1.imag() = s2.real() * css[i__2].imag() + s2.imag() * css[i__2].real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); i__2 = iflag - 1; cs.real() = csr[i__2].real(), cs.imag() = csr[i__2].imag(); L280:; } return 0; L290: *nz = -1; return 0; } /* cunk1_ */ #undef cwrk_ref #undef cwrk_subscr int cunk2_(System::Complex<float>* z__, float* fnu, int32* kode, int32* mr, int32* n, System::Complex<float>* y, int32* nz, float* tol, float* elim, float* alim) { /* Initialized data */ static System::Complex<float> czero = {(float)0., (float)0.}; static System::Complex<float> cone = {(float)1., (float)0.}; static System::Complex<float> ci = {(float)0., (float)1.}; static System::Complex<float> cr1 = {(float)1., (float)1.73205080756887729}; static System::Complex<float> cr2 = {(float)-.5, (float)-.866025403784438647}; static float hpi = (float)1.57079632679489662; static float pi = (float)3.14159265358979324; static float aic = (float)1.26551212348464539; static System::Complex<float> cip[4] = {{(float)1., (float)0.}, {(float)0., (float)-1.}, {(float)-1., (float)0.}, {(float)0., (float)1.}}; /* System generated locals */ int32 i__1, i__2, i__3, i__4; float r__1, r__2; System::Complex<float> q__1, q__2, q__3, q__4, q__5, q__6; int32 i__, j, k; float x; System::Complex<float> c1, c2, s1, s2, ai; int32 ib, ic; System::Complex<float> ck; float fn; int32 il; System::Complex<float> cs; int32 in, kk; System::Complex<float> cy[2], zb; int32 nw; System::Complex<float> zn, rz, zr; float yy, c2i, c2m, c2r, rs1; System::Complex<float> dai; float ang; System::Complex<float> cfn; float asc, car; System::Complex<float> arg[2]; float fnf; int32 ifn, nai; System::Complex<float> phi[2]; float cpn; int32 iuf; float fmr, sar; System::Complex<float> csr[3], css[3]; float sgn; int32 inu; float bry[3], spn, aarg; int32 ndai; System::Complex<float> argd; float aphi; System::Complex<float> cscl, phid, crsc, csgn; int32 idum; System::Complex<float> cspn, asum[2], bsum[2], zeta1[2], zeta2[2]; int32 iflag, kflag; float ascle; int32 kdflg; int32 ipard; System::Complex<float> asumd, bsumd; System::Complex<float> zeta1d, zeta2d; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE CUNK2 */ /* ***REFER TO CBESK */ /* CUNK2 COMPUTES K(FNU,Z) AND ITS ANALYTIC CONTINUATION FROM THE */ /* RIGHT HALF PLANE TO THE LEFT HALF PLANE BY MEANS OF THE */ /* UNIFORM ASYMPTOTIC EXPANSIONS FOR H(KIND,FNU,ZN) AND J(FNU,ZN) */ /* WHERE ZN IS IN THE RIGHT HALF PLANE, KIND=(3-MR)/2, MR=+1 OR */ /* -1. HERE ZN=ZR*I OR -ZR*I WHERE ZR=Z IF Z IS IN THE RIGHT */ /* HALF PLANE OR ZR=-Z IF Z IS IN THE LEFT HALF PLANE. MR INDIC- */ /* ATES THE DIRECTION OF ROTATION FOR ANALYTIC CONTINUATION. */ /* NZ=-1 MEANS AN OVERFLOW WILL OCCUR */ /* ***ROUTINES CALLED CAIRY,CS1S2,CUCHK,CUNHJ,R1MACH */ /* ***END PROLOGUE CUNK2 */ /* Parameter adjustments */ --y; /* Function Body */ kdflg = 1; *nz = 0; /* ----------------------------------------------------------------------- */ /* EXP(-ALIM)=EXP(-ELIM)/TOL=APPROX. ONE PRECISION GREATER THAN */ /* THE UNDERFLOW LIMIT */ /* ----------------------------------------------------------------------- */ r__1 = (float)1. / *tol; q__1.real() = r__1, q__1.imag() = (float)0.; cscl.real() = q__1.real(), cscl.imag() = q__1.imag(); q__1.real() = *tol, q__1.imag() = (float)0.; crsc.real() = q__1.real(), crsc.imag() = q__1.imag(); css[0].real() = cscl.real(), css[0].imag() = cscl.imag(); css[1].real() = cone.real(), css[1].imag() = cone.imag(); css[2].real() = crsc.real(), css[2].imag() = crsc.imag(); csr[0].real() = crsc.real(), csr[0].imag() = crsc.imag(); csr[1].real() = cone.real(), csr[1].imag() = cone.imag(); csr[2].real() = cscl.real(), csr[2].imag() = cscl.imag(); bry[0] = r1mach_(&c__1) * (float)1e3 / *tol; bry[1] = (float)1. / bry[0]; bry[2] = r1mach_(&c__2); x = z__->real(); zr.real() = z__->real(), zr.imag() = z__->imag(); if(x < (float)0.) { q__1.real() = -z__->real(), q__1.imag() = -z__->imag(); zr.real() = q__1.real(), zr.imag() = q__1.imag(); } yy = r_imag(&zr); q__2.real() = -zr.real(), q__2.imag() = -zr.imag(); q__1.real() = q__2.real() * ci.real() - q__2.imag() * ci.imag(), q__1.imag() = q__2.real() * ci.imag() + q__2.imag() * ci.real(); zn.real() = q__1.real(), zn.imag() = q__1.imag(); zb.real() = zr.real(), zb.imag() = zr.imag(); inu = (int32)(*fnu); fnf = *fnu - (float)inu; ang = -hpi * fnf; car = cos(ang); sar = sin(ang); cpn = -hpi * car; spn = -hpi * sar; r__1 = -spn; q__1.real() = r__1, q__1.imag() = cpn; c2.real() = q__1.real(), c2.imag() = q__1.imag(); kk = inu % 4 + 1; q__2.real() = cr1.real() * c2.real() - cr1.imag() * c2.imag(), q__2.imag() = cr1.real() * c2.imag() + cr1.imag() * c2.real(); i__1 = kk - 1; q__1.real() = q__2.real() * cip[i__1].real() - q__2.imag() * cip[i__1].imag(), q__1.imag() = q__2.real() * cip[i__1].imag() + q__2.imag() * cip[i__1].real(); cs.real() = q__1.real(), cs.imag() = q__1.imag(); if(yy > (float)0.) { goto L10; } q__2.real() = -zn.real(), q__2.imag() = -zn.imag(); r_cnjg(&q__1, &q__2); zn.real() = q__1.real(), zn.imag() = q__1.imag(); r_cnjg(&q__1, &zb); zb.real() = q__1.real(), zb.imag() = q__1.imag(); L10: /* ----------------------------------------------------------------------- */ /* K(FNU,Z) IS COMPUTED FROM H(2,FNU,-I*Z) WHERE Z IS IN THE FIRST */ /* QUADRANT. FOURTH QUADRANT VALUES (YY.LE.0.0E0) ARE COMPUTED BY */ /* CONJUGATION SINCE THE K FUNCTION IS REAL ON THE POSITIVE REAL AXIS */ /* ----------------------------------------------------------------------- */ j = 2; i__1 = *n; for(i__ = 1; i__ <= i__1; ++i__) { /* ----------------------------------------------------------------------- */ /* J FLIP FLOPS BETWEEN 1 AND 2 IN J = 3 - J */ /* ----------------------------------------------------------------------- */ j = 3 - j; fn = *fnu + (float)(i__ - 1); cunhj_(&zn, &fn, &c__0, tol, &phi[j - 1], &arg[j - 1], &zeta1[j - 1], &zeta2[j - 1], &asum[j - 1], &bsum[j - 1]); if(*kode == 1) { goto L20; } q__1.real() = fn, q__1.imag() = (float)0.; cfn.real() = q__1.real(), cfn.imag() = q__1.imag(); i__2 = j - 1; i__3 = j - 1; q__4.real() = zb.real() + zeta2[i__3].real(), q__4.imag() = zb.imag() + zeta2[i__3].imag(); c_div(&q__3, &cfn, &q__4); q__2.real() = cfn.real() * q__3.real() - cfn.imag() * q__3.imag(), q__2.imag() = cfn.real() * q__3.imag() + cfn.imag() * q__3.real(); q__1.real() = zeta1[i__2].real() - q__2.real(), q__1.imag() = zeta1[i__2].imag() - q__2.imag(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); goto L30; L20: i__2 = j - 1; i__3 = j - 1; q__1.real() = zeta1[i__2].real() - zeta2[i__3].real(), q__1.imag() = zeta1[i__2].imag() - zeta2[i__3].imag(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); L30: /* ----------------------------------------------------------------------- */ /* TEST FOR UNDERFLOW AND OVERFLOW */ /* ----------------------------------------------------------------------- */ rs1 = s1.real(); if(abs(rs1) > *elim) { goto L60; } if(kdflg == 1) { kflag = 2; } if(abs(rs1) < *alim) { goto L40; } /* ----------------------------------------------------------------------- */ /* REFINE TEST AND SCALE */ /* ----------------------------------------------------------------------- */ aphi = c_abs(&phi[j - 1]); aarg = c_abs(&arg[j - 1]); rs1 = rs1 + log(aphi) - log(aarg) * (float).25 - aic; if(abs(rs1) > *elim) { goto L60; } if(kdflg == 1) { kflag = 1; } if(rs1 < (float)0.) { goto L40; } if(kdflg == 1) { kflag = 3; } L40: /* ----------------------------------------------------------------------- */ /* SCALE S1 TO KEEP INTERMEDIATE ARITHMETIC ON SCALE NEAR */ /* EXPONENT EXTREMES */ /* ----------------------------------------------------------------------- */ i__2 = j - 1; q__1.real() = arg[i__2].real() * cr2.real() - arg[i__2].imag() * cr2.imag(), q__1.imag() = arg[i__2].real() * cr2.imag() + arg[i__2].imag() * cr2.real(); c2.real() = q__1.real(), c2.imag() = q__1.imag(); cairy_(&c2, &c__0, &c__2, &ai, &nai, &idum); cairy_(&c2, &c__1, &c__2, &dai, &ndai, &idum); i__2 = j - 1; q__2.real() = cs.real() * phi[i__2].real() - cs.imag() * phi[i__2].imag(), q__2.imag() = cs.real() * phi[i__2].imag() + cs.imag() * phi[i__2].real(); i__3 = j - 1; q__4.real() = ai.real() * asum[i__3].real() - ai.imag() * asum[i__3].imag(), q__4.imag() = ai.real() * asum[i__3].imag() + ai.imag() * asum[i__3].real(); q__6.real() = cr2.real() * dai.real() - cr2.imag() * dai.imag(), q__6.imag() = cr2.real() * dai.imag() + cr2.imag() * dai.real(); i__4 = j - 1; q__5.real() = q__6.real() * bsum[i__4].real() - q__6.imag() * bsum[i__4].imag(), q__5.imag() = q__6.real() * bsum[i__4].imag() + q__6.imag() * bsum[i__4].real(); q__3.real() = q__4.real() + q__5.real(), q__3.imag() = q__4.imag() + q__5.imag(); q__1.real() = q__2.real() * q__3.real() - q__2.imag() * q__3.imag(), q__1.imag() = q__2.real() * q__3.imag() + q__2.imag() * q__3.real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); c2r = s1.real(); c2i = r_imag(&s1); i__2 = kflag - 1; c2m = exp(c2r) * css[i__2].real(); q__2.real() = c2m, q__2.imag() = (float)0.; r__1 = cos(c2i); r__2 = sin(c2i); q__3.real() = r__1, q__3.imag() = r__2; q__1.real() = q__2.real() * q__3.real() - q__2.imag() * q__3.imag(), q__1.imag() = q__2.real() * q__3.imag() + q__2.imag() * q__3.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); q__1.real() = s2.real() * s1.real() - s2.imag() * s1.imag(), q__1.imag() = s2.real() * s1.imag() + s2.imag() * s1.real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); if(kflag != 1) { goto L50; } cuchk_(&s2, &nw, bry, tol); if(nw != 0) { goto L60; } L50: if(yy <= (float)0.) { r_cnjg(&q__1, &s2); s2.real() = q__1.real(), s2.imag() = q__1.imag(); } i__2 = kdflg - 1; cy[i__2].real() = s2.real(), cy[i__2].imag() = s2.imag(); i__2 = i__; i__3 = kflag - 1; q__1.real() = s2.real() * csr[i__3].real() - s2.imag() * csr[i__3].imag(), q__1.imag() = s2.real() * csr[i__3].imag() + s2.imag() * csr[i__3].real(); y[i__2].real() = q__1.real(), y[i__2].imag() = q__1.imag(); q__2.real() = -ci.real(), q__2.imag() = -ci.imag(); q__1.real() = q__2.real() * cs.real() - q__2.imag() * cs.imag(), q__1.imag() = q__2.real() * cs.imag() + q__2.imag() * cs.real(); cs.real() = q__1.real(), cs.imag() = q__1.imag(); if(kdflg == 2) { goto L75; } kdflg = 2; goto L70; L60: if(rs1 > (float)0.) { goto L300; } /* ----------------------------------------------------------------------- */ /* FOR X.LT.0.0, THE I FUNCTION TO BE ADDED WILL OVERFLOW */ /* ----------------------------------------------------------------------- */ if(x < (float)0.) { goto L300; } kdflg = 1; i__2 = i__; y[i__2].real() = czero.real(), y[i__2].imag() = czero.imag(); q__2.real() = -ci.real(), q__2.imag() = -ci.imag(); q__1.real() = q__2.real() * cs.real() - q__2.imag() * cs.imag(), q__1.imag() = q__2.real() * cs.imag() + q__2.imag() * cs.real(); cs.real() = q__1.real(), cs.imag() = q__1.imag(); ++(*nz); if(i__ == 1) { goto L70; } i__2 = i__ - 1; if(y[i__2].real() == czero.real() && y[i__2].imag() == czero.imag()) { goto L70; } i__2 = i__ - 1; y[i__2].real() = czero.real(), y[i__2].imag() = czero.imag(); ++(*nz); L70:; } i__ = *n; L75: c_div(&q__1, &c_b17, &zr); rz.real() = q__1.real(), rz.imag() = q__1.imag(); q__2.real() = fn, q__2.imag() = (float)0.; q__1.real() = q__2.real() * rz.real() - q__2.imag() * rz.imag(), q__1.imag() = q__2.real() * rz.imag() + q__2.imag() * rz.real(); ck.real() = q__1.real(), ck.imag() = q__1.imag(); ib = i__ + 1; if(*n < ib) { goto L170; } /* ----------------------------------------------------------------------- */ /* TEST LAST MEMBER FOR UNDERFLOW AND OVERFLOW, SET SEQUENCE TO ZERO */ /* ON UNDERFLOW */ /* ----------------------------------------------------------------------- */ fn = *fnu + (float)(*n - 1); ipard = 1; if(*mr != 0) { ipard = 0; } cunhj_(&zn, &fn, &ipard, tol, &phid, &argd, &zeta1d, &zeta2d, &asumd, &bsumd); if(*kode == 1) { goto L80; } q__1.real() = fn, q__1.imag() = (float)0.; cfn.real() = q__1.real(), cfn.imag() = q__1.imag(); q__4.real() = zb.real() + zeta2d.real(), q__4.imag() = zb.imag() + zeta2d.imag(); c_div(&q__3, &cfn, &q__4); q__2.real() = cfn.real() * q__3.real() - cfn.imag() * q__3.imag(), q__2.imag() = cfn.real() * q__3.imag() + cfn.imag() * q__3.real(); q__1.real() = zeta1d.real() - q__2.real(), q__1.imag() = zeta1d.imag() - q__2.imag(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); goto L90; L80: q__1.real() = zeta1d.real() - zeta2d.real(), q__1.imag() = zeta1d.imag() - zeta2d.imag(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); L90: rs1 = s1.real(); if(abs(rs1) > *elim) { goto L95; } if(abs(rs1) < *alim) { goto L100; } /* ----------------------------------------------------------------------- */ /* REFINE ESTIMATE AND TEST */ /* ----------------------------------------------------------------------- */ aphi = c_abs(&phid); aarg = c_abs(&argd); rs1 = rs1 + log(aphi) - log(aarg) * (float).25 - aic; if(abs(rs1) < *elim) { goto L100; } L95: if(rs1 > (float)0.) { goto L300; } /* ----------------------------------------------------------------------- */ /* FOR X.LT.0.0, THE I FUNCTION TO BE ADDED WILL OVERFLOW */ /* ----------------------------------------------------------------------- */ if(x < (float)0.) { goto L300; } *nz = *n; i__1 = *n; for(i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; y[i__2].real() = czero.real(), y[i__2].imag() = czero.imag(); /* L96: */ } return 0; L100: /* ----------------------------------------------------------------------- */ /* SCALED FORWARD RECURRENCE FOR REMAINDER OF THE SEQUENCE */ /* ----------------------------------------------------------------------- */ s1.real() = cy[0].real(), s1.imag() = cy[0].imag(); s2.real() = cy[1].real(), s2.imag() = cy[1].imag(); i__1 = kflag - 1; c1.real() = csr[i__1].real(), c1.imag() = csr[i__1].imag(); ascle = bry[kflag - 1]; i__1 = *n; for(i__ = ib; i__ <= i__1; ++i__) { c2.real() = s2.real(), c2.imag() = s2.imag(); q__2.real() = ck.real() * s2.real() - ck.imag() * s2.imag(), q__2.imag() = ck.real() * s2.imag() + ck.imag() * s2.real(); q__1.real() = q__2.real() + s1.real(), q__1.imag() = q__2.imag() + s1.imag(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); s1.real() = c2.real(), s1.imag() = c2.imag(); q__1.real() = ck.real() + rz.real(), q__1.imag() = ck.imag() + rz.imag(); ck.real() = q__1.real(), ck.imag() = q__1.imag(); q__1.real() = s2.real() * c1.real() - s2.imag() * c1.imag(), q__1.imag() = s2.real() * c1.imag() + s2.imag() * c1.real(); c2.real() = q__1.real(), c2.imag() = q__1.imag(); i__2 = i__; y[i__2].real() = c2.real(), y[i__2].imag() = c2.imag(); if(kflag >= 3) { goto L120; } c2r = c2.real(); c2i = r_imag(&c2); c2r = abs(c2r); c2i = abs(c2i); c2m = max(c2r, c2i); if(c2m <= ascle) { goto L120; } ++kflag; ascle = bry[kflag - 1]; q__1.real() = s1.real() * c1.real() - s1.imag() * c1.imag(), q__1.imag() = s1.real() * c1.imag() + s1.imag() * c1.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); s2.real() = c2.real(), s2.imag() = c2.imag(); i__2 = kflag - 1; q__1.real() = s1.real() * css[i__2].real() - s1.imag() * css[i__2].imag(), q__1.imag() = s1.real() * css[i__2].imag() + s1.imag() * css[i__2].real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); i__2 = kflag - 1; q__1.real() = s2.real() * css[i__2].real() - s2.imag() * css[i__2].imag(), q__1.imag() = s2.real() * css[i__2].imag() + s2.imag() * css[i__2].real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); i__2 = kflag - 1; c1.real() = csr[i__2].real(), c1.imag() = csr[i__2].imag(); L120:; } L170: if(*mr == 0) { return 0; } /* ----------------------------------------------------------------------- */ /* ANALYTIC CONTINUATION FOR RE(Z).LT.0.0E0 */ /* ----------------------------------------------------------------------- */ *nz = 0; fmr = (float)(*mr); sgn = -r_sign(&pi, &fmr); /* ----------------------------------------------------------------------- */ /* CSPN AND CSGN ARE COEFF OF K AND I FUNCTIONS RESP. */ /* ----------------------------------------------------------------------- */ q__1.real() = (float)0., q__1.imag() = sgn; csgn.real() = q__1.real(), csgn.imag() = q__1.imag(); if(yy <= (float)0.) { r_cnjg(&q__1, &csgn); csgn.real() = q__1.real(), csgn.imag() = q__1.imag(); } ifn = inu + *n - 1; ang = fnf * sgn; cpn = cos(ang); spn = sin(ang); q__1.real() = cpn, q__1.imag() = spn; cspn.real() = q__1.real(), cspn.imag() = q__1.imag(); if(ifn % 2 == 1) { q__1.real() = -cspn.real(), q__1.imag() = -cspn.imag(); cspn.real() = q__1.real(), cspn.imag() = q__1.imag(); } /* ----------------------------------------------------------------------- */ /* CS=COEFF OF THE J FUNCTION TO GET THE I FUNCTION. I(FNU,Z) IS */ /* COMPUTED FROM EXP(I*FNU*HPI)*J(FNU,-I*Z) WHERE Z IS IN THE FIRST */ /* QUADRANT. FOURTH QUADRANT VALUES (YY.LE.0.0E0) ARE COMPUTED BY */ /* CONJUGATION SINCE THE I FUNCTION IS REAL ON THE POSITIVE REAL AXIS */ /* ----------------------------------------------------------------------- */ r__1 = -sar; q__2.real() = car, q__2.imag() = r__1; q__1.real() = q__2.real() * csgn.real() - q__2.imag() * csgn.imag(), q__1.imag() = q__2.real() * csgn.imag() + q__2.imag() * csgn.real(); cs.real() = q__1.real(), cs.imag() = q__1.imag(); in = ifn % 4 + 1; i__1 = in - 1; c2.real() = cip[i__1].real(), c2.imag() = cip[i__1].imag(); r_cnjg(&q__2, &c2); q__1.real() = cs.real() * q__2.real() - cs.imag() * q__2.imag(), q__1.imag() = cs.real() * q__2.imag() + cs.imag() * q__2.real(); cs.real() = q__1.real(), cs.imag() = q__1.imag(); asc = bry[0]; kk = *n; kdflg = 1; --ib; ic = ib - 1; iuf = 0; i__1 = *n; for(k = 1; k <= i__1; ++k) { /* ----------------------------------------------------------------------- */ /* LOGIC TO SORT OUT CASES WHOSE PARAMETERS WERE SET FOR THE K */ /* FUNCTION ABOVE */ /* ----------------------------------------------------------------------- */ fn = *fnu + (float)(kk - 1); if(*n > 2) { goto L180; } L175: i__2 = j - 1; phid.real() = phi[i__2].real(), phid.imag() = phi[i__2].imag(); i__2 = j - 1; argd.real() = arg[i__2].real(), argd.imag() = arg[i__2].imag(); i__2 = j - 1; zeta1d.real() = zeta1[i__2].real(), zeta1d.imag() = zeta1[i__2].imag(); i__2 = j - 1; zeta2d.real() = zeta2[i__2].real(), zeta2d.imag() = zeta2[i__2].imag(); i__2 = j - 1; asumd.real() = asum[i__2].real(), asumd.imag() = asum[i__2].imag(); i__2 = j - 1; bsumd.real() = bsum[i__2].real(), bsumd.imag() = bsum[i__2].imag(); j = 3 - j; goto L190; L180: if(kk == *n && ib < *n) { goto L190; } if(kk == ib || kk == ic) { goto L175; } cunhj_(&zn, &fn, &c__0, tol, &phid, &argd, &zeta1d, &zeta2d, &asumd, &bsumd); L190: if(*kode == 1) { goto L200; } q__1.real() = fn, q__1.imag() = (float)0.; cfn.real() = q__1.real(), cfn.imag() = q__1.imag(); q__2.real() = -zeta1d.real(), q__2.imag() = -zeta1d.imag(); q__5.real() = zb.real() + zeta2d.real(), q__5.imag() = zb.imag() + zeta2d.imag(); c_div(&q__4, &cfn, &q__5); q__3.real() = cfn.real() * q__4.real() - cfn.imag() * q__4.imag(), q__3.imag() = cfn.real() * q__4.imag() + cfn.imag() * q__4.real(); q__1.real() = q__2.real() + q__3.real(), q__1.imag() = q__2.imag() + q__3.imag(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); goto L210; L200: q__2.real() = -zeta1d.real(), q__2.imag() = -zeta1d.imag(); q__1.real() = q__2.real() + zeta2d.real(), q__1.imag() = q__2.imag() + zeta2d.imag(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); L210: /* ----------------------------------------------------------------------- */ /* TEST FOR UNDERFLOW AND OVERFLOW */ /* ----------------------------------------------------------------------- */ rs1 = s1.real(); if(abs(rs1) > *elim) { goto L260; } if(kdflg == 1) { iflag = 2; } if(abs(rs1) < *alim) { goto L220; } /* ----------------------------------------------------------------------- */ /* REFINE TEST AND SCALE */ /* ----------------------------------------------------------------------- */ aphi = c_abs(&phid); aarg = c_abs(&argd); rs1 = rs1 + log(aphi) - log(aarg) * (float).25 - aic; if(abs(rs1) > *elim) { goto L260; } if(kdflg == 1) { iflag = 1; } if(rs1 < (float)0.) { goto L220; } if(kdflg == 1) { iflag = 3; } L220: cairy_(&argd, &c__0, &c__2, &ai, &nai, &idum); cairy_(&argd, &c__1, &c__2, &dai, &ndai, &idum); q__2.real() = cs.real() * phid.real() - cs.imag() * phid.imag(), q__2.imag() = cs.real() * phid.imag() + cs.imag() * phid.real(); q__4.real() = ai.real() * asumd.real() - ai.imag() * asumd.imag(), q__4.imag() = ai.real() * asumd.imag() + ai.imag() * asumd.real(); q__5.real() = dai.real() * bsumd.real() - dai.imag() * bsumd.imag(), q__5.imag() = dai.real() * bsumd.imag() + dai.imag() * bsumd.real(); q__3.real() = q__4.real() + q__5.real(), q__3.imag() = q__4.imag() + q__5.imag(); q__1.real() = q__2.real() * q__3.real() - q__2.imag() * q__3.imag(), q__1.imag() = q__2.real() * q__3.imag() + q__2.imag() * q__3.real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); c2r = s1.real(); c2i = r_imag(&s1); i__2 = iflag - 1; c2m = exp(c2r) * css[i__2].real(); q__2.real() = c2m, q__2.imag() = (float)0.; r__1 = cos(c2i); r__2 = sin(c2i); q__3.real() = r__1, q__3.imag() = r__2; q__1.real() = q__2.real() * q__3.real() - q__2.imag() * q__3.imag(), q__1.imag() = q__2.real() * q__3.imag() + q__2.imag() * q__3.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); q__1.real() = s2.real() * s1.real() - s2.imag() * s1.imag(), q__1.imag() = s2.real() * s1.imag() + s2.imag() * s1.real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); if(iflag != 1) { goto L230; } cuchk_(&s2, &nw, bry, tol); if(nw != 0) { s2.real() = (float)0., s2.imag() = (float)0.; } L230: if(yy <= (float)0.) { r_cnjg(&q__1, &s2); s2.real() = q__1.real(), s2.imag() = q__1.imag(); } i__2 = kdflg - 1; cy[i__2].real() = s2.real(), cy[i__2].imag() = s2.imag(); c2.real() = s2.real(), c2.imag() = s2.imag(); i__2 = iflag - 1; q__1.real() = s2.real() * csr[i__2].real() - s2.imag() * csr[i__2].imag(), q__1.imag() = s2.real() * csr[i__2].imag() + s2.imag() * csr[i__2].real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); /* ----------------------------------------------------------------------- */ /* ADD I AND K FUNCTIONS, K SEQUENCE IN Y(I), I=1,N */ /* ----------------------------------------------------------------------- */ i__2 = kk; s1.real() = y[i__2].real(), s1.imag() = y[i__2].imag(); if(*kode == 1) { goto L250; } cs1s2_(&zr, &s1, &s2, &nw, &asc, alim, &iuf); *nz += nw; L250: i__2 = kk; q__2.real() = s1.real() * cspn.real() - s1.imag() * cspn.imag(), q__2.imag() = s1.real() * cspn.imag() + s1.imag() * cspn.real(); q__1.real() = q__2.real() + s2.real(), q__1.imag() = q__2.imag() + s2.imag(); y[i__2].real() = q__1.real(), y[i__2].imag() = q__1.imag(); --kk; q__1.real() = -cspn.real(), q__1.imag() = -cspn.imag(); cspn.real() = q__1.real(), cspn.imag() = q__1.imag(); q__2.real() = -cs.real(), q__2.imag() = -cs.imag(); q__1.real() = q__2.real() * ci.real() - q__2.imag() * ci.imag(), q__1.imag() = q__2.real() * ci.imag() + q__2.imag() * ci.real(); cs.real() = q__1.real(), cs.imag() = q__1.imag(); if(c2.real() != czero.real() || c2.imag() != czero.imag()) { goto L255; } kdflg = 1; goto L270; L255: if(kdflg == 2) { goto L275; } kdflg = 2; goto L270; L260: if(rs1 > (float)0.) { goto L300; } s2.real() = czero.real(), s2.imag() = czero.imag(); goto L230; L270:; } k = *n; L275: il = *n - k; if(il == 0) { return 0; } /* ----------------------------------------------------------------------- */ /* RECUR BACKWARD FOR REMAINDER OF I SEQUENCE AND ADD IN THE */ /* K FUNCTIONS, SCALING THE I SEQUENCE DURING RECURRENCE TO KEEP */ /* INTERMEDIATE ARITHMETIC ON SCALE NEAR EXPONENT EXTREMES. */ /* ----------------------------------------------------------------------- */ s1.real() = cy[0].real(), s1.imag() = cy[0].imag(); s2.real() = cy[1].real(), s2.imag() = cy[1].imag(); i__1 = iflag - 1; cs.real() = csr[i__1].real(), cs.imag() = csr[i__1].imag(); ascle = bry[iflag - 1]; fn = (float)(inu + il); i__1 = il; for(i__ = 1; i__ <= i__1; ++i__) { c2.real() = s2.real(), c2.imag() = s2.imag(); r__1 = fn + fnf; q__4.real() = r__1, q__4.imag() = (float)0.; q__3.real() = q__4.real() * rz.real() - q__4.imag() * rz.imag(), q__3.imag() = q__4.real() * rz.imag() + q__4.imag() * rz.real(); q__2.real() = q__3.real() * s2.real() - q__3.imag() * s2.imag(), q__2.imag() = q__3.real() * s2.imag() + q__3.imag() * s2.real(); q__1.real() = s1.real() + q__2.real(), q__1.imag() = s1.imag() + q__2.imag(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); s1.real() = c2.real(), s1.imag() = c2.imag(); fn += (float)-1.; q__1.real() = s2.real() * cs.real() - s2.imag() * cs.imag(), q__1.imag() = s2.real() * cs.imag() + s2.imag() * cs.real(); c2.real() = q__1.real(), c2.imag() = q__1.imag(); ck.real() = c2.real(), ck.imag() = c2.imag(); i__2 = kk; c1.real() = y[i__2].real(), c1.imag() = y[i__2].imag(); if(*kode == 1) { goto L280; } cs1s2_(&zr, &c1, &c2, &nw, &asc, alim, &iuf); *nz += nw; L280: i__2 = kk; q__2.real() = c1.real() * cspn.real() - c1.imag() * cspn.imag(), q__2.imag() = c1.real() * cspn.imag() + c1.imag() * cspn.real(); q__1.real() = q__2.real() + c2.real(), q__1.imag() = q__2.imag() + c2.imag(); y[i__2].real() = q__1.real(), y[i__2].imag() = q__1.imag(); --kk; q__1.real() = -cspn.real(), q__1.imag() = -cspn.imag(); cspn.real() = q__1.real(), cspn.imag() = q__1.imag(); if(iflag >= 3) { goto L290; } c2r = ck.real(); c2i = r_imag(&ck); c2r = abs(c2r); c2i = abs(c2i); c2m = max(c2r, c2i); if(c2m <= ascle) { goto L290; } ++iflag; ascle = bry[iflag - 1]; q__1.real() = s1.real() * cs.real() - s1.imag() * cs.imag(), q__1.imag() = s1.real() * cs.imag() + s1.imag() * cs.real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); s2.real() = ck.real(), s2.imag() = ck.imag(); i__2 = iflag - 1; q__1.real() = s1.real() * css[i__2].real() - s1.imag() * css[i__2].imag(), q__1.imag() = s1.real() * css[i__2].imag() + s1.imag() * css[i__2].real(); s1.real() = q__1.real(), s1.imag() = q__1.imag(); i__2 = iflag - 1; q__1.real() = s2.real() * css[i__2].real() - s2.imag() * css[i__2].imag(), q__1.imag() = s2.real() * css[i__2].imag() + s2.imag() * css[i__2].real(); s2.real() = q__1.real(), s2.imag() = q__1.imag(); i__2 = iflag - 1; cs.real() = csr[i__2].real(), cs.imag() = csr[i__2].imag(); L290:; } return 0; L300: *nz = -1; return 0; } /* cunk2_ */ int cuoik_(System::Complex<float>* z__, float* fnu, int32* kode, int32* ikflg, int32* n, System::Complex<float>* y, int32* nuf, float* tol, float* elim, float* alim) { /* Initialized data */ static System::Complex<float> czero = {(float)0., (float)0.}; static float aic = (float)1.265512123484645396; /* System generated locals */ int32 i__1, i__2; float r__1, r__2; System::Complex<float> q__1, q__2, q__3, q__4, q__5; int32 i__; float x, ax, ay; System::Complex<float> zb, cz; int32 nn, nw; System::Complex<float> zn, zr; float yy; System::Complex<float> arg, phi; float fnn, gnn, gnu, rcz; System::Complex<float> sum; float aarg, aphi; int32 init; System::Complex<float> asum, bsum, cwrk[16], zeta1, zeta2; float ascle; int32 iform; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE CUOIK */ /* ***REFER TO CBESI,CBESK,CBESH */ /* CUOIK COMPUTES THE LEADING TERMS OF THE UNIFORM ASYMPTOTIC */ /* EXPANSIONS FOR THE I AND K FUNCTIONS AND COMPARES THEM */ /* (IN LOGARITHMIC FORM) TO ALIM AND ELIM FOR OVER AND UNDERFLOW */ /* WHERE ALIM.LT.ELIM. IF THE MAGNITUDE, BASED ON THE LEADING */ /* EXPONENTIAL, IS LESS THAN ALIM OR GREATER THAN -ALIM, THEN */ /* THE RESULT IS ON SCALE. IF NOT, THEN A REFINED TEST USING OTHER */ /* MULTIPLIERS (IN LOGARITHMIC FORM) IS MADE BASED ON ELIM. HERE */ /* EXP(-ELIM)=SMALLEST MACHINE NUMBER*1.0E+3 AND EXP(-ALIM)= */ /* EXP(-ELIM)/TOL */ /* IKFLG=1 MEANS THE I SEQUENCE IS TESTED */ /* =2 MEANS THE K SEQUENCE IS TESTED */ /* NUF = 0 MEANS THE LAST MEMBER OF THE SEQUENCE IS ON SCALE */ /* =-1 MEANS AN OVERFLOW WOULD OCCUR */ /* IKFLG=1 AND NUF.GT.0 MEANS THE LAST NUF Y VALUES WERE SET TO ZERO */ /* THE FIRST N-NUF VALUES MUST BE SET BY ANOTHER ROUTINE */ /* IKFLG=2 AND NUF.EQ.N MEANS ALL Y VALUES WERE SET TO ZERO */ /* IKFLG=2 AND 0.LT.NUF.LT.N NOT CONSIDERED. Y MUST BE SET BY */ /* ANOTHER ROUTINE */ /* ***ROUTINES CALLED CUCHK,CUNHJ,CUNIK,R1MACH */ /* ***END PROLOGUE CUOIK */ /* Parameter adjustments */ --y; /* Function Body */ *nuf = 0; nn = *n; x = z__->real(); zr.real() = z__->real(), zr.imag() = z__->imag(); if(x < (float)0.) { q__1.real() = -z__->real(), q__1.imag() = -z__->imag(); zr.real() = q__1.real(), zr.imag() = q__1.imag(); } zb.real() = zr.real(), zb.imag() = zr.imag(); yy = r_imag(&zr); ax = abs(x) * (float)1.7321; ay = abs(yy); iform = 1; if(ay > ax) { iform = 2; } gnu = max(*fnu, (float)1.); if(*ikflg == 1) { goto L10; } fnn = (float)nn; gnn = *fnu + fnn - (float)1.; gnu = max(gnn, fnn); L10: /* ----------------------------------------------------------------------- */ /* ONLY THE MAGNITUDE OF ARG AND PHI ARE NEEDED ALONG WITH THE */ /* REAL PARTS OF ZETA1, ZETA2 AND ZB. NO ATTEMPT IS MADE TO GET */ /* THE SIGN OF THE IMAGINARY PART CORRECT. */ /* ----------------------------------------------------------------------- */ if(iform == 2) { goto L20; } init = 0; cunik_(&zr, &gnu, ikflg, &c__1, tol, &init, &phi, &zeta1, &zeta2, &sum, cwrk); q__2.real() = -zeta1.real(), q__2.imag() = -zeta1.imag(); q__1.real() = q__2.real() + zeta2.real(), q__1.imag() = q__2.imag() + zeta2.imag(); cz.real() = q__1.real(), cz.imag() = q__1.imag(); goto L40; L20: q__2.real() = -zr.real(), q__2.imag() = -zr.imag(); q__1.real() = q__2.real() * (float)0. - q__2.imag() * (float)1., q__1.imag() = q__2.real() * (float)1. + q__2.imag() * (float)0.; zn.real() = q__1.real(), zn.imag() = q__1.imag(); if(yy > (float)0.) { goto L30; } q__2.real() = -zn.real(), q__2.imag() = -zn.imag(); r_cnjg(&q__1, &q__2); zn.real() = q__1.real(), zn.imag() = q__1.imag(); L30: cunhj_(&zn, &gnu, &c__1, tol, &phi, &arg, &zeta1, &zeta2, &asum, &bsum); q__2.real() = -zeta1.real(), q__2.imag() = -zeta1.imag(); q__1.real() = q__2.real() + zeta2.real(), q__1.imag() = q__2.imag() + zeta2.imag(); cz.real() = q__1.real(), cz.imag() = q__1.imag(); aarg = c_abs(&arg); L40: if(*kode == 2) { q__1.real() = cz.real() - zb.real(), q__1.imag() = cz.imag() - zb.imag(); cz.real() = q__1.real(), cz.imag() = q__1.imag(); } if(*ikflg == 2) { q__1.real() = -cz.real(), q__1.imag() = -cz.imag(); cz.real() = q__1.real(), cz.imag() = q__1.imag(); } aphi = c_abs(&phi); rcz = cz.real(); /* ----------------------------------------------------------------------- */ /* OVERFLOW TEST */ /* ----------------------------------------------------------------------- */ if(rcz > *elim) { goto L170; } if(rcz < *alim) { goto L50; } rcz += log(aphi); if(iform == 2) { rcz = rcz - log(aarg) * (float).25 - aic; } if(rcz > *elim) { goto L170; } goto L100; L50: /* ----------------------------------------------------------------------- */ /* UNDERFLOW TEST */ /* ----------------------------------------------------------------------- */ if(rcz < -(*elim)) { goto L60; } if(rcz > -(*alim)) { goto L100; } rcz += log(aphi); if(iform == 2) { rcz = rcz - log(aarg) * (float).25 - aic; } if(rcz > -(*elim)) { goto L80; } L60: i__1 = nn; for(i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; y[i__2].real() = czero.real(), y[i__2].imag() = czero.imag(); /* L70: */ } *nuf = nn; return 0; L80: ascle = r1mach_(&c__1) * (float)1e3 / *tol; c_log(&q__2, &phi); q__1.real() = cz.real() + q__2.real(), q__1.imag() = cz.imag() + q__2.imag(); cz.real() = q__1.real(), cz.imag() = q__1.imag(); if(iform == 1) { goto L90; } c_log(&q__4, &arg); q__3.real() = q__4.real() * (float).25 - q__4.imag() * (float)0., q__3.imag() = q__4.real() * (float)0. + q__4.imag() * (float).25; q__2.real() = cz.real() - q__3.real(), q__2.imag() = cz.imag() - q__3.imag(); q__5.real() = aic, q__5.imag() = (float)0.; q__1.real() = q__2.real() - q__5.real(), q__1.imag() = q__2.imag() - q__5.imag(); cz.real() = q__1.real(), cz.imag() = q__1.imag(); L90: ax = exp(rcz) / *tol; ay = r_imag(&cz); q__2.real() = ax, q__2.imag() = (float)0.; r__1 = cos(ay); r__2 = sin(ay); q__3.real() = r__1, q__3.imag() = r__2; q__1.real() = q__2.real() * q__3.real() - q__2.imag() * q__3.imag(), q__1.imag() = q__2.real() * q__3.imag() + q__2.imag() * q__3.real(); cz.real() = q__1.real(), cz.imag() = q__1.imag(); cuchk_(&cz, &nw, &ascle, tol); if(nw == 1) { goto L60; } L100: if(*ikflg == 2) { return 0; } if(*n == 1) { return 0; } /* ----------------------------------------------------------------------- */ /* SET UNDERFLOWS ON I SEQUENCE */ /* ----------------------------------------------------------------------- */ L110: gnu = *fnu + (float)(nn - 1); if(iform == 2) { goto L120; } init = 0; cunik_(&zr, &gnu, ikflg, &c__1, tol, &init, &phi, &zeta1, &zeta2, &sum, cwrk); q__2.real() = -zeta1.real(), q__2.imag() = -zeta1.imag(); q__1.real() = q__2.real() + zeta2.real(), q__1.imag() = q__2.imag() + zeta2.imag(); cz.real() = q__1.real(), cz.imag() = q__1.imag(); goto L130; L120: cunhj_(&zn, &gnu, &c__1, tol, &phi, &arg, &zeta1, &zeta2, &asum, &bsum); q__2.real() = -zeta1.real(), q__2.imag() = -zeta1.imag(); q__1.real() = q__2.real() + zeta2.real(), q__1.imag() = q__2.imag() + zeta2.imag(); cz.real() = q__1.real(), cz.imag() = q__1.imag(); aarg = c_abs(&arg); L130: if(*kode == 2) { q__1.real() = cz.real() - zb.real(), q__1.imag() = cz.imag() - zb.imag(); cz.real() = q__1.real(), cz.imag() = q__1.imag(); } aphi = c_abs(&phi); rcz = cz.real(); if(rcz < -(*elim)) { goto L140; } if(rcz > -(*alim)) { return 0; } rcz += log(aphi); if(iform == 2) { rcz = rcz - log(aarg) * (float).25 - aic; } if(rcz > -(*elim)) { goto L150; } L140: i__1 = nn; y[i__1].real() = czero.real(), y[i__1].imag() = czero.imag(); --nn; ++(*nuf); if(nn == 0) { return 0; } goto L110; L150: ascle = r1mach_(&c__1) * (float)1e3 / *tol; c_log(&q__2, &phi); q__1.real() = cz.real() + q__2.real(), q__1.imag() = cz.imag() + q__2.imag(); cz.real() = q__1.real(), cz.imag() = q__1.imag(); if(iform == 1) { goto L160; } c_log(&q__4, &arg); q__3.real() = q__4.real() * (float).25 - q__4.imag() * (float)0., q__3.imag() = q__4.real() * (float)0. + q__4.imag() * (float).25; q__2.real() = cz.real() - q__3.real(), q__2.imag() = cz.imag() - q__3.imag(); q__5.real() = aic, q__5.imag() = (float)0.; q__1.real() = q__2.real() - q__5.real(), q__1.imag() = q__2.imag() - q__5.imag(); cz.real() = q__1.real(), cz.imag() = q__1.imag(); L160: ax = exp(rcz) / *tol; ay = r_imag(&cz); q__2.real() = ax, q__2.imag() = (float)0.; r__1 = cos(ay); r__2 = sin(ay); q__3.real() = r__1, q__3.imag() = r__2; q__1.real() = q__2.real() * q__3.real() - q__2.imag() * q__3.imag(), q__1.imag() = q__2.real() * q__3.imag() + q__2.imag() * q__3.real(); cz.real() = q__1.real(), cz.imag() = q__1.imag(); cuchk_(&cz, &nw, &ascle, tol); if(nw == 1) { goto L140; } return 0; L170: *nuf = -1; return 0; } /* cuoik_ */ int cwrsk_(System::Complex<float>* zr, float* fnu, int32* kode, int32* n, System::Complex<float>* y, int32* nz, System::Complex<float>* cw, float* tol, float* elim, float* alim) { /* System generated locals */ int32 i__1, i__2; float r__1; System::Complex<float> q__1, q__2, q__3; int32 i__; System::Complex<float> c1, c2; float s1, s2; System::Complex<float> ct; int32 nw; System::Complex<float> st; float yy, act, acw; System::Complex<float> rct, cscl, cinu; float ascle; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE CWRSK */ /* ***REFER TO CBESI,CBESK */ /* CWRSK COMPUTES THE I BESSEL FUNCTION FOR RE(Z).GE.0.0 BY */ /* NORMALIZING THE I FUNCTION RATIOS FROM CRATI BY THE WRONSKIAN */ /* ***ROUTINES CALLED CBKNU,CRATI,R1MACH */ /* ***END PROLOGUE CWRSK */ /* ----------------------------------------------------------------------- */ /* I(FNU+I-1,Z) BY BACKWARD RECURRENCE FOR RATIOS */ /* Y(I)=I(FNU+I,Z)/I(FNU+I-1,Z) FROM CRATI NORMALIZED BY THE */ /* WRONSKIAN WITH K(FNU,Z) AND K(FNU+1,Z) FROM CBKNU. */ /* ----------------------------------------------------------------------- */ /* Parameter adjustments */ --y; --cw; /* Function Body */ *nz = 0; cbknu_(zr, fnu, kode, &c__2, &cw[1], &nw, tol, elim, alim); if(nw != 0) { goto L50; } crati_(zr, fnu, n, &y[1], tol); /* ----------------------------------------------------------------------- */ /* RECUR FORWARD ON I(FNU+1,Z) = R(FNU,Z)*I(FNU,Z), */ /* R(FNU+J-1,Z)=Y(J), J=1,...,N */ /* ----------------------------------------------------------------------- */ cinu.real() = (float)1., cinu.imag() = (float)0.; if(*kode == 1) { goto L10; } yy = r_imag(zr); s1 = cos(yy); s2 = sin(yy); q__1.real() = s1, q__1.imag() = s2; cinu.real() = q__1.real(), cinu.imag() = q__1.imag(); L10: /* ----------------------------------------------------------------------- */ /* ON LOW EXPONENT MACHINES THE K FUNCTIONS CAN BE CLOSE TO BOTH */ /* THE UNDER AND OVERFLOW LIMITS AND THE NORMALIZATION MUST BE */ /* SCALED TO PREVENT OVER OR UNDERFLOW. CUOIK HAS DETERMINED THAT */ /* THE RESULT IS ON SCALE. */ /* ----------------------------------------------------------------------- */ acw = c_abs(&cw[2]); ascle = r1mach_(&c__1) * (float)1e3 / *tol; cscl.real() = (float)1., cscl.imag() = (float)0.; if(acw > ascle) { goto L20; } r__1 = (float)1. / *tol; q__1.real() = r__1, q__1.imag() = (float)0.; cscl.real() = q__1.real(), cscl.imag() = q__1.imag(); goto L30; L20: ascle = (float)1. / ascle; if(acw < ascle) { goto L30; } q__1.real() = *tol, q__1.imag() = (float)0.; cscl.real() = q__1.real(), cscl.imag() = q__1.imag(); L30: q__1.real() = cw[1].real() * cscl.real() - cw[1].imag() * cscl.imag(), q__1.imag() = cw[1].real() * cscl.imag() + cw[1].imag() * cscl.real(); c1.real() = q__1.real(), c1.imag() = q__1.imag(); q__1.real() = cw[2].real() * cscl.real() - cw[2].imag() * cscl.imag(), q__1.imag() = cw[2].real() * cscl.imag() + cw[2].imag() * cscl.real(); c2.real() = q__1.real(), c2.imag() = q__1.imag(); st.real() = y[1].real(), st.imag() = y[1].imag(); /* ----------------------------------------------------------------------- */ /* CINU=CINU*(CONJG(CT)/CABS(CT))*(1.0E0/CABS(CT) PREVENTS */ /* UNDER- OR OVERFLOW PREMATURELY BY SQUARING CABS(CT) */ /* ----------------------------------------------------------------------- */ q__3.real() = st.real() * c1.real() - st.imag() * c1.imag(), q__3.imag() = st.real() * c1.imag() + st.imag() * c1.real(); q__2.real() = c2.real() + q__3.real(), q__2.imag() = c2.imag() + q__3.imag(); q__1.real() = zr->real() * q__2.real() - zr->imag() * q__2.imag(), q__1.imag() = zr->real() * q__2.imag() + zr->imag() * q__2.real(); ct.real() = q__1.real(), ct.imag() = q__1.imag(); act = c_abs(&ct); r__1 = (float)1. / act; q__1.real() = r__1, q__1.imag() = (float)0.; rct.real() = q__1.real(), rct.imag() = q__1.imag(); r_cnjg(&q__2, &ct); q__1.real() = q__2.real() * rct.real() - q__2.imag() * rct.imag(), q__1.imag() = q__2.real() * rct.imag() + q__2.imag() * rct.real(); ct.real() = q__1.real(), ct.imag() = q__1.imag(); q__2.real() = cinu.real() * rct.real() - cinu.imag() * rct.imag(), q__2.imag() = cinu.real() * rct.imag() + cinu.imag() * rct.real(); q__1.real() = q__2.real() * ct.real() - q__2.imag() * ct.imag(), q__1.imag() = q__2.real() * ct.imag() + q__2.imag() * ct.real(); cinu.real() = q__1.real(), cinu.imag() = q__1.imag(); q__1.real() = cinu.real() * cscl.real() - cinu.imag() * cscl.imag(), q__1.imag() = cinu.real() * cscl.imag() + cinu.imag() * cscl.real(); y[1].real() = q__1.real(), y[1].imag() = q__1.imag(); if(*n == 1) { return 0; } i__1 = *n; for(i__ = 2; i__ <= i__1; ++i__) { q__1.real() = st.real() * cinu.real() - st.imag() * cinu.imag(), q__1.imag() = st.real() * cinu.imag() + st.imag() * cinu.real(); cinu.real() = q__1.real(), cinu.imag() = q__1.imag(); i__2 = i__; st.real() = y[i__2].real(), st.imag() = y[i__2].imag(); i__2 = i__; q__1.real() = cinu.real() * cscl.real() - cinu.imag() * cscl.imag(), q__1.imag() = cinu.real() * cscl.imag() + cinu.imag() * cscl.real(); y[i__2].real() = q__1.real(), y[i__2].imag() = q__1.imag(); /* L40: */ } return 0; L50: *nz = -1; if(nw == -2) { *nz = -2; } return 0; } /* cwrsk_ */ //double d1mach_(int32* i__) //{ // /* System generated locals */ // double ret_val; // cilist ci__1; // // /* Builtin functions */ // int32 s_wsfe(cilist*), do_fio(int32*, char*, ftnlen), e_wsfe(); // int s_stop(char*, ftnlen); // // /* *********************************************************************72 */ // // /* c D1MACH returns double precision float machine-dependent constants. */ // // /* Discussion: */ // // /* D1MACH can be used to obtain machine-dependent parameters */ // /* for the local machine environment. It is a function */ // /* with one input argument, and can be called as follows: */ // // /* D = D1MACH ( I ) */ // // /* where I=1,...,5. The output value of D above is */ // /* determined by the input value of I:. */ // // /* D1MACH ( 1) = B**(EMIN-1), the smallest positive magnitude. */ // /* D1MACH ( 2) = B**EMAX*(1 - B**(-T)), the largest magnitude. */ // /* D1MACH ( 3) = B**(-T), the smallest relative spacing. */ // /* D1MACH ( 4) = B**(1-T), the largest relative spacing. */ // /* D1MACH ( 5) = LOG10(B) */ // // /* Licensing: */ // // /* This code is distributed under the GNU LGPL license. */ // // /* Modified: */ // // /* 25 April 2007 */ // // /* Author: */ // // /* Original FORTRAN77 version by Phyllis Fox, Andrew Hall, Norman Schryer. */ // /* This FORTRAN77 version by John Burkardt. */ // // /* Reference: */ // // /* Phyllis Fox, Andrew Hall, Norman Schryer, */ // /* Algorithm 528: */ // /* Framework for a Portable Library, */ // /* ACM Transactions on Mathematical Software, */ // /* Volume 4, Number 2, June 1978, page 176-188. */ // // /* Parameters: */ // // /* Input, int32 I, the index of the desired constant. */ // // /* Output, double precision D1MACH, the value of the constant. */ // // if(*i__ < 1) // { // ci__1.cierr = 0; // ci__1.ciunit = 6; // ci__1.cifmt = "(a)"; // s_wsfe(&ci__1); // do_fio(&c__1, " ", (ftnlen)1); // e_wsfe(); // ci__1.cierr = 0; // ci__1.ciunit = 6; // ci__1.cifmt = "(a)"; // s_wsfe(&ci__1); // do_fio(&c__1, "D1MACH - Fatal error!", (ftnlen)21); // e_wsfe(); // ci__1.cierr = 0; // ci__1.ciunit = 6; // ci__1.cifmt = "(a)"; // s_wsfe(&ci__1); // do_fio(&c__1, " The input argument I is out of bounds.", (ftnlen)40); // e_wsfe(); // ci__1.cierr = 0; // ci__1.ciunit = 6; // ci__1.cifmt = "(a)"; // s_wsfe(&ci__1); // do_fio(&c__1, " Legal values satisfy 1 <= I <= 5.", (ftnlen)35); // e_wsfe(); // ci__1.cierr = 0; // ci__1.ciunit = 6; // ci__1.cifmt = "(a,i12)"; // s_wsfe(&ci__1); // do_fio(&c__1, " I = ", (ftnlen)6); // do_fio(&c__1, (char*)&(*i__), (ftnlen)sizeof(int32)); // e_wsfe(); // ret_val = 0.; // s_stop("", (ftnlen)0); // } // else if(*i__ == 1) // { // ret_val = 4.450147717014403e-308; // } // else if(*i__ == 2) // { // ret_val = 8.988465674311579e307; // } // else if(*i__ == 3) // { // ret_val = 1.110223024625157e-16; // } // else if(*i__ == 4) // { // ret_val = 2.220446049250313e-16; // } // else if(*i__ == 5) // { // ret_val = .301029995663981; // } // else if(5 < *i__) // { // ci__1.cierr = 0; // ci__1.ciunit = 6; // ci__1.cifmt = "(a)"; // s_wsfe(&ci__1); // do_fio(&c__1, " ", (ftnlen)1); // e_wsfe(); // ci__1.cierr = 0; // ci__1.ciunit = 6; // ci__1.cifmt = "(a)"; // s_wsfe(&ci__1); // do_fio(&c__1, "D1MACH - Fatal error!", (ftnlen)21); // e_wsfe(); // ci__1.cierr = 0; // ci__1.ciunit = 6; // ci__1.cifmt = "(a)"; // s_wsfe(&ci__1); // do_fio(&c__1, " The input argument I is out of bounds.", (ftnlen)40); // e_wsfe(); // ci__1.cierr = 0; // ci__1.ciunit = 6; // ci__1.cifmt = "(a)"; // s_wsfe(&ci__1); // do_fio(&c__1, " Legal values satisfy 1 <= I <= 5.", (ftnlen)35); // e_wsfe(); // ci__1.cierr = 0; // ci__1.ciunit = 6; // ci__1.cifmt = "(a,i12)"; // s_wsfe(&ci__1); // do_fio(&c__1, " I = ", (ftnlen)6); // do_fio(&c__1, (char*)&(*i__), (ftnlen)sizeof(int32)); // e_wsfe(); // ret_val = 0.; // s_stop("", (ftnlen)0); // } // return ret_val; //} /* d1mach_ */ double dgamln_(double* z__, int32* ierr) { /* Initialized data */ static double gln[100] = {0., 0., .693147180559945309, 1.791759469228055, 3.17805383034794562, 4.78749174278204599, 6.579251212010101, 8.5251613610654143, 10.6046029027452502, 12.8018274800814696, 15.1044125730755153, 17.5023078458738858, 19.9872144956618861, 22.5521638531234229, 25.1912211827386815, 27.8992713838408916, 30.6718601060806728, 33.5050734501368889, 36.3954452080330536, 39.339884187199494, 42.335616460753485, 45.380138898476908, 48.4711813518352239, 51.6066755677643736, 54.7847293981123192, 58.0036052229805199, 61.261701761002002, 64.5575386270063311, 67.889743137181535, 71.257038967168009, 74.6582363488301644, 78.0922235533153106, 81.5579594561150372, 85.0544670175815174, 88.5808275421976788, 92.1361756036870925, 95.7196945421432025, 99.3306124547874269, 102.968198614513813, 106.631760260643459, 110.320639714757395, 114.034211781461703, 117.771881399745072, 121.533081515438634, 125.317271149356895, 129.123933639127215, 132.95257503561631, 136.802722637326368, 140.673923648234259, 144.565743946344886, 148.477766951773032, 152.409592584497358, 156.360836303078785, 160.331128216630907, 164.320112263195181, 168.327445448427652, 172.352797139162802, 176.395848406997352, 180.456291417543771, 184.533828861449491, 188.628173423671591, 192.739047287844902, 196.866181672889994, 201.009316399281527, 205.168199482641199, 209.342586752536836, 213.532241494563261, 217.736934113954227, 221.956441819130334, 226.190548323727593, 230.439043565776952, 234.701723442818268, 238.978389561834323, 243.268849002982714, 247.572914096186884, 251.890402209723194, 256.221135550009525, 260.564940971863209, 264.921649798552801, 269.291097651019823, 273.673124285693704, 278.067573440366143, 282.474292687630396, 286.893133295426994, 291.323950094270308, 295.766601350760624, 300.220948647014132, 304.686856765668715, 309.164193580146922, 313.652829949879062, 318.152639620209327, 322.663499126726177, 327.185287703775217, 331.717887196928473, 336.261181979198477, 340.815058870799018, 345.379407062266854, 349.954118040770237, 354.539085519440809, 359.134205369575399}; static double cf[22] = {.0833333333333333333, -.00277777777777777778, 7.93650793650793651e-4, -5.95238095238095238e-4, 8.41750841750841751e-4, -.00191752691752691753, .00641025641025641026, -.0295506535947712418, .179644372368830573, -1.39243221690590112, 13.402864044168392, -156.848284626002017, 2193.10333333333333, -36108.7712537249894, 691472.268851313067, -15238221.5394074162, 382900751.391414141, -10882266035.7843911, 347320283765.002252, -12369602142269.2745, 488788064793079.335, -21320333960919373.9}; static double con = 1.83787706640934548; /* System generated locals */ int32 i__1; double ret_val; int32 i__, k; double s, t1, fz, zm; int32 mz, nz; double zp; int32 i1m; double fln, tlg, rln, trm, tst, zsq, zinc, zmin, zdmy, wdtol; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE DGAMLN */ /* ***DATE WRITTEN 830501 (YYMMDD) */ /* ***REVISION DATE 830501 (YYMMDD) */ /* ***CATEGORY NO. B5F */ /* ***KEYWORDS GAMMA FUNCTION,LOGARITHM OF GAMMA FUNCTION */ /* ***AUTHOR AMOS, DONALD E., SANDIA NATIONAL LABORATORIES */ /* ***PURPOSE TO COMPUTE THE LOGARITHM OF THE GAMMA FUNCTION */ /* ***DESCRIPTION */ /* **** A DOUBLE PRECISION ROUTINE **** */ /* DGAMLN COMPUTES THE NATURAL LOG OF THE GAMMA FUNCTION FOR */ /* Z.GT.0. THE ASYMPTOTIC EXPANSION IS USED TO GENERATE VALUES */ /* GREATER THAN ZMIN WHICH ARE ADJUSTED BY THE RECURSION */ /* G(Z+1)=Z*G(Z) FOR Z.LE.ZMIN. THE FUNCTION WAS MADE AS */ /* PORTABLE AS POSSIBLE BY COMPUTIMG ZMIN FROM THE NUMBER OF BASE */ /* 10 DIGITS IN A WORD, RLN=AMAX1(-ALOG10(R1MACH(4)),0.5E-18) */ /* LIMITED TO 18 DIGITS OF (RELATIVE) ACCURACY. */ /* SINCE INTEGER ARGUMENTS ARE COMMON, A TABLE LOOK UP ON 100 */ /* VALUES IS USED FOR SPEED OF EXECUTION. */ /* DESCRIPTION OF ARGUMENTS */ /* INPUT Z IS D0UBLE PRECISION */ /* Z - ARGUMENT, Z.GT.0.0D0 */ /* OUTPUT DGAMLN IS DOUBLE PRECISION */ /* DGAMLN - NATURAL LOG OF THE GAMMA FUNCTION AT Z.NE.0.0D0 */ /* IERR - ERROR FLAG */ /* IERR=0, NORMAL RETURN, COMPUTATION COMPLETED */ /* IERR=1, Z.LE.0.0D0, NO COMPUTATION */ /* ***REFERENCES COMPUTATION OF BESSEL FUNCTIONS OF COMPLEX ARGUMENT */ /* BY D. E. AMOS, SAND83-0083, MAY, 1983. */ /* ***ROUTINES CALLED I1MACH,D1MACH */ /* ***END PROLOGUE DGAMLN */ /* LNGAMMA(N), N=1,100 */ /* COEFFICIENTS OF ASYMPTOTIC EXPANSION */ /* LN(2*PI) */ /* ***FIRST EXECUTABLE STATEMENT DGAMLN */ *ierr = 0; if(*z__ <= 0.) { goto L70; } if(*z__ > 101.) { goto L10; } nz = (int32)(*z__); fz = *z__ - (float)nz; if(fz > 0.) { goto L10; } if(nz > 100) { goto L10; } ret_val = gln[nz - 1]; return ret_val; L10: wdtol = d1mach_(&c__4); wdtol = max(wdtol, 5e-19); i1m = i1mach_(&c__14); rln = d1mach_(&c__5) * (float)i1m; fln = std::min(rln, 20.); fln = max(fln, 3.); fln += -3.; zm = fln * .3875 + 1.8; mz = (int32)((float)zm) + 1; zmin = (float)mz; zdmy = *z__; zinc = 0.; if(*z__ >= zmin) { goto L20; } zinc = zmin - (float)nz; zdmy = *z__ + zinc; L20: zp = 1. / zdmy; t1 = cf[0] * zp; s = t1; if(zp < wdtol) { goto L40; } zsq = zp * zp; tst = t1 * wdtol; for(k = 2; k <= 22; ++k) { zp *= zsq; trm = cf[k - 1] * zp; if(abs(trm) < tst) { goto L40; } s += trm; /* L30: */ } L40: if(zinc != 0.) { goto L50; } tlg = log(*z__); ret_val = *z__ * (tlg - 1.) + (con - tlg) * .5 + s; return ret_val; L50: zp = 1.; nz = (int32)((float)zinc); i__1 = nz; for(i__ = 1; i__ <= i__1; ++i__) { zp *= *z__ + (float)(i__ - 1); /* L60: */ } tlg = log(zdmy); ret_val = zdmy * (tlg - 1.) - log(zp) + (con - tlg) * .5 + s; return ret_val; L70: *ierr = 1; return ret_val; } /* dgamln_ */ double gamln_(float* z__, int32* ierr) { /* Initialized data */ static float gln[100] = {(float)0., (float)0., (float).693147180559945309, (float)1.791759469228055, (float)3.17805383034794562, (float)4.78749174278204599, (float)6.579251212010101, (float)8.5251613610654143, (float)10.6046029027452502, (float)12.8018274800814696, (float)15.1044125730755153, (float)17.5023078458738858, (float)19.9872144956618861, (float)22.5521638531234229, (float)25.1912211827386815, (float)27.8992713838408916, (float)30.6718601060806728, (float)33.5050734501368889, (float)36.3954452080330536, (float)39.339884187199494, (float)42.335616460753485, (float)45.380138898476908, (float)48.4711813518352239, (float)51.6066755677643736, (float)54.7847293981123192, (float)58.0036052229805199, (float)61.261701761002002, (float)64.5575386270063311, (float)67.889743137181535, (float)71.257038967168009, (float)74.6582363488301644, (float)78.0922235533153106, (float)81.5579594561150372, (float)85.0544670175815174, (float)88.5808275421976788, (float)92.1361756036870925, (float)95.7196945421432025, (float)99.3306124547874269, (float)102.968198614513813, (float)106.631760260643459, (float)110.320639714757395, (float)114.034211781461703, (float)117.771881399745072, (float)121.533081515438634, (float)125.317271149356895, (float)129.123933639127215, (float)132.95257503561631, (float)136.802722637326368, (float)140.673923648234259, (float)144.565743946344886, (float)148.477766951773032, (float)152.409592584497358, (float)156.360836303078785, (float)160.331128216630907, (float)164.320112263195181, (float)168.327445448427652, (float)172.352797139162802, (float)176.395848406997352, (float)180.456291417543771, (float)184.533828861449491, (float)188.628173423671591, (float)192.739047287844902, (float)196.866181672889994, (float)201.009316399281527, (float)205.168199482641199, (float)209.342586752536836, (float)213.532241494563261, (float)217.736934113954227, (float)221.956441819130334, (float)226.190548323727593, (float)230.439043565776952, (float)234.701723442818268, (float)238.978389561834323, (float)243.268849002982714, (float)247.572914096186884, (float)251.890402209723194, (float)256.221135550009525, (float)260.564940971863209, (float)264.921649798552801, (float)269.291097651019823, (float)273.673124285693704, (float)278.067573440366143, (float)282.474292687630396, (float)286.893133295426994, (float)291.323950094270308, (float)295.766601350760624, (float)300.220948647014132, (float)304.686856765668715, (float)309.164193580146922, (float)313.652829949879062, (float)318.152639620209327, (float)322.663499126726177, (float)327.185287703775217, (float)331.717887196928473, (float)336.261181979198477, (float)340.815058870799018, (float)345.379407062266854, (float)349.954118040770237, (float)354.539085519440809, (float)359.134205369575399}; static float cf[22] = {(float).0833333333333333333, (float)-.00277777777777777778, (float)7.93650793650793651e-4, (float)-5.95238095238095238e-4, (float)8.41750841750841751e-4, (float)-.00191752691752691753, (float).00641025641025641026, (float)-.0295506535947712418, (float).179644372368830573, (float)-1.39243221690590112, (float)13.402864044168392, (float)-156.848284626002017, (float)2193.10333333333333, (float)-36108.7712537249894, (float)691472.268851313067, (float)-15238221.5394074162, (float)382900751.391414141, (float)-10882266035.7843911, (float)347320283765.002252, (float)-12369602142269.2745, (float)488788064793079.335, (float)-21320333960919373.9}; static float con = (float)1.83787706640934548; /* System generated locals */ int32 i__1; float ret_val; int32 i__, k; float s, t1, fz; int32 mz, nz; float zm, zp; int32 i1m; float fln, tlg, rln, trm, tst, zsq, zinc, zmin, zdmy, wdtol; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE GAMLN */ /* ***DATE WRITTEN 830501 (YYMMDD) */ /* ***REVISION DATE 830501 (YYMMDD) */ /* ***CATEGORY NO. B5F */ /* ***KEYWORDS GAMMA FUNCTION,LOGARITHM OF GAMMA FUNCTION */ /* ***AUTHOR AMOS, DONALD E., SANDIA NATIONAL LABORATORIES */ /* ***PURPOSE TO COMPUTE THE LOGARITHM OF THE GAMMA FUNCTION */ /* ***DESCRIPTION */ /* GAMLN COMPUTES THE NATURAL LOG OF THE GAMMA FUNCTION FOR */ /* Z.GT.0. THE ASYMPTOTIC EXPANSION IS USED TO GENERATE VALUES */ /* GREATER THAN ZMIN WHICH ARE ADJUSTED BY THE RECURSION */ /* G(Z+1)=Z*G(Z) FOR Z.LE.ZMIN. THE FUNCTION WAS MADE AS */ /* PORTABLE AS POSSIBLE BY COMPUTIMG ZMIN FROM THE NUMBER OF BASE */ /* 10 DIGITS IN A WORD, RLN=AMAX1(-ALOG10(R1MACH(4)),0.5E-18) */ /* LIMITED TO 18 DIGITS OF (RELATIVE) ACCURACY. */ /* SINCE INTEGER ARGUMENTS ARE COMMON, A TABLE LOOK UP ON 100 */ /* VALUES IS USED FOR SPEED OF EXECUTION. */ /* DESCRIPTION OF ARGUMENTS */ /* INPUT */ /* Z - REAL ARGUMENT, Z.GT.0.0E0 */ /* OUTPUT */ /* GAMLN - NATURAL LOG OF THE GAMMA FUNCTION AT Z */ /* IERR - ERROR FLAG */ /* IERR=0, NORMAL RETURN, COMPUTATION COMPLETED */ /* IERR=1, Z.LE.0.0E0, NO COMPUTATION */ /* ***REFERENCES COMPUTATION OF BESSEL FUNCTIONS OF COMPLEX ARGUMENT */ /* BY D. E. AMOS, SAND83-0083, MAY, 1983. */ /* ***ROUTINES CALLED I1MACH,R1MACH */ /* ***END PROLOGUE GAMLN */ /* LNGAMMA(N), N=1,100 */ /* COEFFICIENTS OF ASYMPTOTIC EXPANSION */ /* LN(2*PI) */ /* ***FIRST EXECUTABLE STATEMENT GAMLN */ *ierr = 0; if(*z__ <= (float)0.) { goto L70; } if(*z__ > (float)101.) { goto L10; } nz = (int32)(*z__); fz = *z__ - (float)nz; if(fz > (float)0.) { goto L10; } if(nz > 100) { goto L10; } ret_val = gln[nz - 1]; return ret_val; L10: wdtol = r1mach_(&c__4); wdtol = max(wdtol, (float)5e-19); i1m = i1mach_(&c__11); rln = r1mach_(&c__5) * (float)i1m; fln = std::min(rln, (float)20.); fln = max(fln, (float)3.); fln += (float)-3.; zm = fln * (float).3875 + (float)1.8; mz = (int32)zm + 1; zmin = (float)mz; zdmy = *z__; zinc = (float)0.; if(*z__ >= zmin) { goto L20; } zinc = zmin - (float)nz; zdmy = *z__ + zinc; L20: zp = (float)1. / zdmy; t1 = cf[0] * zp; s = t1; if(zp < wdtol) { goto L40; } zsq = zp * zp; tst = t1 * wdtol; for(k = 2; k <= 22; ++k) { zp *= zsq; trm = cf[k - 1] * zp; if(abs(trm) < tst) { goto L40; } s += trm; /* L30: */ } L40: if(zinc != (float)0.) { goto L50; } tlg = log(*z__); ret_val = *z__ * (tlg - (float)1.) + (con - tlg) * (float).5 + s; return ret_val; L50: zp = (float)1.; nz = (int32)zinc; i__1 = nz; for(i__ = 1; i__ <= i__1; ++i__) { zp *= *z__ + (float)(i__ - 1); /* L60: */ } tlg = log(zdmy); ret_val = zdmy * (tlg - (float)1.) - log(zp) + (con - tlg) * (float).5 + s; return ret_val; L70: *ierr = 1; return ret_val; } /* gamln_ */ //int32 i1mach_(int32* i__) //{ // /* System generated locals */ // int32 ret_val; // cilist ci__1; // // /* Builtin functions */ // int32 s_wsfe(cilist*), do_fio(int32*, char*, ftnlen), e_wsfe(); // int s_stop(char*, ftnlen); // // /* *********************************************************************72 */ // // /* c I1MACH returns int32 machine dependent constants. */ // // /* Discussion: */ // // /* Input/output unit numbers. */ // // /* I1MACH(1) = the standard input unit. */ // /* I1MACH(2) = the standard output unit. */ // /* I1MACH(3) = the standard punch unit. */ // /* I1MACH(4) = the standard error message unit. */ // // /* Words. */ // // /* I1MACH(5) = the number of bits per int32 storage unit. */ // /* I1MACH(6) = the number of characters per int32 storage unit. */ // // /* Integers. */ // // /* Assume integers are represented in the S digit base A form: */ // // /* Sign * (X(S-1)*A**(S-1) + ... + X(1)*A + X(0)) */ // // /* where 0 <= X(1:S-1) < A. */ // // /* I1MACH(7) = A, the base. */ // /* I1MACH(8) = S, the number of base A digits. */ // /* I1MACH(9) = A**S-1, the largest int32. */ // // /* Floating point numbers */ // // /* Assume floating point numbers are represented in the T digit */ // /* base B form: */ // // /* Sign * (B**E) * ((X(1)/B) + ... + (X(T)/B**T) ) */ // // /* where 0 <= X(I) < B for I=1 to T, 0 < X(1) and EMIN <= E <= EMAX. */ // // /* I1MACH(10) = B, the base. */ // // /* Single precision */ // // /* I1MACH(11) = T, the number of base B digits. */ // /* I1MACH(12) = EMIN, the smallest exponent E. */ // /* I1MACH(13) = EMAX, the largest exponent E. */ // // /* Double precision */ // // /* I1MACH(14) = T, the number of base B digits. */ // /* I1MACH(15) = EMIN, the smallest exponent E. */ // /* I1MACH(16) = EMAX, the largest exponent E. */ // // /* Licensing: */ // // /* This code is distributed under the GNU LGPL license. */ // // /* Modified: */ // // /* 25 April 2007 */ // // /* Author: */ // // /* Original FORTRAN77 version by Phyllis Fox, Andrew Hall, Norman Schryer. */ // /* This FORTRAN77 version by John Burkardt. */ // // /* Reference: */ // // /* Phyllis Fox, Andrew Hall, Norman Schryer, */ // /* Algorithm 528, */ // /* Framework for a Portable Library, */ // /* ACM Transactions on Mathematical Software, */ // /* Volume 4, Number 2, June 1978, page 176-188. */ // // /* Parameters: */ // // /* Input, int32 I, chooses the parameter to be returned. */ // /* 1 <= I <= 16. */ // // /* Output, int32 I1MACH, the value of the chosen parameter. */ // // if(*i__ < 1) // { // ci__1.cierr = 0; // ci__1.ciunit = 6; // ci__1.cifmt = "(a)"; // s_wsfe(&ci__1); // do_fio(&c__1, " ", (ftnlen)1); // e_wsfe(); // ci__1.cierr = 0; // ci__1.ciunit = 6; // ci__1.cifmt = "(a)"; // s_wsfe(&ci__1); // do_fio(&c__1, "I1MACH - Fatal error!", (ftnlen)21); // e_wsfe(); // ci__1.cierr = 0; // ci__1.ciunit = 6; // ci__1.cifmt = "(a)"; // s_wsfe(&ci__1); // do_fio(&c__1, " The input argument I is out of bounds.", (ftnlen)40); // e_wsfe(); // ci__1.cierr = 0; // ci__1.ciunit = 6; // ci__1.cifmt = "(a)"; // s_wsfe(&ci__1); // do_fio(&c__1, " Legal values satisfy 1 <= I <= 16.", (ftnlen)36); // e_wsfe(); // ci__1.cierr = 0; // ci__1.ciunit = 6; // ci__1.cifmt = "(a,i12)"; // s_wsfe(&ci__1); // do_fio(&c__1, " I = ", (ftnlen)6); // do_fio(&c__1, (char*)&(*i__), (ftnlen)sizeof(int32)); // e_wsfe(); // ret_val = 0; // s_stop("", (ftnlen)0); // } // else if(*i__ == 1) // { // ret_val = 5; // } // else if(*i__ == 2) // { // ret_val = 6; // } // else if(*i__ == 3) // { // ret_val = 7; // } // else if(*i__ == 4) // { // ret_val = 6; // } // else if(*i__ == 5) // { // ret_val = 32; // } // else if(*i__ == 6) // { // ret_val = 4; // } // else if(*i__ == 7) // { // ret_val = 2; // } // else if(*i__ == 8) // { // ret_val = 31; // } // else if(*i__ == 9) // { // ret_val = 2147483647; // } // else if(*i__ == 10) // { // ret_val = 2; // } // else if(*i__ == 11) // { // ret_val = 24; // } // else if(*i__ == 12) // { // ret_val = -125; // } // else if(*i__ == 13) // { // ret_val = 128; // } // else if(*i__ == 14) // { // ret_val = 53; // } // else if(*i__ == 15) // { // ret_val = -1021; // } // else if(*i__ == 16) // { // ret_val = 1024; // } // else if(16 < *i__) // { // ci__1.cierr = 0; // ci__1.ciunit = 6; // ci__1.cifmt = "(a)"; // s_wsfe(&ci__1); // do_fio(&c__1, " ", (ftnlen)1); // e_wsfe(); // ci__1.cierr = 0; // ci__1.ciunit = 6; // ci__1.cifmt = "(a)"; // s_wsfe(&ci__1); // do_fio(&c__1, "I1MACH - Fatal error!", (ftnlen)21); // e_wsfe(); // ci__1.cierr = 0; // ci__1.ciunit = 6; // ci__1.cifmt = "(a)"; // s_wsfe(&ci__1); // do_fio(&c__1, " The input argument I is out of bounds.", (ftnlen)40); // e_wsfe(); // ci__1.cierr = 0; // ci__1.ciunit = 6; // ci__1.cifmt = "(a)"; // s_wsfe(&ci__1); // do_fio(&c__1, " Legal values satisfy 1 <= I <= 16.", (ftnlen)36); // e_wsfe(); // ci__1.cierr = 0; // ci__1.ciunit = 6; // ci__1.cifmt = "(a,i12)"; // s_wsfe(&ci__1); // do_fio(&c__1, " I = ", (ftnlen)6); // do_fio(&c__1, (char*)&(*i__), (ftnlen)sizeof(int32)); // e_wsfe(); // ret_val = 0; // s_stop("", (ftnlen)0); // } // return ret_val; //} /* i1mach_ */ //double r1mach_(int32* i__) //{ // /* System generated locals */ // float ret_val; // cilist ci__1; // // /* Builtin functions */ // int32 s_wsfe(cilist*), do_fio(int32*, char*, ftnlen), e_wsfe(); // int s_stop(char*, ftnlen); // // /* *********************************************************************72 */ // // /* c R1MACH returns single precision float machine constants. */ // // /* Discussion: */ // // /* Assume that single precision float numbers are stored with a mantissa */ // /* of T digits in base B, with an exponent whose value must lie */ // /* between EMIN and EMAX. Then for values of I between 1 and 5, */ // /* R1MACH will return the following values: */ // // /* R1MACH(1) = B**(EMIN-1), the smallest positive magnitude. */ // /* R1MACH(2) = B**EMAX*(1-B**(-T)), the largest magnitude. */ // /* R1MACH(3) = B**(-T), the smallest relative spacing. */ // /* R1MACH(4) = B**(1-T), the largest relative spacing. */ // /* R1MACH(5) = log10(B) */ // // /* Licensing: */ // // /* This code is distributed under the GNU LGPL license. */ // // /* Modified: */ // // /* 25 April 2007 */ // // /* Author: */ // // /* Original FORTRAN77 version by Phyllis Fox, Andrew Hall, Norman Schryer. */ // /* This FORTRAN77 version by John Burkardt. */ // // /* Reference: */ // // /* Phyllis Fox, Andrew Hall, Norman Schryer, */ // /* Algorithm 528, */ // /* Framework for a Portable Library, */ // /* ACM Transactions on Mathematical Software, */ // /* Volume 4, Number 2, June 1978, page 176-188. */ // // /* Parameters: */ // // /* Input, int32 I, chooses the parameter to be returned. */ // /* 1 <= I <= 5. */ // // /* Output, float R1MACH, the value of the chosen parameter. */ // // if(*i__ < 1) // { // ci__1.cierr = 0; // ci__1.ciunit = 6; // ci__1.cifmt = "(a)"; // s_wsfe(&ci__1); // do_fio(&c__1, " ", (ftnlen)1); // e_wsfe(); // ci__1.cierr = 0; // ci__1.ciunit = 6; // ci__1.cifmt = "(a)"; // s_wsfe(&ci__1); // do_fio(&c__1, "R1MACH - Fatal error!", (ftnlen)21); // e_wsfe(); // ci__1.cierr = 0; // ci__1.ciunit = 6; // ci__1.cifmt = "(a)"; // s_wsfe(&ci__1); // do_fio(&c__1, " The input argument I is out of bounds.", (ftnlen)40); // e_wsfe(); // ci__1.cierr = 0; // ci__1.ciunit = 6; // ci__1.cifmt = "(a)"; // s_wsfe(&ci__1); // do_fio(&c__1, " Legal values satisfy 1 <= I <= 5.", (ftnlen)35); // e_wsfe(); // ci__1.cierr = 0; // ci__1.ciunit = 6; // ci__1.cifmt = "(a,i12)"; // s_wsfe(&ci__1); // do_fio(&c__1, " I = ", (ftnlen)6); // do_fio(&c__1, (char*)&(*i__), (ftnlen)sizeof(int32)); // e_wsfe(); // ret_val = (float)0.; // s_stop("", (ftnlen)0); // } // else if(*i__ == 1) // { // ret_val = (float)1.1754944e-38; // } // else if(*i__ == 2) // { // ret_val = (float)3.4028235e38; // } // else if(*i__ == 3) // { // ret_val = (float)5.9604645e-8; // } // else if(*i__ == 4) // { // ret_val = (float)1.1920929e-7; // } // else if(*i__ == 5) // { // ret_val = (float).30103; // } // else if(5 < *i__) // { // ci__1.cierr = 0; // ci__1.ciunit = 6; // ci__1.cifmt = "(a)"; // s_wsfe(&ci__1); // do_fio(&c__1, " ", (ftnlen)1); // e_wsfe(); // ci__1.cierr = 0; // ci__1.ciunit = 6; // ci__1.cifmt = "(a)"; // s_wsfe(&ci__1); // do_fio(&c__1, "R1MACH - Fatal error!", (ftnlen)21); // e_wsfe(); // ci__1.cierr = 0; // ci__1.ciunit = 6; // ci__1.cifmt = "(a)"; // s_wsfe(&ci__1); // do_fio(&c__1, " The input argument I is out of bounds.", (ftnlen)40); // e_wsfe(); // ci__1.cierr = 0; // ci__1.ciunit = 6; // ci__1.cifmt = "(a)"; // s_wsfe(&ci__1); // do_fio(&c__1, " Legal values satisfy 1 <= I <= 5.", (ftnlen)35); // e_wsfe(); // ci__1.cierr = 0; // ci__1.ciunit = 6; // ci__1.cifmt = "(a,i12)"; // s_wsfe(&ci__1); // do_fio(&c__1, " I = ", (ftnlen)6); // do_fio(&c__1, (char*)&(*i__), (ftnlen)sizeof(int32)); // e_wsfe(); // ret_val = (float)0.; // s_stop("", (ftnlen)0); // } // return ret_val; //} /* r1mach_ */ #undef month_ref double zabs_(double* zr, double* zi) { /* System generated locals */ double ret_val; double q, s, u, v; /* *********************************************************************72 */ /* c ZABS carries out double precision System::Complex<float> absolute values. */ /* ***BEGIN PROLOGUE ZABS */ /* ***REFER TO ZBESH,ZBESI,ZBESJ,ZBESK,ZBESY,ZAIRY,ZBIRY */ /* ZABS COMPUTES THE ABSOLUTE VALUE OR MAGNITUDE OF A DOUBLE */ /* PRECISION COMPLEX VARIABLE CMPLX(ZR,ZI) */ /* ***ROUTINES CALLED (NONE) */ /* ***END PROLOGUE ZABS */ u = abs(*zr); v = abs(*zi); s = u + v; /* ----------------------------------------------------------------------- */ /* S*1.0D0 MAKES AN UNNORMALIZED UNDERFLOW ON CDC MACHINES INTO A */ /* TRUE FLOATING ZERO */ /* ----------------------------------------------------------------------- */ s *= 1.; if(s == 0.) { goto L20; } if(u > v) { goto L10; } q = u / v; ret_val = v * sqrt(q * q + 1.); return ret_val; L10: q = v / u; ret_val = u * sqrt(q * q + 1.); return ret_val; L20: ret_val = 0.; return ret_val; } /* zabs_ */ int zacai_(double* zr, double* zi, double* fnu, int32* kode, int32* mr, int32* n, double* yr, double* yi, int32* nz, double* rl, double* tol, double* elim, double* alim) { /* Initialized data */ static double pi = 3.14159265358979324; double az; int32 nn, nw; double yy, c1i, c2i, c1r, c2r, arg; int32 iuf; double cyi[2], fmr, sgn; int32 inu; double cyr[2], zni, znr, dfnu; double ascle, csgni, csgnr, cspni, cspnr; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE ZACAI */ /* ***REFER TO ZAIRY */ /* ZACAI APPLIES THE ANALYTIC CONTINUATION FORMULA */ /* K(FNU,ZN*EXP(MP))=K(FNU,ZN)*EXP(-MP*FNU) - MP*I(FNU,ZN) */ /* MP=PI*MR*CMPLX(0.0,1.0) */ /* TO CONTINUE THE K FUNCTION FROM THE RIGHT HALF TO THE LEFT */ /* HALF Z PLANE FOR USE WITH ZAIRY WHERE FNU=1/3 OR 2/3 AND N=1. */ /* ZACAI IS THE SAME AS ZACON WITH THE PARTS FOR LARGER ORDERS AND */ /* RECURRENCE REMOVED. A RECURSIVE CALL TO ZACON CAN RESULT IF ZACON */ /* IS CALLED FROM ZAIRY. */ /* ***ROUTINES CALLED ZASYI,ZBKNU,ZMLRI,ZSERI,ZS1S2,D1MACH,ZABS */ /* ***END PROLOGUE ZACAI */ /* COMPLEX CSGN,CSPN,C1,C2,Y,Z,ZN,CY */ /* Parameter adjustments */ --yi; --yr; /* Function Body */ *nz = 0; znr = -(*zr); zni = -(*zi); az = zabs_(zr, zi); nn = *n; dfnu = *fnu + (double)((float)(*n - 1)); if(az <= 2.) { goto L10; } if(az * az * .25 > dfnu + 1.) { goto L20; } L10: /* ----------------------------------------------------------------------- */ /* POWER SERIES FOR THE I FUNCTION */ /* ----------------------------------------------------------------------- */ zseri_(&znr, &zni, fnu, kode, &nn, &yr[1], &yi[1], &nw, tol, elim, alim); goto L40; L20: if(az < *rl) { goto L30; } /* ----------------------------------------------------------------------- */ /* ASYMPTOTIC EXPANSION FOR LARGE Z FOR THE I FUNCTION */ /* ----------------------------------------------------------------------- */ zasyi_(&znr, &zni, fnu, kode, &nn, &yr[1], &yi[1], &nw, rl, tol, elim, alim); if(nw < 0) { goto L80; } goto L40; L30: /* ----------------------------------------------------------------------- */ /* MILLER ALGORITHM NORMALIZED BY THE SERIES FOR THE I FUNCTION */ /* ----------------------------------------------------------------------- */ zmlri_(&znr, &zni, fnu, kode, &nn, &yr[1], &yi[1], &nw, tol); if(nw < 0) { goto L80; } L40: /* ----------------------------------------------------------------------- */ /* ANALYTIC CONTINUATION TO THE LEFT HALF PLANE FOR THE K FUNCTION */ /* ----------------------------------------------------------------------- */ zbknu_(&znr, &zni, fnu, kode, &c__1, cyr, cyi, &nw, tol, elim, alim); if(nw != 0) { goto L80; } fmr = (double)((float)(*mr)); sgn = -d_sign(&pi, &fmr); csgnr = 0.; csgni = sgn; if(*kode == 1) { goto L50; } yy = -zni; csgnr = -csgni * sin(yy); csgni *= cos(yy); L50: /* ----------------------------------------------------------------------- */ /* CALCULATE CSPN=EXP(FNU*PI*I) TO MINIMIZE LOSSES OF SIGNIFICANCE */ /* WHEN FNU IS LARGE */ /* ----------------------------------------------------------------------- */ inu = (int32)((float)(*fnu)); arg = (*fnu - (double)((float)inu)) * sgn; cspnr = cos(arg); cspni = sin(arg); if(inu % 2 == 0) { goto L60; } cspnr = -cspnr; cspni = -cspni; L60: c1r = cyr[0]; c1i = cyi[0]; c2r = yr[1]; c2i = yi[1]; if(*kode == 1) { goto L70; } iuf = 0; ascle = d1mach_(&c__1) * 1e3 / *tol; zs1s2_(&znr, &zni, &c1r, &c1i, &c2r, &c2i, &nw, &ascle, alim, &iuf); *nz += nw; L70: yr[1] = cspnr * c1r - cspni * c1i + csgnr * c2r - csgni * c2i; yi[1] = cspnr * c1i + cspni * c1r + csgnr * c2i + csgni * c2r; return 0; L80: *nz = -1; if(nw == -2) { *nz = -2; } return 0; } /* zacai_ */ int zacon_(double* zr, double* zi, double* fnu, int32* kode, int32* mr, int32* n, double* yr, double* yi, int32* nz, double* rl, double* fnul, double* tol, double* elim, double* alim) { /* Initialized data */ static double pi = 3.14159265358979324; static double zeror = 0.; static double coner = 1.; /* System generated locals */ int32 i__1; int32 i__; double fn; int32 nn, nw; double yy, c1i, c2i, c1m, as2, c1r, c2r, s1i, s2i, s1r, s2r, cki, arg, ckr, cpn; int32 iuf; double cyi[2], fmr, csr, azn, sgn; int32 inu; double bry[3], cyr[2], pti, spn, sti, zni, rzi, ptr, str, znr, rzr, sc1i, sc2i, sc1r, sc2r, cscl, cscr; double csrr[3], cssr[3], razn; int32 kflag; double ascle, bscle, csgni, csgnr, cspni, cspnr; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE ZACON */ /* ***REFER TO ZBESK,ZBESH */ /* ZACON APPLIES THE ANALYTIC CONTINUATION FORMULA */ /* K(FNU,ZN*EXP(MP))=K(FNU,ZN)*EXP(-MP*FNU) - MP*I(FNU,ZN) */ /* MP=PI*MR*CMPLX(0.0,1.0) */ /* TO CONTINUE THE K FUNCTION FROM THE RIGHT HALF TO THE LEFT */ /* HALF Z PLANE */ /* ***ROUTINES CALLED ZBINU,ZBKNU,ZS1S2,D1MACH,ZABS,ZMLT */ /* ***END PROLOGUE ZACON */ /* COMPLEX CK,CONE,CSCL,CSCR,CSGN,CSPN,CY,CZERO,C1,C2,RZ,SC1,SC2,ST, */ /* *S1,S2,Y,Z,ZN */ /* Parameter adjustments */ --yi; --yr; /* Function Body */ *nz = 0; znr = -(*zr); zni = -(*zi); nn = *n; zbinu_(&znr, &zni, fnu, kode, &nn, &yr[1], &yi[1], &nw, rl, fnul, tol, elim, alim); if(nw < 0) { goto L90; } /* ----------------------------------------------------------------------- */ /* ANALYTIC CONTINUATION TO THE LEFT HALF PLANE FOR THE K FUNCTION */ /* ----------------------------------------------------------------------- */ nn = std::min(2L, *n); zbknu_(&znr, &zni, fnu, kode, &nn, cyr, cyi, &nw, tol, elim, alim); if(nw != 0) { goto L90; } s1r = cyr[0]; s1i = cyi[0]; fmr = (double)((float)(*mr)); sgn = -d_sign(&pi, &fmr); csgnr = zeror; csgni = sgn; if(*kode == 1) { goto L10; } yy = -zni; cpn = cos(yy); spn = sin(yy); zmlt_(&csgnr, &csgni, &cpn, &spn, &csgnr, &csgni); L10: /* ----------------------------------------------------------------------- */ /* CALCULATE CSPN=EXP(FNU*PI*I) TO MINIMIZE LOSSES OF SIGNIFICANCE */ /* WHEN FNU IS LARGE */ /* ----------------------------------------------------------------------- */ inu = (int32)((float)(*fnu)); arg = (*fnu - (double)((float)inu)) * sgn; cpn = cos(arg); spn = sin(arg); cspnr = cpn; cspni = spn; if(inu % 2 == 0) { goto L20; } cspnr = -cspnr; cspni = -cspni; L20: iuf = 0; c1r = s1r; c1i = s1i; c2r = yr[1]; c2i = yi[1]; ascle = d1mach_(&c__1) * 1e3 / *tol; if(*kode == 1) { goto L30; } zs1s2_(&znr, &zni, &c1r, &c1i, &c2r, &c2i, &nw, &ascle, alim, &iuf); *nz += nw; sc1r = c1r; sc1i = c1i; L30: zmlt_(&cspnr, &cspni, &c1r, &c1i, &str, &sti); zmlt_(&csgnr, &csgni, &c2r, &c2i, &ptr, &pti); yr[1] = str + ptr; yi[1] = sti + pti; if(*n == 1) { return 0; } cspnr = -cspnr; cspni = -cspni; s2r = cyr[1]; s2i = cyi[1]; c1r = s2r; c1i = s2i; c2r = yr[2]; c2i = yi[2]; if(*kode == 1) { goto L40; } zs1s2_(&znr, &zni, &c1r, &c1i, &c2r, &c2i, &nw, &ascle, alim, &iuf); *nz += nw; sc2r = c1r; sc2i = c1i; L40: zmlt_(&cspnr, &cspni, &c1r, &c1i, &str, &sti); zmlt_(&csgnr, &csgni, &c2r, &c2i, &ptr, &pti); yr[2] = str + ptr; yi[2] = sti + pti; if(*n == 2) { return 0; } cspnr = -cspnr; cspni = -cspni; azn = zabs_(&znr, &zni); razn = 1. / azn; str = znr * razn; sti = -zni * razn; rzr = (str + str) * razn; rzi = (sti + sti) * razn; fn = *fnu + 1.; ckr = fn * rzr; cki = fn * rzi; /* ----------------------------------------------------------------------- */ /* SCALE NEAR EXPONENT EXTREMES DURING RECURRENCE ON K FUNCTIONS */ /* ----------------------------------------------------------------------- */ cscl = 1. / *tol; cscr = *tol; cssr[0] = cscl; cssr[1] = coner; cssr[2] = cscr; csrr[0] = cscr; csrr[1] = coner; csrr[2] = cscl; bry[0] = ascle; bry[1] = 1. / ascle; bry[2] = d1mach_(&c__2); as2 = zabs_(&s2r, &s2i); kflag = 2; if(as2 > bry[0]) { goto L50; } kflag = 1; goto L60; L50: if(as2 < bry[1]) { goto L60; } kflag = 3; L60: bscle = bry[kflag - 1]; s1r *= cssr[kflag - 1]; s1i *= cssr[kflag - 1]; s2r *= cssr[kflag - 1]; s2i *= cssr[kflag - 1]; csr = csrr[kflag - 1]; i__1 = *n; for(i__ = 3; i__ <= i__1; ++i__) { str = s2r; sti = s2i; s2r = ckr * str - cki * sti + s1r; s2i = ckr * sti + cki * str + s1i; s1r = str; s1i = sti; c1r = s2r * csr; c1i = s2i * csr; str = c1r; sti = c1i; c2r = yr[i__]; c2i = yi[i__]; if(*kode == 1) { goto L70; } if(iuf < 0) { goto L70; } zs1s2_(&znr, &zni, &c1r, &c1i, &c2r, &c2i, &nw, &ascle, alim, &iuf); *nz += nw; sc1r = sc2r; sc1i = sc2i; sc2r = c1r; sc2i = c1i; if(iuf != 3) { goto L70; } iuf = -4; s1r = sc1r * cssr[kflag - 1]; s1i = sc1i * cssr[kflag - 1]; s2r = sc2r * cssr[kflag - 1]; s2i = sc2i * cssr[kflag - 1]; str = sc2r; sti = sc2i; L70: ptr = cspnr * c1r - cspni * c1i; pti = cspnr * c1i + cspni * c1r; yr[i__] = ptr + csgnr * c2r - csgni * c2i; yi[i__] = pti + csgnr * c2i + csgni * c2r; ckr += rzr; cki += rzi; cspnr = -cspnr; cspni = -cspni; if(kflag >= 3) { goto L80; } ptr = abs(c1r); pti = abs(c1i); c1m = max(ptr, pti); if(c1m <= bscle) { goto L80; } ++kflag; bscle = bry[kflag - 1]; s1r *= csr; s1i *= csr; s2r = str; s2i = sti; s1r *= cssr[kflag - 1]; s1i *= cssr[kflag - 1]; s2r *= cssr[kflag - 1]; s2i *= cssr[kflag - 1]; csr = csrr[kflag - 1]; L80:; } return 0; L90: *nz = -1; if(nw == -2) { *nz = -2; } return 0; } /* zacon_ */ int zairy_(double* zr, double* zi, int32* id, int32* kode, double* air, double* aii, int32* nz, int32* ierr) { /* Initialized data */ static double tth = .666666666666666667; static double c1 = .35502805388781724; static double c2 = .258819403792806799; static double coef = .183776298473930683; static double zeror = 0.; static double zeroi = 0.; static double coner = 1.; static double conei = 0.; /* System generated locals */ int32 i__1, i__2; double d__1; int32 k; double d1, d2; int32 k1, k2; double aa, bb, ad, cc, ak, bk, ck, dk, az; int32 nn; double rl; int32 mr; double s1i, az3, s2i, s1r, s2r, z3i, z3r, dig, fid, cyi[1], r1m5, fnu, cyr[1], tol, sti, ptr, str, sfac, alim, elim, alaz; double csqi, atrm, ztai, csqr, ztar; double trm1i, trm2i, trm1r, trm2r; int32 iflag; /* *********************************************************************72 */ /* c ZAIRY computes a sequence of System::Complex<float> Airy Ai functions. */ /* ***BEGIN PROLOGUE ZAIRY */ /* ***DATE WRITTEN 830501 (YYMMDD) */ /* ***REVISION DATE 890801, 930101 (YYMMDD) */ /* ***CATEGORY NO. B5K */ /* ***KEYWORDS AIRY FUNCTION,BESSEL FUNCTIONS OF ORDER ONE THIRD */ /* ***AUTHOR AMOS, DONALD E., SANDIA NATIONAL LABORATORIES */ /* ***PURPOSE TO COMPUTE AIRY FUNCTIONS AI(Z) AND DAI(Z) FOR COMPLEX Z */ /* ***DESCRIPTION */ /* ***A DOUBLE PRECISION ROUTINE*** */ /* ON KODE=1, ZAIRY COMPUTES THE COMPLEX AIRY FUNCTION AI(Z) OR */ /* ITS DERIVATIVE DAI(Z)/DZ ON ID=0 OR ID=1 RESPECTIVELY. ON */ /* KODE=2, A SCALING OPTION CEXP(ZTA)*AI(Z) OR CEXP(ZTA)* */ /* DAI(Z)/DZ IS PROVIDED TO REMOVE THE EXPONENTIAL DECAY IN */ /* -PI/3.LT.ARG(Z).LT.PI/3 AND THE EXPONENTIAL GROWTH IN */ /* PI/3.LT.ABS(ARG(Z)).LT.PI WHERE ZTA=(2/3)*Z*CSQRT(Z). */ /* WHILE THE AIRY FUNCTIONS AI(Z) AND DAI(Z)/DZ ARE ANALYTIC IN */ /* THE WHOLE Z PLANE, THE CORRESPONDING SCALED FUNCTIONS DEFINED */ /* FOR KODE=2 HAVE A CUT ALONG THE NEGATIVE REAL AXIS. */ /* DEFINTIONS AND NOTATION ARE FOUND IN THE NBS HANDBOOK OF */ /* MATHEMATICAL FUNCTIONS (REF. 1). */ /* INPUT ZR,ZI ARE DOUBLE PRECISION */ /* ZR,ZI - Z=CMPLX(ZR,ZI) */ /* ID - ORDER OF DERIVATIVE, ID=0 OR ID=1 */ /* KODE - A PARAMETER TO INDICATE THE SCALING OPTION */ /* KODE= 1 RETURNS */ /* AI=AI(Z) ON ID=0 OR */ /* AI=DAI(Z)/DZ ON ID=1 */ /* = 2 RETURNS */ /* AI=CEXP(ZTA)*AI(Z) ON ID=0 OR */ /* AI=CEXP(ZTA)*DAI(Z)/DZ ON ID=1 WHERE */ /* ZTA=(2/3)*Z*CSQRT(Z) */ /* OUTPUT AIR,AII ARE DOUBLE PRECISION */ /* AIR,AII- COMPLEX ANSWER DEPENDING ON THE CHOICES FOR ID AND */ /* KODE */ /* NZ - UNDERFLOW INDICATOR */ /* NZ= 0 , NORMAL RETURN */ /* NZ= 1 , AI=CMPLX(0.0D0,0.0D0) DUE TO UNDERFLOW IN */ /* -PI/3.LT.ARG(Z).LT.PI/3 ON KODE=1 */ /* IERR - ERROR FLAG */ /* IERR=0, NORMAL RETURN - COMPUTATION COMPLETED */ /* IERR=1, INPUT ERROR - NO COMPUTATION */ /* IERR=2, OVERFLOW - NO COMPUTATION, REAL(ZTA) */ /* TOO LARGE ON KODE=1 */ /* IERR=3, CABS(Z) LARGE - COMPUTATION COMPLETED */ /* LOSSES OF SIGNIFCANCE BY ARGUMENT REDUCTION */ /* PRODUCE LESS THAN HALF OF MACHINE ACCURACY */ /* IERR=4, CABS(Z) TOO LARGE - NO COMPUTATION */ /* COMPLETE LOSS OF ACCURACY BY ARGUMENT */ /* REDUCTION */ /* IERR=5, ERROR - NO COMPUTATION, */ /* ALGORITHM TERMINATION CONDITION NOT MET */ /* ***LONG DESCRIPTION */ /* AI AND DAI ARE COMPUTED FOR CABS(Z).GT.1.0 FROM THE K BESSEL */ /* FUNCTIONS BY */ /* AI(Z)=C*SQRT(Z)*K(1/3,ZTA) , DAI(Z)=-C*Z*K(2/3,ZTA) */ /* C=1.0/(PI*SQRT(3.0)) */ /* ZTA=(2/3)*Z**(3/2) */ /* WITH THE POWER SERIES FOR CABS(Z).LE.1.0. */ /* IN MOST COMPLEX VARIABLE COMPUTATION, ONE MUST EVALUATE ELE- */ /* MENTARY FUNCTIONS. WHEN THE MAGNITUDE OF Z IS LARGE, LOSSES */ /* OF SIGNIFICANCE BY ARGUMENT REDUCTION OCCUR. CONSEQUENTLY, IF */ /* THE MAGNITUDE OF ZETA=(2/3)*Z**1.5 EXCEEDS U1=SQRT(0.5/UR), */ /* THEN LOSSES EXCEEDING HALF PRECISION ARE LIKELY AND AN ERROR */ /* FLAG IERR=3 IS TRIGGERED WHERE UR=DMAX1(D1MACH(4),1.0D-18) IS */ /* DOUBLE PRECISION UNIT ROUNDOFF LIMITED TO 18 DIGITS PRECISION. */ /* ALSO, IF THE MAGNITUDE OF ZETA IS LARGER THAN U2=0.5/UR, THEN */ /* ALL SIGNIFICANCE IS LOST AND IERR=4. IN ORDER TO USE THE INT */ /* FUNCTION, ZETA MUST BE FURTHER RESTRICTED NOT TO EXCEED THE */ /* LARGEST INTEGER, U3=I1MACH(9). THUS, THE MAGNITUDE OF ZETA */ /* MUST BE RESTRICTED BY MIN(U2,U3). ON 32 BIT MACHINES, U1,U2, */ /* AND U3 ARE APPROXIMATELY 2.0E+3, 4.2E+6, 2.1E+9 IN SINGLE */ /* PRECISION ARITHMETIC AND 1.3E+8, 1.8E+16, 2.1E+9 IN DOUBLE */ /* PRECISION ARITHMETIC RESPECTIVELY. THIS MAKES U2 AND U3 LIMIT- */ /* ING IN THEIR RESPECTIVE ARITHMETICS. THIS MEANS THAT THE MAG- */ /* NITUDE OF Z CANNOT EXCEED 3.1E+4 IN SINGLE AND 2.1E+6 IN */ /* DOUBLE PRECISION ARITHMETIC. THIS ALSO MEANS THAT ONE CAN */ /* EXPECT TO RETAIN, IN THE WORST CASES ON 32 BIT MACHINES, */ /* NO DIGITS IN SINGLE PRECISION AND ONLY 7 DIGITS IN DOUBLE */ /* PRECISION ARITHMETIC. SIMILAR CONSIDERATIONS HOLD FOR OTHER */ /* MACHINES. */ /* THE APPROXIMATE RELATIVE ERROR IN THE MAGNITUDE OF A COMPLEX */ /* BESSEL FUNCTION CAN BE EXPRESSED BY P*10**S WHERE P=MAX(UNIT */ /* ROUNDOFF,1.0E-18) IS THE NOMINAL PRECISION AND 10**S REPRE- */ /* SENTS THE INCREASE IN ERROR DUE TO ARGUMENT REDUCTION IN THE */ /* ELEMENTARY FUNCTIONS. HERE, S=MAX(1,ABS(LOG10(CABS(Z))), */ /* ABS(LOG10(FNU))) APPROXIMATELY (I.E. S=MAX(1,ABS(EXPONENT OF */ /* CABS(Z),ABS(EXPONENT OF FNU)) ). HOWEVER, THE PHASE ANGLE MAY */ /* HAVE ONLY ABSOLUTE ACCURACY. THIS IS MOST LIKELY TO OCCUR WHEN */ /* ONE COMPONENT (IN ABSOLUTE VALUE) IS LARGER THAN THE OTHER BY */ /* SEVERAL ORDERS OF MAGNITUDE. IF ONE COMPONENT IS 10**K LARGER */ /* THAN THE OTHER, THEN ONE CAN EXPECT ONLY MAX(ABS(LOG10(P))-K, */ /* 0) SIGNIFICANT DIGITS; OR, STATED ANOTHER WAY, WHEN K EXCEEDS */ /* THE EXPONENT OF P, NO SIGNIFICANT DIGITS REMAIN IN THE SMALLER */ /* COMPONENT. HOWEVER, THE PHASE ANGLE RETAINS ABSOLUTE ACCURACY */ /* BECAUSE, IN COMPLEX ARITHMETIC WITH PRECISION P, THE SMALLER */ /* COMPONENT WILL NOT (AS A RULE) DECREASE BELOW P TIMES THE */ /* MAGNITUDE OF THE LARGER COMPONENT. IN THESE EXTREME CASES, */ /* THE PRINCIPAL PHASE ANGLE IS ON THE ORDER OF +P, -P, PI/2-P, */ /* OR -PI/2+P. */ /* ***REFERENCES HANDBOOK OF MATHEMATICAL FUNCTIONS BY M. ABRAMOWITZ */ /* AND I. A. STEGUN, NBS AMS SERIES 55, U.S. DEPT. OF */ /* COMMERCE, 1955. */ /* COMPUTATION OF BESSEL FUNCTIONS OF COMPLEX ARGUMENT */ /* AND LARGE ORDER BY D. E. AMOS, SAND83-0643, MAY, 1983 */ /* A SUBROUTINE PACKAGE FOR BESSEL FUNCTIONS OF A COMPLEX */ /* ARGUMENT AND NONNEGATIVE ORDER BY D. E. AMOS, SAND85- */ /* 1018, MAY, 1985 */ /* A PORTABLE PACKAGE FOR BESSEL FUNCTIONS OF A COMPLEX */ /* ARGUMENT AND NONNEGATIVE ORDER BY D. E. AMOS, ACM */ /* TRANS. MATH. SOFTWARE, VOL. 12, NO. 3, SEPTEMBER 1986, */ /* PP 265-273. */ /* ***ROUTINES CALLED ZACAI,ZBKNU,ZEXP,ZSQRT,ZABS,I1MACH,D1MACH */ /* ***END PROLOGUE ZAIRY */ /* COMPLEX AI,CONE,CSQ,CY,S1,S2,TRM1,TRM2,Z,ZTA,Z3 */ /* ***FIRST EXECUTABLE STATEMENT ZAIRY */ *ierr = 0; *nz = 0; if(*id < 0 || *id > 1) { *ierr = 1; } if(*kode < 1 || *kode > 2) { *ierr = 1; } if(*ierr != 0) { return 0; } az = zabs_(zr, zi); /* Computing MAX */ d__1 = d1mach_(&c__4); tol = max(d__1, 1e-18); fid = (double)((float)(*id)); if(az > 1.) { goto L70; } /* ----------------------------------------------------------------------- */ /* POWER SERIES FOR CABS(Z).LE.1. */ /* ----------------------------------------------------------------------- */ s1r = coner; s1i = conei; s2r = coner; s2i = conei; if(az < tol) { goto L170; } aa = az * az; if(aa < tol / az) { goto L40; } trm1r = coner; trm1i = conei; trm2r = coner; trm2i = conei; atrm = 1.; str = *zr * *zr - *zi * *zi; sti = *zr * *zi + *zi * *zr; z3r = str * *zr - sti * *zi; z3i = str * *zi + sti * *zr; az3 = az * aa; ak = fid + 2.; bk = 3. - fid - fid; ck = 4. - fid; dk = fid + 3. + fid; d1 = ak * dk; d2 = bk * ck; ad = std::min(d1, d2); ak = fid * 9. + 24.; bk = 30. - fid * 9.; for(k = 1; k <= 25; ++k) { str = (trm1r * z3r - trm1i * z3i) / d1; trm1i = (trm1r * z3i + trm1i * z3r) / d1; trm1r = str; s1r += trm1r; s1i += trm1i; str = (trm2r * z3r - trm2i * z3i) / d2; trm2i = (trm2r * z3i + trm2i * z3r) / d2; trm2r = str; s2r += trm2r; s2i += trm2i; atrm = atrm * az3 / ad; d1 += ak; d2 += bk; ad = std::min(d1, d2); if(atrm < tol * ad) { goto L40; } ak += 18.; bk += 18.; /* L30: */ } L40: if(*id == 1) { goto L50; } *air = s1r * c1 - c2 * (*zr * s2r - *zi * s2i); *aii = s1i * c1 - c2 * (*zr * s2i + *zi * s2r); if(*kode == 1) { return 0; } zsqrt_(zr, zi, &str, &sti); ztar = tth * (*zr * str - *zi * sti); ztai = tth * (*zr * sti + *zi * str); zexp_(&ztar, &ztai, &str, &sti); ptr = *air * str - *aii * sti; *aii = *air * sti + *aii * str; *air = ptr; return 0; L50: *air = -s2r * c2; *aii = -s2i * c2; if(az <= tol) { goto L60; } str = *zr * s1r - *zi * s1i; sti = *zr * s1i + *zi * s1r; cc = c1 / (fid + 1.); *air += cc * (str * *zr - sti * *zi); *aii += cc * (str * *zi + sti * *zr); L60: if(*kode == 1) { return 0; } zsqrt_(zr, zi, &str, &sti); ztar = tth * (*zr * str - *zi * sti); ztai = tth * (*zr * sti + *zi * str); zexp_(&ztar, &ztai, &str, &sti); ptr = str * *air - sti * *aii; *aii = str * *aii + sti * *air; *air = ptr; return 0; /* ----------------------------------------------------------------------- */ /* CASE FOR CABS(Z).GT.1.0 */ /* ----------------------------------------------------------------------- */ L70: fnu = (fid + 1.) / 3.; /* ----------------------------------------------------------------------- */ /* SET PARAMETERS RELATED TO MACHINE CONSTANTS. */ /* TOL IS THE APPROXIMATE UNIT ROUNDOFF LIMITED TO 1.0D-18. */ /* ELIM IS THE APPROXIMATE EXPONENTIAL OVER- AND UNDERFLOW LIMIT. */ /* EXP(-ELIM).LT.EXP(-ALIM)=EXP(-ELIM)/TOL AND */ /* EXP(ELIM).GT.EXP(ALIM)=EXP(ELIM)*TOL ARE INTERVALS NEAR */ /* UNDERFLOW AND OVERFLOW LIMITS WHERE SCALED ARITHMETIC IS DONE. */ /* RL IS THE LOWER BOUNDARY OF THE ASYMPTOTIC EXPANSION FOR LARGE Z. */ /* DIG = NUMBER OF BASE 10 DIGITS IN TOL = 10**(-DIG). */ /* ----------------------------------------------------------------------- */ k1 = i1mach_(&c__15); k2 = i1mach_(&c__16); r1m5 = d1mach_(&c__5); /* Computing MIN */ i__1 = abs(k1), i__2 = abs(k2); k = std::min(i__1, i__2); elim = ((double)((float)k) * r1m5 - 3.) * 2.303; k1 = i1mach_(&c__14) - 1; aa = r1m5 * (double)((float)k1); dig = std::min(aa, 18.); aa *= 2.303; /* Computing MAX */ d__1 = -aa; alim = elim + max(d__1, -41.45); rl = dig * 1.2 + 3.; alaz = log(az); /* -------------------------------------------------------------------------- */ /* TEST FOR PROPER RANGE */ /* ----------------------------------------------------------------------- */ aa = .5 / tol; bb = (double)((float)i1mach_(&c__9)) * .5; aa = std::min(aa, bb); aa = pow_dd(&aa, &tth); if(az > aa) { goto L260; } aa = sqrt(aa); if(az > aa) { *ierr = 3; } zsqrt_(zr, zi, &csqr, &csqi); ztar = tth * (*zr * csqr - *zi * csqi); ztai = tth * (*zr * csqi + *zi * csqr); /* ----------------------------------------------------------------------- */ /* RE(ZTA).LE.0 WHEN RE(Z).LT.0, ESPECIALLY WHEN IM(Z) IS SMALL */ /* ----------------------------------------------------------------------- */ iflag = 0; sfac = 1.; ak = ztai; if(*zr >= 0.) { goto L80; } bk = ztar; ck = -abs(bk); ztar = ck; ztai = ak; L80: if(*zi != 0.) { goto L90; } if(*zr > 0.) { goto L90; } ztar = 0.; ztai = ak; L90: aa = ztar; if(aa >= 0. && *zr > 0.) { goto L110; } if(*kode == 2) { goto L100; } /* ----------------------------------------------------------------------- */ /* OVERFLOW TEST */ /* ----------------------------------------------------------------------- */ if(aa > -alim) { goto L100; } aa = -aa + alaz * .25; iflag = 1; sfac = tol; if(aa > elim) { goto L270; } L100: /* ----------------------------------------------------------------------- */ /* CBKNU AND CACON RETURN EXP(ZTA)*K(FNU,ZTA) ON KODE=2 */ /* ----------------------------------------------------------------------- */ mr = 1; if(*zi < 0.) { mr = -1; } zacai_(&ztar, &ztai, &fnu, kode, &mr, &c__1, cyr, cyi, &nn, &rl, &tol, &elim, &alim); if(nn < 0) { goto L280; } *nz += nn; goto L130; L110: if(*kode == 2) { goto L120; } /* ----------------------------------------------------------------------- */ /* UNDERFLOW TEST */ /* ----------------------------------------------------------------------- */ if(aa < alim) { goto L120; } aa = -aa - alaz * .25; iflag = 2; sfac = 1. / tol; if(aa < -elim) { goto L210; } L120: zbknu_(&ztar, &ztai, &fnu, kode, &c__1, cyr, cyi, nz, &tol, &elim, &alim); L130: s1r = cyr[0] * coef; s1i = cyi[0] * coef; if(iflag != 0) { goto L150; } if(*id == 1) { goto L140; } *air = csqr * s1r - csqi * s1i; *aii = csqr * s1i + csqi * s1r; return 0; L140: *air = -(*zr * s1r - *zi * s1i); *aii = -(*zr * s1i + *zi * s1r); return 0; L150: s1r *= sfac; s1i *= sfac; if(*id == 1) { goto L160; } str = s1r * csqr - s1i * csqi; s1i = s1r * csqi + s1i * csqr; s1r = str; *air = s1r / sfac; *aii = s1i / sfac; return 0; L160: str = -(s1r * *zr - s1i * *zi); s1i = -(s1r * *zi + s1i * *zr); s1r = str; *air = s1r / sfac; *aii = s1i / sfac; return 0; L170: aa = d1mach_(&c__1) * 1e3; s1r = zeror; s1i = zeroi; if(*id == 1) { goto L190; } if(az <= aa) { goto L180; } s1r = c2 * *zr; s1i = c2 * *zi; L180: *air = c1 - s1r; *aii = -s1i; return 0; L190: *air = -c2; *aii = 0.; aa = sqrt(aa); if(az <= aa) { goto L200; } s1r = (*zr * *zr - *zi * *zi) * .5; s1i = *zr * *zi; L200: *air += c1 * s1r; *aii += c1 * s1i; return 0; L210: *nz = 1; *air = zeror; *aii = zeroi; return 0; L270: *nz = 0; *ierr = 2; return 0; L280: if(nn == -1) { goto L270; } *nz = 0; *ierr = 5; return 0; L260: *ierr = 4; *nz = 0; return 0; } /* zairy_ */ int zasyi_(double* zr, double* zi, double* fnu, int32* kode, int32* n, double* yr, double* yi, int32* nz, double* rl, double* tol, double* elim, double* alim) { /* Initialized data */ static double pi = 3.14159265358979324; static double rtpi = .159154943091895336; static double zeror = 0.; static double zeroi = 0.; static double coner = 1.; static double conei = 0.; /* System generated locals */ int32 i__1, i__2; double d__1, d__2; int32 i__, j, k, m; double s, aa, bb; int32 ib; double ak, bk; int32 il, jl; double az; int32 nn; double p1i, s2i, p1r, s2r, cki, dki, fdn, arg, aez, arm, ckr, dkr, czi, ezi, sgn; int32 inu; double raz, czr, ezr, sqk, sti, rzi, tzi, str, rzr, tzr, ak1i, ak1r, cs1i, cs2i, cs1r, cs2r, dnu2, rtr1, dfnu; double atol; int32 koded; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE ZASYI */ /* ***REFER TO ZBESI,ZBESK */ /* ZASYI COMPUTES THE I BESSEL FUNCTION FOR REAL(Z).GE.0.0 BY */ /* MEANS OF THE ASYMPTOTIC EXPANSION FOR LARGE CABS(Z) IN THE */ /* REGION CABS(Z).GT.MAX(RL,FNU*FNU/2). NZ=0 IS A NORMAL RETURN. */ /* NZ.LT.0 INDICATES AN OVERFLOW ON KODE=1. */ /* ***ROUTINES CALLED D1MACH,ZABS,ZDIV,ZEXP,ZMLT,ZSQRT */ /* ***END PROLOGUE ZASYI */ /* COMPLEX AK1,CK,CONE,CS1,CS2,CZ,CZERO,DK,EZ,P1,RZ,S2,Y,Z */ /* Parameter adjustments */ --yi; --yr; /* Function Body */ *nz = 0; az = zabs_(zr, zi); arm = d1mach_(&c__1) * 1e3; rtr1 = sqrt(arm); il = std::min(2L, *n); dfnu = *fnu + (double)((float)(*n - il)); /* ----------------------------------------------------------------------- */ /* OVERFLOW TEST */ /* ----------------------------------------------------------------------- */ raz = 1. / az; str = *zr * raz; sti = -(*zi) * raz; ak1r = rtpi * str * raz; ak1i = rtpi * sti * raz; zsqrt_(&ak1r, &ak1i, &ak1r, &ak1i); czr = *zr; czi = *zi; if(*kode != 2) { goto L10; } czr = zeror; czi = *zi; L10: if(abs(czr) > *elim) { goto L100; } dnu2 = dfnu + dfnu; koded = 1; if(abs(czr) > *alim && *n > 2) { goto L20; } koded = 0; zexp_(&czr, &czi, &str, &sti); zmlt_(&ak1r, &ak1i, &str, &sti, &ak1r, &ak1i); L20: fdn = 0.; if(dnu2 > rtr1) { fdn = dnu2 * dnu2; } ezr = *zr * 8.; ezi = *zi * 8.; /* ----------------------------------------------------------------------- */ /* WHEN Z IS IMAGINARY, THE ERROR TEST MUST BE MADE RELATIVE TO THE */ /* FIRST RECIPROCAL POWER SINCE THIS IS THE LEADING TERM OF THE */ /* EXPANSION FOR THE IMAGINARY PART. */ /* ----------------------------------------------------------------------- */ aez = az * 8.; s = *tol / aez; jl = (int32)((float)(*rl + *rl)) + 2; p1r = zeror; p1i = zeroi; if(*zi == 0.) { goto L30; } /* ----------------------------------------------------------------------- */ /* CALCULATE EXP(PI*(0.5+FNU+N-IL)*I) TO MINIMIZE LOSSES OF */ /* SIGNIFICANCE WHEN FNU OR N IS LARGE */ /* ----------------------------------------------------------------------- */ inu = (int32)((float)(*fnu)); arg = (*fnu - (double)((float)inu)) * pi; inu = inu + *n - il; ak = -sin(arg); bk = cos(arg); if(*zi < 0.) { bk = -bk; } p1r = ak; p1i = bk; if(inu % 2 == 0) { goto L30; } p1r = -p1r; p1i = -p1i; L30: i__1 = il; for(k = 1; k <= i__1; ++k) { sqk = fdn - 1.; atol = s * abs(sqk); sgn = 1.; cs1r = coner; cs1i = conei; cs2r = coner; cs2i = conei; ckr = coner; cki = conei; ak = 0.; aa = 1.; bb = aez; dkr = ezr; dki = ezi; i__2 = jl; for(j = 1; j <= i__2; ++j) { zdiv_(&ckr, &cki, &dkr, &dki, &str, &sti); ckr = str * sqk; cki = sti * sqk; cs2r += ckr; cs2i += cki; sgn = -sgn; cs1r += ckr * sgn; cs1i += cki * sgn; dkr += ezr; dki += ezi; aa = aa * abs(sqk) / bb; bb += aez; ak += 8.; sqk -= ak; if(aa <= atol) { goto L50; } /* L40: */ } goto L110; L50: s2r = cs1r; s2i = cs1i; if(*zr + *zr >= *elim) { goto L60; } tzr = *zr + *zr; tzi = *zi + *zi; d__1 = -tzr; d__2 = -tzi; zexp_(&d__1, &d__2, &str, &sti); zmlt_(&str, &sti, &p1r, &p1i, &str, &sti); zmlt_(&str, &sti, &cs2r, &cs2i, &str, &sti); s2r += str; s2i += sti; L60: fdn = fdn + dfnu * 8. + 4.; p1r = -p1r; p1i = -p1i; m = *n - il + k; yr[m] = s2r * ak1r - s2i * ak1i; yi[m] = s2r * ak1i + s2i * ak1r; /* L70: */ } if(*n <= 2) { return 0; } nn = *n; k = nn - 2; ak = (double)((float)k); str = *zr * raz; sti = -(*zi) * raz; rzr = (str + str) * raz; rzi = (sti + sti) * raz; ib = 3; i__1 = nn; for(i__ = ib; i__ <= i__1; ++i__) { yr[k] = (ak + *fnu) * (rzr * yr[k + 1] - rzi * yi[k + 1]) + yr[k + 2]; yi[k] = (ak + *fnu) * (rzr * yi[k + 1] + rzi * yr[k + 1]) + yi[k + 2]; ak += -1.; --k; /* L80: */ } if(koded == 0) { return 0; } zexp_(&czr, &czi, &ckr, &cki); i__1 = nn; for(i__ = 1; i__ <= i__1; ++i__) { str = yr[i__] * ckr - yi[i__] * cki; yi[i__] = yr[i__] * cki + yi[i__] * ckr; yr[i__] = str; /* L90: */ } return 0; L100: *nz = -1; return 0; L110: *nz = -2; return 0; } /* zasyi_ */ int zbesh_(double* zr, double* zi, double* fnu, int32* kode, int32* m, int32* n, double* cyr, double* cyi, int32* nz, int32* ierr) { /* Initialized data */ static double hpi = 1.57079632679489662; /* System generated locals */ int32 i__1, i__2; double d__1, d__2; int32 i__, k, k1, k2; double aa, bb, fn; int32 mm; double az; int32 ir, nn; double rl; int32 mr, nw; double dig, arg, aln, fmm, r1m5, ufl, sgn; int32 nuf, inu; double tol, sti, zni, zti, str, znr, alim, elim; double atol, rhpi; int32 inuh; double fnul, rtol, ascle, csgni; double csgnr; /* *********************************************************************72 */ /* c ZBESH computes a sequence of System::Complex<float> Hankel functions. */ /* ***BEGIN PROLOGUE ZBESH */ /* ***DATE WRITTEN 830501 (YYMMDD) */ /* ***REVISION DATE 890801, 930101 (YYMMDD) */ /* ***CATEGORY NO. B5K */ /* ***KEYWORDS H-BESSEL FUNCTIONS,BESSEL FUNCTIONS OF COMPLEX ARGUMENT, */ /* BESSEL FUNCTIONS OF THIRD KIND,HANKEL FUNCTIONS */ /* ***AUTHOR AMOS, DONALD E., SANDIA NATIONAL LABORATORIES */ /* ***PURPOSE TO COMPUTE THE H-BESSEL FUNCTIONS OF A COMPLEX ARGUMENT */ /* ***DESCRIPTION */ /* ***A DOUBLE PRECISION ROUTINE*** */ /* ON KODE=1, ZBESH COMPUTES AN N MEMBER SEQUENCE OF COMPLEX */ /* HANKEL (BESSEL) FUNCTIONS CY(J)=H(M,FNU+J-1,Z) FOR KINDS M=1 */ /* OR 2, REAL, NONNEGATIVE ORDERS FNU+J-1, J=1,...,N, AND COMPLEX */ /* Z.NE.CMPLX(0.0,0.0) IN THE CUT PLANE -PI.LT.ARG(Z).LE.PI. */ /* ON KODE=2, ZBESH RETURNS THE SCALED HANKEL FUNCTIONS */ /* CY(I)=EXP(-MM*Z*I)*H(M,FNU+J-1,Z) MM=3-2*M, I**2=-1. */ /* WHICH REMOVES THE EXPONENTIAL BEHAVIOR IN BOTH THE UPPER AND */ /* LOWER HALF PLANES. DEFINITIONS AND NOTATION ARE FOUND IN THE */ /* NBS HANDBOOK OF MATHEMATICAL FUNCTIONS (REF. 1). */ /* INPUT ZR,ZI,FNU ARE DOUBLE PRECISION */ /* ZR,ZI - Z=CMPLX(ZR,ZI), Z.NE.CMPLX(0.0D0,0.0D0), */ /* -PT.LT.ARG(Z).LE.PI */ /* FNU - ORDER OF INITIAL H FUNCTION, FNU.GE.0.0D0 */ /* KODE - A PARAMETER TO INDICATE THE SCALING OPTION */ /* KODE= 1 RETURNS */ /* CY(J)=H(M,FNU+J-1,Z), J=1,...,N */ /* = 2 RETURNS */ /* CY(J)=H(M,FNU+J-1,Z)*EXP(-I*Z*(3-2M)) */ /* J=1,...,N , I**2=-1 */ /* M - KIND OF HANKEL FUNCTION, M=1 OR 2 */ /* N - NUMBER OF MEMBERS IN THE SEQUENCE, N.GE.1 */ /* OUTPUT CYR,CYI ARE DOUBLE PRECISION */ /* CYR,CYI- DOUBLE PRECISION VECTORS WHOSE FIRST N COMPONENTS */ /* CONTAIN REAL AND IMAGINARY PARTS FOR THE SEQUENCE */ /* CY(J)=H(M,FNU+J-1,Z) OR */ /* CY(J)=H(M,FNU+J-1,Z)*EXP(-I*Z*(3-2M)) J=1,...,N */ /* DEPENDING ON KODE, I**2=-1. */ /* NZ - NUMBER OF COMPONENTS SET TO ZERO DUE TO UNDERFLOW, */ /* NZ= 0 , NORMAL RETURN */ /* NZ.GT.0 , FIRST NZ COMPONENTS OF CY SET TO ZERO DUE */ /* TO UNDERFLOW, CY(J)=CMPLX(0.0D0,0.0D0) */ /* J=1,...,NZ WHEN Y.GT.0.0 AND M=1 OR */ /* Y.LT.0.0 AND M=2. FOR THE COMPLMENTARY */ /* HALF PLANES, NZ STATES ONLY THE NUMBER */ /* OF UNDERFLOWS. */ /* IERR - ERROR FLAG */ /* IERR=0, NORMAL RETURN - COMPUTATION COMPLETED */ /* IERR=1, INPUT ERROR - NO COMPUTATION */ /* IERR=2, OVERFLOW - NO COMPUTATION, FNU TOO */ /* LARGE OR CABS(Z) TOO SMALL OR BOTH */ /* IERR=3, CABS(Z) OR FNU+N-1 LARGE - COMPUTATION DONE */ /* BUT LOSSES OF SIGNIFCANCE BY ARGUMENT */ /* REDUCTION PRODUCE LESS THAN HALF OF MACHINE */ /* ACCURACY */ /* IERR=4, CABS(Z) OR FNU+N-1 TOO LARGE - NO COMPUTA- */ /* TION BECAUSE OF COMPLETE LOSSES OF SIGNIFI- */ /* CANCE BY ARGUMENT REDUCTION */ /* IERR=5, ERROR - NO COMPUTATION, */ /* ALGORITHM TERMINATION CONDITION NOT MET */ /* ***LONG DESCRIPTION */ /* THE COMPUTATION IS CARRIED OUT BY THE RELATION */ /* H(M,FNU,Z)=(1/MP)*EXP(-MP*FNU)*K(FNU,Z*EXP(-MP)) */ /* MP=MM*HPI*I, MM=3-2*M, HPI=PI/2, I**2=-1 */ /* FOR M=1 OR 2 WHERE THE K BESSEL FUNCTION IS COMPUTED FOR THE */ /* RIGHT HALF PLANE RE(Z).GE.0.0. THE K FUNCTION IS CONTINUED */ /* TO THE LEFT HALF PLANE BY THE RELATION */ /* K(FNU,Z*EXP(MP)) = EXP(-MP*FNU)*K(FNU,Z)-MP*I(FNU,Z) */ /* MP=MR*PI*I, MR=+1 OR -1, RE(Z).GT.0, I**2=-1 */ /* WHERE I(FNU,Z) IS THE I BESSEL FUNCTION. */ /* EXPONENTIAL DECAY OF H(M,FNU,Z) OCCURS IN THE UPPER HALF Z */ /* PLANE FOR M=1 AND THE LOWER HALF Z PLANE FOR M=2. EXPONENTIAL */ /* GROWTH OCCURS IN THE COMPLEMENTARY HALF PLANES. SCALING */ /* BY EXP(-MM*Z*I) REMOVES THE EXPONENTIAL BEHAVIOR IN THE */ /* WHOLE Z PLANE FOR Z TO INFINITY. */ /* FOR NEGATIVE ORDERS,THE FORMULAE */ /* H(1,-FNU,Z) = H(1,FNU,Z)*CEXP( PI*FNU*I) */ /* H(2,-FNU,Z) = H(2,FNU,Z)*CEXP(-PI*FNU*I) */ /* I**2=-1 */ /* CAN BE USED. */ /* IN MOST COMPLEX VARIABLE COMPUTATION, ONE MUST EVALUATE ELE- */ /* MENTARY FUNCTIONS. WHEN THE MAGNITUDE OF Z OR FNU+N-1 IS */ /* LARGE, LOSSES OF SIGNIFICANCE BY ARGUMENT REDUCTION OCCUR. */ /* CONSEQUENTLY, IF EITHER ONE EXCEEDS U1=SQRT(0.5/UR), THEN */ /* LOSSES EXCEEDING HALF PRECISION ARE LIKELY AND AN ERROR FLAG */ /* IERR=3 IS TRIGGERED WHERE UR=DMAX1(D1MACH(4),1.0D-18) IS */ /* DOUBLE PRECISION UNIT ROUNDOFF LIMITED TO 18 DIGITS PRECISION. */ /* IF EITHER IS LARGER THAN U2=0.5/UR, THEN ALL SIGNIFICANCE IS */ /* LOST AND IERR=4. IN ORDER TO USE THE INT FUNCTION, ARGUMENTS */ /* MUST BE FURTHER RESTRICTED NOT TO EXCEED THE LARGEST MACHINE */ /* INTEGER, U3=I1MACH(9). THUS, THE MAGNITUDE OF Z AND FNU+N-1 IS */ /* RESTRICTED BY MIN(U2,U3). ON 32 BIT MACHINES, U1,U2, AND U3 */ /* ARE APPROXIMATELY 2.0E+3, 4.2E+6, 2.1E+9 IN SINGLE PRECISION */ /* ARITHMETIC AND 1.3E+8, 1.8E+16, 2.1E+9 IN DOUBLE PRECISION */ /* ARITHMETIC RESPECTIVELY. THIS MAKES U2 AND U3 LIMITING IN */ /* THEIR RESPECTIVE ARITHMETICS. THIS MEANS THAT ONE CAN EXPECT */ /* TO RETAIN, IN THE WORST CASES ON 32 BIT MACHINES, NO DIGITS */ /* IN SINGLE AND ONLY 7 DIGITS IN DOUBLE PRECISION ARITHMETIC. */ /* SIMILAR CONSIDERATIONS HOLD FOR OTHER MACHINES. */ /* THE APPROXIMATE RELATIVE ERROR IN THE MAGNITUDE OF A COMPLEX */ /* BESSEL FUNCTION CAN BE EXPRESSED BY P*10**S WHERE P=MAX(UNIT */ /* ROUNDOFF,1.0D-18) IS THE NOMINAL PRECISION AND 10**S REPRE- */ /* SENTS THE INCREASE IN ERROR DUE TO ARGUMENT REDUCTION IN THE */ /* ELEMENTARY FUNCTIONS. HERE, S=MAX(1,ABS(LOG10(CABS(Z))), */ /* ABS(LOG10(FNU))) APPROXIMATELY (I.E. S=MAX(1,ABS(EXPONENT OF */ /* CABS(Z),ABS(EXPONENT OF FNU)) ). HOWEVER, THE PHASE ANGLE MAY */ /* HAVE ONLY ABSOLUTE ACCURACY. THIS IS MOST LIKELY TO OCCUR WHEN */ /* ONE COMPONENT (IN ABSOLUTE VALUE) IS LARGER THAN THE OTHER BY */ /* SEVERAL ORDERS OF MAGNITUDE. IF ONE COMPONENT IS 10**K LARGER */ /* THAN THE OTHER, THEN ONE CAN EXPECT ONLY MAX(ABS(LOG10(P))-K, */ /* 0) SIGNIFICANT DIGITS; OR, STATED ANOTHER WAY, WHEN K EXCEEDS */ /* THE EXPONENT OF P, NO SIGNIFICANT DIGITS REMAIN IN THE SMALLER */ /* COMPONENT. HOWEVER, THE PHASE ANGLE RETAINS ABSOLUTE ACCURACY */ /* BECAUSE, IN COMPLEX ARITHMETIC WITH PRECISION P, THE SMALLER */ /* COMPONENT WILL NOT (AS A RULE) DECREASE BELOW P TIMES THE */ /* MAGNITUDE OF THE LARGER COMPONENT. IN THESE EXTREME CASES, */ /* THE PRINCIPAL PHASE ANGLE IS ON THE ORDER OF +P, -P, PI/2-P, */ /* OR -PI/2+P. */ /* ***REFERENCES HANDBOOK OF MATHEMATICAL FUNCTIONS BY M. ABRAMOWITZ */ /* AND I. A. STEGUN, NBS AMS SERIES 55, U.S. DEPT. OF */ /* COMMERCE, 1955. */ /* COMPUTATION OF BESSEL FUNCTIONS OF COMPLEX ARGUMENT */ /* BY D. E. AMOS, SAND83-0083, MAY, 1983. */ /* COMPUTATION OF BESSEL FUNCTIONS OF COMPLEX ARGUMENT */ /* AND LARGE ORDER BY D. E. AMOS, SAND83-0643, MAY, 1983 */ /* A SUBROUTINE PACKAGE FOR BESSEL FUNCTIONS OF A COMPLEX */ /* ARGUMENT AND NONNEGATIVE ORDER BY D. E. AMOS, SAND85- */ /* 1018, MAY, 1985 */ /* A PORTABLE PACKAGE FOR BESSEL FUNCTIONS OF A COMPLEX */ /* ARGUMENT AND NONNEGATIVE ORDER BY D. E. AMOS, ACM */ /* TRANS. MATH. SOFTWARE, VOL. 12, NO. 3, SEPTEMBER 1986, */ /* PP 265-273. */ /* ***ROUTINES CALLED ZACON,ZBKNU,ZBUNK,ZUOIK,ZABS,I1MACH,D1MACH */ /* ***END PROLOGUE ZBESH */ /* COMPLEX CY,Z,ZN,ZT,CSGN */ /* Parameter adjustments */ --cyi; --cyr; /* Function Body */ /* ***FIRST EXECUTABLE STATEMENT ZBESH */ *ierr = 0; *nz = 0; if(*zr == 0. && *zi == 0.) { *ierr = 1; } if(*fnu < 0.) { *ierr = 1; } if(*m < 1 || *m > 2) { *ierr = 1; } if(*kode < 1 || *kode > 2) { *ierr = 1; } if(*n < 1) { *ierr = 1; } if(*ierr != 0) { return 0; } nn = *n; /* ----------------------------------------------------------------------- */ /* SET PARAMETERS RELATED TO MACHINE CONSTANTS. */ /* TOL IS THE APPROXIMATE UNIT ROUNDOFF LIMITED TO 1.0E-18. */ /* ELIM IS THE APPROXIMATE EXPONENTIAL OVER- AND UNDERFLOW LIMIT. */ /* EXP(-ELIM).LT.EXP(-ALIM)=EXP(-ELIM)/TOL AND */ /* EXP(ELIM).GT.EXP(ALIM)=EXP(ELIM)*TOL ARE INTERVALS NEAR */ /* UNDERFLOW AND OVERFLOW LIMITS WHERE SCALED ARITHMETIC IS DONE. */ /* RL IS THE LOWER BOUNDARY OF THE ASYMPTOTIC EXPANSION FOR LARGE Z. */ /* DIG = NUMBER OF BASE 10 DIGITS IN TOL = 10**(-DIG). */ /* FNUL IS THE LOWER BOUNDARY OF THE ASYMPTOTIC SERIES FOR LARGE FNU */ /* ----------------------------------------------------------------------- */ /* Computing MAX */ d__1 = d1mach_(&c__4); tol = max(d__1, 1e-18); k1 = i1mach_(&c__15); k2 = i1mach_(&c__16); r1m5 = d1mach_(&c__5); /* Computing MIN */ i__1 = abs(k1), i__2 = abs(k2); k = std::min(i__1, i__2); elim = ((double)((float)k) * r1m5 - 3.) * 2.303; k1 = i1mach_(&c__14) - 1; aa = r1m5 * (double)((float)k1); dig = std::min(aa, 18.); aa *= 2.303; /* Computing MAX */ d__1 = -aa; alim = elim + max(d__1, -41.45); fnul = (dig - 3.) * 6. + 10.; rl = dig * 1.2 + 3.; fn = *fnu + (double)((float)(nn - 1)); mm = 3 - *m - *m; fmm = (double)((float)mm); znr = fmm * *zi; zni = -fmm * *zr; /* ----------------------------------------------------------------------- */ /* TEST FOR PROPER RANGE */ /* ----------------------------------------------------------------------- */ az = zabs_(zr, zi); aa = .5 / tol; bb = (double)((float)i1mach_(&c__9)) * .5; aa = std::min(aa, bb); if(az > aa) { goto L260; } if(fn > aa) { goto L260; } aa = sqrt(aa); if(az > aa) { *ierr = 3; } if(fn > aa) { *ierr = 3; } /* ----------------------------------------------------------------------- */ /* OVERFLOW TEST ON THE LAST MEMBER OF THE SEQUENCE */ /* ----------------------------------------------------------------------- */ ufl = d1mach_(&c__1) * 1e3; if(az < ufl) { goto L230; } if(*fnu > fnul) { goto L90; } if(fn <= 1.) { goto L70; } if(fn > 2.) { goto L60; } if(az > tol) { goto L70; } arg = az * .5; aln = -fn * log(arg); if(aln > elim) { goto L230; } goto L70; L60: zuoik_(&znr, &zni, fnu, kode, &c__2, &nn, &cyr[1], &cyi[1], &nuf, &tol, &elim, &alim); if(nuf < 0) { goto L230; } *nz += nuf; nn -= nuf; /* ----------------------------------------------------------------------- */ /* HERE NN=N OR NN=0 SINCE NUF=0,NN, OR -1 ON RETURN FROM CUOIK */ /* IF NUF=NN, THEN CY(I)=CZERO FOR ALL I */ /* ----------------------------------------------------------------------- */ if(nn == 0) { goto L140; } L70: if(znr < 0. || znr == 0. && zni < 0. && *m == 2) { goto L80; } /* ----------------------------------------------------------------------- */ /* RIGHT HALF PLANE COMPUTATION, XN.GE.0. .AND. (XN.NE.0. .OR. */ /* YN.GE.0. .OR. M=1) */ /* ----------------------------------------------------------------------- */ zbknu_(&znr, &zni, fnu, kode, &nn, &cyr[1], &cyi[1], nz, &tol, &elim, &alim); goto L110; /* ----------------------------------------------------------------------- */ /* LEFT HALF PLANE COMPUTATION */ /* ----------------------------------------------------------------------- */ L80: mr = -mm; zacon_(&znr, &zni, fnu, kode, &mr, &nn, &cyr[1], &cyi[1], &nw, &rl, &fnul, &tol, &elim, &alim); if(nw < 0) { goto L240; } *nz = nw; goto L110; L90: /* ----------------------------------------------------------------------- */ /* UNIFORM ASYMPTOTIC EXPANSIONS FOR FNU.GT.FNUL */ /* ----------------------------------------------------------------------- */ mr = 0; if(znr >= 0. && (znr != 0. || zni >= 0. || *m != 2)) { goto L100; } mr = -mm; if(znr != 0. || zni >= 0.) { goto L100; } znr = -znr; zni = -zni; L100: zbunk_(&znr, &zni, fnu, kode, &mr, &nn, &cyr[1], &cyi[1], &nw, &tol, &elim, &alim); if(nw < 0) { goto L240; } *nz += nw; L110: /* ----------------------------------------------------------------------- */ /* H(M,FNU,Z) = -FMM*(I/HPI)*(ZT**FNU)*K(FNU,-Z*ZT) */ /* ZT=EXP(-FMM*HPI*I) = CMPLX(0.0,-FMM), FMM=3-2*M, M=1,2 */ /* ----------------------------------------------------------------------- */ d__1 = -fmm; sgn = d_sign(&hpi, &d__1); /* ----------------------------------------------------------------------- */ /* CALCULATE EXP(FNU*HPI*I) TO MINIMIZE LOSSES OF SIGNIFICANCE */ /* WHEN FNU IS LARGE */ /* ----------------------------------------------------------------------- */ inu = (int32)((float)(*fnu)); inuh = inu / 2; ir = inu - (inuh << 1); arg = (*fnu - (double)((float)(inu - ir))) * sgn; rhpi = 1. / sgn; /* ZNI = RHPI*DCOS(ARG) */ /* ZNR = -RHPI*DSIN(ARG) */ csgni = rhpi * cos(arg); csgnr = -rhpi * sin(arg); if(inuh % 2 == 0) { goto L120; } /* ZNR = -ZNR */ /* ZNI = -ZNI */ csgnr = -csgnr; csgni = -csgni; L120: zti = -fmm; rtol = 1. / tol; ascle = ufl * rtol; i__1 = nn; for(i__ = 1; i__ <= i__1; ++i__) { /* STR = CYR(I)*ZNR - CYI(I)*ZNI */ /* CYI(I) = CYR(I)*ZNI + CYI(I)*ZNR */ /* CYR(I) = STR */ /* STR = -ZNI*ZTI */ /* ZNI = ZNR*ZTI */ /* ZNR = STR */ aa = cyr[i__]; bb = cyi[i__]; atol = 1.; /* Computing MAX */ d__1 = abs(aa), d__2 = abs(bb); if(max(d__1, d__2) > ascle) { goto L135; } aa *= rtol; bb *= rtol; atol = tol; L135: str = aa * csgnr - bb * csgni; sti = aa * csgni + bb * csgnr; cyr[i__] = str * atol; cyi[i__] = sti * atol; str = -csgni * zti; csgni = csgnr * zti; csgnr = str; /* L130: */ } return 0; L140: if(znr < 0.) { goto L230; } return 0; L230: *nz = 0; *ierr = 2; return 0; L240: if(nw == -1) { goto L230; } *nz = 0; *ierr = 5; return 0; L260: *nz = 0; *ierr = 4; return 0; } /* zbesh_ */ int zbesi_(double* zr, double* zi, double* fnu, int32* kode, int32* n, double* cyr, double* cyi, int32* nz, int32* ierr) { /* Initialized data */ static double pi = 3.14159265358979324; static double coner = 1.; static double conei = 0.; /* System generated locals */ int32 i__1, i__2; double d__1, d__2; int32 i__, k, k1, k2; double aa, bb, fn, az; int32 nn; double rl, dig, arg, r1m5; int32 inu; double tol, sti, zni, str, znr, alim, elim; double atol, fnul, rtol, ascle, csgni, csgnr; /* *********************************************************************72 */ /* c ZBESI computes a sequence of System::Complex<float> Bessel I functions. */ /* ***BEGIN PROLOGUE ZBESI */ /* ***DATE WRITTEN 830501 (YYMMDD) */ /* ***REVISION DATE 890801, 930101 (YYMMDD) */ /* ***CATEGORY NO. B5K */ /* ***KEYWORDS I-BESSEL FUNCTION,COMPLEX BESSEL FUNCTION, */ /* MODIFIED BESSEL FUNCTION OF THE FIRST KIND */ /* ***AUTHOR AMOS, DONALD E., SANDIA NATIONAL LABORATORIES */ /* ***PURPOSE TO COMPUTE I-BESSEL FUNCTIONS OF COMPLEX ARGUMENT */ /* ***DESCRIPTION */ /* ***A DOUBLE PRECISION ROUTINE*** */ /* ON KODE=1, ZBESI COMPUTES AN N MEMBER SEQUENCE OF COMPLEX */ /* BESSEL FUNCTIONS CY(J)=I(FNU+J-1,Z) FOR REAL, NONNEGATIVE */ /* ORDERS FNU+J-1, J=1,...,N AND COMPLEX Z IN THE CUT PLANE */ /* -PI.LT.ARG(Z).LE.PI. ON KODE=2, ZBESI RETURNS THE SCALED */ /* FUNCTIONS */ /* CY(J)=EXP(-ABS(X))*I(FNU+J-1,Z) J = 1,...,N , X=REAL(Z) */ /* WITH THE EXPONENTIAL GROWTH REMOVED IN BOTH THE LEFT AND */ /* RIGHT HALF PLANES FOR Z TO INFINITY. DEFINITIONS AND NOTATION */ /* ARE FOUND IN THE NBS HANDBOOK OF MATHEMATICAL FUNCTIONS */ /* (REF. 1). */ /* INPUT ZR,ZI,FNU ARE DOUBLE PRECISION */ /* ZR,ZI - Z=CMPLX(ZR,ZI), -PI.LT.ARG(Z).LE.PI */ /* FNU - ORDER OF INITIAL I FUNCTION, FNU.GE.0.0D0 */ /* KODE - A PARAMETER TO INDICATE THE SCALING OPTION */ /* KODE= 1 RETURNS */ /* CY(J)=I(FNU+J-1,Z), J=1,...,N */ /* = 2 RETURNS */ /* CY(J)=I(FNU+J-1,Z)*EXP(-ABS(X)), J=1,...,N */ /* N - NUMBER OF MEMBERS OF THE SEQUENCE, N.GE.1 */ /* OUTPUT CYR,CYI ARE DOUBLE PRECISION */ /* CYR,CYI- DOUBLE PRECISION VECTORS WHOSE FIRST N COMPONENTS */ /* CONTAIN REAL AND IMAGINARY PARTS FOR THE SEQUENCE */ /* CY(J)=I(FNU+J-1,Z) OR */ /* CY(J)=I(FNU+J-1,Z)*EXP(-ABS(X)) J=1,...,N */ /* DEPENDING ON KODE, X=REAL(Z) */ /* NZ - NUMBER OF COMPONENTS SET TO ZERO DUE TO UNDERFLOW, */ /* NZ= 0 , NORMAL RETURN */ /* NZ.GT.0 , LAST NZ COMPONENTS OF CY SET TO ZERO */ /* TO UNDERFLOW, CY(J)=CMPLX(0.0D0,0.0D0) */ /* J = N-NZ+1,...,N */ /* IERR - ERROR FLAG */ /* IERR=0, NORMAL RETURN - COMPUTATION COMPLETED */ /* IERR=1, INPUT ERROR - NO COMPUTATION */ /* IERR=2, OVERFLOW - NO COMPUTATION, REAL(Z) TOO */ /* LARGE ON KODE=1 */ /* IERR=3, CABS(Z) OR FNU+N-1 LARGE - COMPUTATION DONE */ /* BUT LOSSES OF SIGNIFCANCE BY ARGUMENT */ /* REDUCTION PRODUCE LESS THAN HALF OF MACHINE */ /* ACCURACY */ /* IERR=4, CABS(Z) OR FNU+N-1 TOO LARGE - NO COMPUTA- */ /* TION BECAUSE OF COMPLETE LOSSES OF SIGNIFI- */ /* CANCE BY ARGUMENT REDUCTION */ /* IERR=5, ERROR - NO COMPUTATION, */ /* ALGORITHM TERMINATION CONDITION NOT MET */ /* ***LONG DESCRIPTION */ /* THE COMPUTATION IS CARRIED OUT BY THE POWER SERIES FOR */ /* SMALL CABS(Z), THE ASYMPTOTIC EXPANSION FOR LARGE CABS(Z), */ /* THE MILLER ALGORITHM NORMALIZED BY THE WRONSKIAN AND A */ /* NEUMANN SERIES FOR IMTERMEDIATE MAGNITUDES, AND THE */ /* UNIFORM ASYMPTOTIC EXPANSIONS FOR I(FNU,Z) AND J(FNU,Z) */ /* FOR LARGE ORDERS. BACKWARD RECURRENCE IS USED TO GENERATE */ /* SEQUENCES OR REDUCE ORDERS WHEN NECESSARY. */ /* THE CALCULATIONS ABOVE ARE DONE IN THE RIGHT HALF PLANE AND */ /* CONTINUED INTO THE LEFT HALF PLANE BY THE FORMULA */ /* I(FNU,Z*EXP(M*PI)) = EXP(M*PI*FNU)*I(FNU,Z) REAL(Z).GT.0.0 */ /* M = +I OR -I, I**2=-1 */ /* FOR NEGATIVE ORDERS,THE FORMULA */ /* I(-FNU,Z) = I(FNU,Z) + (2/PI)*SIN(PI*FNU)*K(FNU,Z) */ /* CAN BE USED. HOWEVER,FOR LARGE ORDERS CLOSE TO INTEGERS, THE */ /* THE FUNCTION CHANGES RADICALLY. WHEN FNU IS A LARGE POSITIVE */ /* INTEGER,THE MAGNITUDE OF I(-FNU,Z)=I(FNU,Z) IS A LARGE */ /* NEGATIVE POWER OF TEN. BUT WHEN FNU IS NOT AN INTEGER, */ /* K(FNU,Z) DOMINATES IN MAGNITUDE WITH A LARGE POSITIVE POWER OF */ /* TEN AND THE MOST THAT THE SECOND TERM CAN BE REDUCED IS BY */ /* UNIT ROUNDOFF FROM THE COEFFICIENT. THUS, WIDE CHANGES CAN */ /* OCCUR WITHIN UNIT ROUNDOFF OF A LARGE INTEGER FOR FNU. HERE, */ /* LARGE MEANS FNU.GT.CABS(Z). */ /* IN MOST COMPLEX VARIABLE COMPUTATION, ONE MUST EVALUATE ELE- */ /* MENTARY FUNCTIONS. WHEN THE MAGNITUDE OF Z OR FNU+N-1 IS */ /* LARGE, LOSSES OF SIGNIFICANCE BY ARGUMENT REDUCTION OCCUR. */ /* CONSEQUENTLY, IF EITHER ONE EXCEEDS U1=SQRT(0.5/UR), THEN */ /* LOSSES EXCEEDING HALF PRECISION ARE LIKELY AND AN ERROR FLAG */ /* IERR=3 IS TRIGGERED WHERE UR=DMAX1(D1MACH(4),1.0D-18) IS */ /* DOUBLE PRECISION UNIT ROUNDOFF LIMITED TO 18 DIGITS PRECISION. */ /* IF EITHER IS LARGER THAN U2=0.5/UR, THEN ALL SIGNIFICANCE IS */ /* LOST AND IERR=4. IN ORDER TO USE THE INT FUNCTION, ARGUMENTS */ /* MUST BE FURTHER RESTRICTED NOT TO EXCEED THE LARGEST MACHINE */ /* INTEGER, U3=I1MACH(9). THUS, THE MAGNITUDE OF Z AND FNU+N-1 IS */ /* RESTRICTED BY MIN(U2,U3). ON 32 BIT MACHINES, U1,U2, AND U3 */ /* ARE APPROXIMATELY 2.0E+3, 4.2E+6, 2.1E+9 IN SINGLE PRECISION */ /* ARITHMETIC AND 1.3E+8, 1.8E+16, 2.1E+9 IN DOUBLE PRECISION */ /* ARITHMETIC RESPECTIVELY. THIS MAKES U2 AND U3 LIMITING IN */ /* THEIR RESPECTIVE ARITHMETICS. THIS MEANS THAT ONE CAN EXPECT */ /* TO RETAIN, IN THE WORST CASES ON 32 BIT MACHINES, NO DIGITS */ /* IN SINGLE AND ONLY 7 DIGITS IN DOUBLE PRECISION ARITHMETIC. */ /* SIMILAR CONSIDERATIONS HOLD FOR OTHER MACHINES. */ /* THE APPROXIMATE RELATIVE ERROR IN THE MAGNITUDE OF A COMPLEX */ /* BESSEL FUNCTION CAN BE EXPRESSED BY P*10**S WHERE P=MAX(UNIT */ /* ROUNDOFF,1.0E-18) IS THE NOMINAL PRECISION AND 10**S REPRE- */ /* SENTS THE INCREASE IN ERROR DUE TO ARGUMENT REDUCTION IN THE */ /* ELEMENTARY FUNCTIONS. HERE, S=MAX(1,ABS(LOG10(CABS(Z))), */ /* ABS(LOG10(FNU))) APPROXIMATELY (I.E. S=MAX(1,ABS(EXPONENT OF */ /* CABS(Z),ABS(EXPONENT OF FNU)) ). HOWEVER, THE PHASE ANGLE MAY */ /* HAVE ONLY ABSOLUTE ACCURACY. THIS IS MOST LIKELY TO OCCUR WHEN */ /* ONE COMPONENT (IN ABSOLUTE VALUE) IS LARGER THAN THE OTHER BY */ /* SEVERAL ORDERS OF MAGNITUDE. IF ONE COMPONENT IS 10**K LARGER */ /* THAN THE OTHER, THEN ONE CAN EXPECT ONLY MAX(ABS(LOG10(P))-K, */ /* 0) SIGNIFICANT DIGITS; OR, STATED ANOTHER WAY, WHEN K EXCEEDS */ /* THE EXPONENT OF P, NO SIGNIFICANT DIGITS REMAIN IN THE SMALLER */ /* COMPONENT. HOWEVER, THE PHASE ANGLE RETAINS ABSOLUTE ACCURACY */ /* BECAUSE, IN COMPLEX ARITHMETIC WITH PRECISION P, THE SMALLER */ /* COMPONENT WILL NOT (AS A RULE) DECREASE BELOW P TIMES THE */ /* MAGNITUDE OF THE LARGER COMPONENT. IN THESE EXTREME CASES, */ /* THE PRINCIPAL PHASE ANGLE IS ON THE ORDER OF +P, -P, PI/2-P, */ /* OR -PI/2+P. */ /* ***REFERENCES HANDBOOK OF MATHEMATICAL FUNCTIONS BY M. ABRAMOWITZ */ /* AND I. A. STEGUN, NBS AMS SERIES 55, U.S. DEPT. OF */ /* COMMERCE, 1955. */ /* COMPUTATION OF BESSEL FUNCTIONS OF COMPLEX ARGUMENT */ /* BY D. E. AMOS, SAND83-0083, MAY, 1983. */ /* COMPUTATION OF BESSEL FUNCTIONS OF COMPLEX ARGUMENT */ /* AND LARGE ORDER BY D. E. AMOS, SAND83-0643, MAY, 1983 */ /* A SUBROUTINE PACKAGE FOR BESSEL FUNCTIONS OF A COMPLEX */ /* ARGUMENT AND NONNEGATIVE ORDER BY D. E. AMOS, SAND85- */ /* 1018, MAY, 1985 */ /* A PORTABLE PACKAGE FOR BESSEL FUNCTIONS OF A COMPLEX */ /* ARGUMENT AND NONNEGATIVE ORDER BY D. E. AMOS, ACM */ /* TRANS. MATH. SOFTWARE, VOL. 12, NO. 3, SEPTEMBER 1986, */ /* PP 265-273. */ /* ***ROUTINES CALLED ZBINU,ZABS,I1MACH,D1MACH */ /* ***END PROLOGUE ZBESI */ /* COMPLEX CONE,CSGN,CW,CY,CZERO,Z,ZN */ /* Parameter adjustments */ --cyi; --cyr; /* Function Body */ /* ***FIRST EXECUTABLE STATEMENT ZBESI */ *ierr = 0; *nz = 0; if(*fnu < 0.) { *ierr = 1; } if(*kode < 1 || *kode > 2) { *ierr = 1; } if(*n < 1) { *ierr = 1; } if(*ierr != 0) { return 0; } /* ----------------------------------------------------------------------- */ /* SET PARAMETERS RELATED TO MACHINE CONSTANTS. */ /* TOL IS THE APPROXIMATE UNIT ROUNDOFF LIMITED TO 1.0E-18. */ /* ELIM IS THE APPROXIMATE EXPONENTIAL OVER- AND UNDERFLOW LIMIT. */ /* EXP(-ELIM).LT.EXP(-ALIM)=EXP(-ELIM)/TOL AND */ /* EXP(ELIM).GT.EXP(ALIM)=EXP(ELIM)*TOL ARE INTERVALS NEAR */ /* UNDERFLOW AND OVERFLOW LIMITS WHERE SCALED ARITHMETIC IS DONE. */ /* RL IS THE LOWER BOUNDARY OF THE ASYMPTOTIC EXPANSION FOR LARGE Z. */ /* DIG = NUMBER OF BASE 10 DIGITS IN TOL = 10**(-DIG). */ /* FNUL IS THE LOWER BOUNDARY OF THE ASYMPTOTIC SERIES FOR LARGE FNU. */ /* ----------------------------------------------------------------------- */ /* Computing MAX */ d__1 = d1mach_(&c__4); tol = max(d__1, 1e-18); k1 = i1mach_(&c__15); k2 = i1mach_(&c__16); r1m5 = d1mach_(&c__5); /* Computing MIN */ i__1 = abs(k1), i__2 = abs(k2); k = std::min(i__1, i__2); elim = ((double)((float)k) * r1m5 - 3.) * 2.303; k1 = i1mach_(&c__14) - 1; aa = r1m5 * (double)((float)k1); dig = std::min(aa, 18.); aa *= 2.303; /* Computing MAX */ d__1 = -aa; alim = elim + max(d__1, -41.45); rl = dig * 1.2 + 3.; fnul = (dig - 3.) * 6. + 10.; /* ----------------------------------------------------------------------------- */ /* TEST FOR PROPER RANGE */ /* ----------------------------------------------------------------------- */ az = zabs_(zr, zi); fn = *fnu + (double)((float)(*n - 1)); aa = .5 / tol; bb = (double)((float)i1mach_(&c__9)) * .5; aa = std::min(aa, bb); if(az > aa) { goto L260; } if(fn > aa) { goto L260; } aa = sqrt(aa); if(az > aa) { *ierr = 3; } if(fn > aa) { *ierr = 3; } znr = *zr; zni = *zi; csgnr = coner; csgni = conei; if(*zr >= 0.) { goto L40; } znr = -(*zr); zni = -(*zi); /* ----------------------------------------------------------------------- */ /* CALCULATE CSGN=EXP(FNU*PI*I) TO MINIMIZE LOSSES OF SIGNIFICANCE */ /* WHEN FNU IS LARGE */ /* ----------------------------------------------------------------------- */ inu = (int32)((float)(*fnu)); arg = (*fnu - (double)((float)inu)) * pi; if(*zi < 0.) { arg = -arg; } csgnr = cos(arg); csgni = sin(arg); if(inu % 2 == 0) { goto L40; } csgnr = -csgnr; csgni = -csgni; L40: zbinu_(&znr, &zni, fnu, kode, n, &cyr[1], &cyi[1], nz, &rl, &fnul, &tol, &elim, &alim); if(*nz < 0) { goto L120; } if(*zr >= 0.) { return 0; } /* ----------------------------------------------------------------------- */ /* ANALYTIC CONTINUATION TO THE LEFT HALF PLANE */ /* ----------------------------------------------------------------------- */ nn = *n - *nz; if(nn == 0) { return 0; } rtol = 1. / tol; ascle = d1mach_(&c__1) * rtol * 1e3; i__1 = nn; for(i__ = 1; i__ <= i__1; ++i__) { /* STR = CYR(I)*CSGNR - CYI(I)*CSGNI */ /* CYI(I) = CYR(I)*CSGNI + CYI(I)*CSGNR */ /* CYR(I) = STR */ aa = cyr[i__]; bb = cyi[i__]; atol = 1.; /* Computing MAX */ d__1 = abs(aa), d__2 = abs(bb); if(max(d__1, d__2) > ascle) { goto L55; } aa *= rtol; bb *= rtol; atol = tol; L55: str = aa * csgnr - bb * csgni; sti = aa * csgni + bb * csgnr; cyr[i__] = str * atol; cyi[i__] = sti * atol; csgnr = -csgnr; csgni = -csgni; /* L50: */ } return 0; L120: if(*nz == -2) { goto L130; } *nz = 0; *ierr = 2; return 0; L130: *nz = 0; *ierr = 5; return 0; L260: *nz = 0; *ierr = 4; return 0; } /* zbesi_ */ int zbesj_(double* zr, double* zi, double* fnu, int32* kode, int32* n, double* cyr, double* cyi, int32* nz, int32* ierr) { /* Initialized data */ static double hpi = 1.57079632679489662; /* System generated locals */ int32 i__1, i__2; double d__1, d__2; int32 i__, k, k1, k2; double aa, bb, fn; int32 nl; double az; int32 ir; double rl, dig, cii, arg, r1m5; int32 inu; double tol, sti, zni, str, znr, alim, elim; double atol; int32 inuh; double fnul, rtol, ascle, csgni, csgnr; /* *********************************************************************72 */ /* c ZBESJ computes a sequence of System::Complex<float> Bessel J functions. */ /* ***BEGIN PROLOGUE ZBESJ */ /* ***DATE WRITTEN 830501 (YYMMDD) */ /* ***REVISION DATE 890801, 930101 (YYMMDD) */ /* ***CATEGORY NO. B5K */ /* ***KEYWORDS J-BESSEL FUNCTION,BESSEL FUNCTION OF COMPLEX ARGUMENT, */ /* BESSEL FUNCTION OF FIRST KIND */ /* ***AUTHOR AMOS, DONALD E., SANDIA NATIONAL LABORATORIES */ /* ***PURPOSE TO COMPUTE THE J-BESSEL FUNCTION OF A COMPLEX ARGUMENT */ /* ***DESCRIPTION */ /* ***A DOUBLE PRECISION ROUTINE*** */ /* ON KODE=1, ZBESJ COMPUTES AN N MEMBER SEQUENCE OF COMPLEX */ /* BESSEL FUNCTIONS CY(I)=J(FNU+I-1,Z) FOR REAL, NONNEGATIVE */ /* ORDERS FNU+I-1, I=1,...,N AND COMPLEX Z IN THE CUT PLANE */ /* -PI.LT.ARG(Z).LE.PI. ON KODE=2, ZBESJ RETURNS THE SCALED */ /* FUNCTIONS */ /* CY(I)=EXP(-ABS(Y))*J(FNU+I-1,Z) I = 1,...,N , Y=AIMAG(Z) */ /* WHICH REMOVE THE EXPONENTIAL GROWTH IN BOTH THE UPPER AND */ /* LOWER HALF PLANES FOR Z TO INFINITY. DEFINITIONS AND NOTATION */ /* ARE FOUND IN THE NBS HANDBOOK OF MATHEMATICAL FUNCTIONS */ /* (REF. 1). */ /* INPUT ZR,ZI,FNU ARE DOUBLE PRECISION */ /* ZR,ZI - Z=CMPLX(ZR,ZI), -PI.LT.ARG(Z).LE.PI */ /* FNU - ORDER OF INITIAL J FUNCTION, FNU.GE.0.0D0 */ /* KODE - A PARAMETER TO INDICATE THE SCALING OPTION */ /* KODE= 1 RETURNS */ /* CY(I)=J(FNU+I-1,Z), I=1,...,N */ /* = 2 RETURNS */ /* CY(I)=J(FNU+I-1,Z)EXP(-ABS(Y)), I=1,...,N */ /* N - NUMBER OF MEMBERS OF THE SEQUENCE, N.GE.1 */ /* OUTPUT CYR,CYI ARE DOUBLE PRECISION */ /* CYR,CYI- DOUBLE PRECISION VECTORS WHOSE FIRST N COMPONENTS */ /* CONTAIN REAL AND IMAGINARY PARTS FOR THE SEQUENCE */ /* CY(I)=J(FNU+I-1,Z) OR */ /* CY(I)=J(FNU+I-1,Z)EXP(-ABS(Y)) I=1,...,N */ /* DEPENDING ON KODE, Y=AIMAG(Z). */ /* NZ - NUMBER OF COMPONENTS SET TO ZERO DUE TO UNDERFLOW, */ /* NZ= 0 , NORMAL RETURN */ /* NZ.GT.0 , LAST NZ COMPONENTS OF CY SET ZERO DUE */ /* TO UNDERFLOW, CY(I)=CMPLX(0.0D0,0.0D0), */ /* I = N-NZ+1,...,N */ /* IERR - ERROR FLAG */ /* IERR=0, NORMAL RETURN - COMPUTATION COMPLETED */ /* IERR=1, INPUT ERROR - NO COMPUTATION */ /* IERR=2, OVERFLOW - NO COMPUTATION, AIMAG(Z) */ /* TOO LARGE ON KODE=1 */ /* IERR=3, CABS(Z) OR FNU+N-1 LARGE - COMPUTATION DONE */ /* BUT LOSSES OF SIGNIFCANCE BY ARGUMENT */ /* REDUCTION PRODUCE LESS THAN HALF OF MACHINE */ /* ACCURACY */ /* IERR=4, CABS(Z) OR FNU+N-1 TOO LARGE - NO COMPUTA- */ /* TION BECAUSE OF COMPLETE LOSSES OF SIGNIFI- */ /* CANCE BY ARGUMENT REDUCTION */ /* IERR=5, ERROR - NO COMPUTATION, */ /* ALGORITHM TERMINATION CONDITION NOT MET */ /* ***LONG DESCRIPTION */ /* THE COMPUTATION IS CARRIED OUT BY THE FORMULA */ /* J(FNU,Z)=EXP( FNU*PI*I/2)*I(FNU,-I*Z) AIMAG(Z).GE.0.0 */ /* J(FNU,Z)=EXP(-FNU*PI*I/2)*I(FNU, I*Z) AIMAG(Z).LT.0.0 */ /* WHERE I**2 = -1 AND I(FNU,Z) IS THE I BESSEL FUNCTION. */ /* FOR NEGATIVE ORDERS,THE FORMULA */ /* J(-FNU,Z) = J(FNU,Z)*COS(PI*FNU) - Y(FNU,Z)*SIN(PI*FNU) */ /* CAN BE USED. HOWEVER,FOR LARGE ORDERS CLOSE TO INTEGERS, THE */ /* THE FUNCTION CHANGES RADICALLY. WHEN FNU IS A LARGE POSITIVE */ /* INTEGER,THE MAGNITUDE OF J(-FNU,Z)=J(FNU,Z)*COS(PI*FNU) IS A */ /* LARGE NEGATIVE POWER OF TEN. BUT WHEN FNU IS NOT AN INTEGER, */ /* Y(FNU,Z) DOMINATES IN MAGNITUDE WITH A LARGE POSITIVE POWER OF */ /* TEN AND THE MOST THAT THE SECOND TERM CAN BE REDUCED IS BY */ /* UNIT ROUNDOFF FROM THE COEFFICIENT. THUS, WIDE CHANGES CAN */ /* OCCUR WITHIN UNIT ROUNDOFF OF A LARGE INTEGER FOR FNU. HERE, */ /* LARGE MEANS FNU.GT.CABS(Z). */ /* IN MOST COMPLEX VARIABLE COMPUTATION, ONE MUST EVALUATE ELE- */ /* MENTARY FUNCTIONS. WHEN THE MAGNITUDE OF Z OR FNU+N-1 IS */ /* LARGE, LOSSES OF SIGNIFICANCE BY ARGUMENT REDUCTION OCCUR. */ /* CONSEQUENTLY, IF EITHER ONE EXCEEDS U1=SQRT(0.5/UR), THEN */ /* LOSSES EXCEEDING HALF PRECISION ARE LIKELY AND AN ERROR FLAG */ /* IERR=3 IS TRIGGERED WHERE UR=DMAX1(D1MACH(4),1.0D-18) IS */ /* DOUBLE PRECISION UNIT ROUNDOFF LIMITED TO 18 DIGITS PRECISION. */ /* IF EITHER IS LARGER THAN U2=0.5/UR, THEN ALL SIGNIFICANCE IS */ /* LOST AND IERR=4. IN ORDER TO USE THE INT FUNCTION, ARGUMENTS */ /* MUST BE FURTHER RESTRICTED NOT TO EXCEED THE LARGEST MACHINE */ /* INTEGER, U3=I1MACH(9). THUS, THE MAGNITUDE OF Z AND FNU+N-1 IS */ /* RESTRICTED BY MIN(U2,U3). ON 32 BIT MACHINES, U1,U2, AND U3 */ /* ARE APPROXIMATELY 2.0E+3, 4.2E+6, 2.1E+9 IN SINGLE PRECISION */ /* ARITHMETIC AND 1.3E+8, 1.8E+16, 2.1E+9 IN DOUBLE PRECISION */ /* ARITHMETIC RESPECTIVELY. THIS MAKES U2 AND U3 LIMITING IN */ /* THEIR RESPECTIVE ARITHMETICS. THIS MEANS THAT ONE CAN EXPECT */ /* TO RETAIN, IN THE WORST CASES ON 32 BIT MACHINES, NO DIGITS */ /* IN SINGLE AND ONLY 7 DIGITS IN DOUBLE PRECISION ARITHMETIC. */ /* SIMILAR CONSIDERATIONS HOLD FOR OTHER MACHINES. */ /* THE APPROXIMATE RELATIVE ERROR IN THE MAGNITUDE OF A COMPLEX */ /* BESSEL FUNCTION CAN BE EXPRESSED BY P*10**S WHERE P=MAX(UNIT */ /* ROUNDOFF,1.0E-18) IS THE NOMINAL PRECISION AND 10**S REPRE- */ /* SENTS THE INCREASE IN ERROR DUE TO ARGUMENT REDUCTION IN THE */ /* ELEMENTARY FUNCTIONS. HERE, S=MAX(1,ABS(LOG10(CABS(Z))), */ /* ABS(LOG10(FNU))) APPROXIMATELY (I.E. S=MAX(1,ABS(EXPONENT OF */ /* CABS(Z),ABS(EXPONENT OF FNU)) ). HOWEVER, THE PHASE ANGLE MAY */ /* HAVE ONLY ABSOLUTE ACCURACY. THIS IS MOST LIKELY TO OCCUR WHEN */ /* ONE COMPONENT (IN ABSOLUTE VALUE) IS LARGER THAN THE OTHER BY */ /* SEVERAL ORDERS OF MAGNITUDE. IF ONE COMPONENT IS 10**K LARGER */ /* THAN THE OTHER, THEN ONE CAN EXPECT ONLY MAX(ABS(LOG10(P))-K, */ /* 0) SIGNIFICANT DIGITS; OR, STATED ANOTHER WAY, WHEN K EXCEEDS */ /* THE EXPONENT OF P, NO SIGNIFICANT DIGITS REMAIN IN THE SMALLER */ /* COMPONENT. HOWEVER, THE PHASE ANGLE RETAINS ABSOLUTE ACCURACY */ /* BECAUSE, IN COMPLEX ARITHMETIC WITH PRECISION P, THE SMALLER */ /* COMPONENT WILL NOT (AS A RULE) DECREASE BELOW P TIMES THE */ /* MAGNITUDE OF THE LARGER COMPONENT. IN THESE EXTREME CASES, */ /* THE PRINCIPAL PHASE ANGLE IS ON THE ORDER OF +P, -P, PI/2-P, */ /* OR -PI/2+P. */ /* ***REFERENCES HANDBOOK OF MATHEMATICAL FUNCTIONS BY M. ABRAMOWITZ */ /* AND I. A. STEGUN, NBS AMS SERIES 55, U.S. DEPT. OF */ /* COMMERCE, 1955. */ /* COMPUTATION OF BESSEL FUNCTIONS OF COMPLEX ARGUMENT */ /* BY D. E. AMOS, SAND83-0083, MAY, 1983. */ /* COMPUTATION OF BESSEL FUNCTIONS OF COMPLEX ARGUMENT */ /* AND LARGE ORDER BY D. E. AMOS, SAND83-0643, MAY, 1983 */ /* A SUBROUTINE PACKAGE FOR BESSEL FUNCTIONS OF A COMPLEX */ /* ARGUMENT AND NONNEGATIVE ORDER BY D. E. AMOS, SAND85- */ /* 1018, MAY, 1985 */ /* A PORTABLE PACKAGE FOR BESSEL FUNCTIONS OF A COMPLEX */ /* ARGUMENT AND NONNEGATIVE ORDER BY D. E. AMOS, ACM */ /* TRANS. MATH. SOFTWARE, VOL. 12, NO. 3, SEPTEMBER 1986, */ /* PP 265-273. */ /* ***ROUTINES CALLED ZBINU,ZABS,I1MACH,D1MACH */ /* ***END PROLOGUE ZBESJ */ /* COMPLEX CI,CSGN,CY,Z,ZN */ /* Parameter adjustments */ --cyi; --cyr; /* Function Body */ /* ***FIRST EXECUTABLE STATEMENT ZBESJ */ *ierr = 0; *nz = 0; if(*fnu < 0.) { *ierr = 1; } if(*kode < 1 || *kode > 2) { *ierr = 1; } if(*n < 1) { *ierr = 1; } if(*ierr != 0) { return 0; } /* ----------------------------------------------------------------------- */ /* SET PARAMETERS RELATED TO MACHINE CONSTANTS. */ /* TOL IS THE APPROXIMATE UNIT ROUNDOFF LIMITED TO 1.0E-18. */ /* ELIM IS THE APPROXIMATE EXPONENTIAL OVER- AND UNDERFLOW LIMIT. */ /* EXP(-ELIM).LT.EXP(-ALIM)=EXP(-ELIM)/TOL AND */ /* EXP(ELIM).GT.EXP(ALIM)=EXP(ELIM)*TOL ARE INTERVALS NEAR */ /* UNDERFLOW AND OVERFLOW LIMITS WHERE SCALED ARITHMETIC IS DONE. */ /* RL IS THE LOWER BOUNDARY OF THE ASYMPTOTIC EXPANSION FOR LARGE Z. */ /* DIG = NUMBER OF BASE 10 DIGITS IN TOL = 10**(-DIG). */ /* FNUL IS THE LOWER BOUNDARY OF THE ASYMPTOTIC SERIES FOR LARGE FNU. */ /* ----------------------------------------------------------------------- */ /* Computing MAX */ d__1 = d1mach_(&c__4); tol = max(d__1, 1e-18); k1 = i1mach_(&c__15); k2 = i1mach_(&c__16); r1m5 = d1mach_(&c__5); /* Computing MIN */ i__1 = abs(k1), i__2 = abs(k2); k = std::min(i__1, i__2); elim = ((double)((float)k) * r1m5 - 3.) * 2.303; k1 = i1mach_(&c__14) - 1; aa = r1m5 * (double)((float)k1); dig = std::min(aa, 18.); aa *= 2.303; /* Computing MAX */ d__1 = -aa; alim = elim + max(d__1, -41.45); rl = dig * 1.2 + 3.; fnul = (dig - 3.) * 6. + 10.; /* ----------------------------------------------------------------------- */ /* TEST FOR PROPER RANGE */ /* ----------------------------------------------------------------------- */ az = zabs_(zr, zi); fn = *fnu + (double)((float)(*n - 1)); aa = .5 / tol; bb = (double)((float)i1mach_(&c__9)) * .5; aa = std::min(aa, bb); if(az > aa) { goto L260; } if(fn > aa) { goto L260; } aa = sqrt(aa); if(az > aa) { *ierr = 3; } if(fn > aa) { *ierr = 3; } /* ----------------------------------------------------------------------- */ /* CALCULATE CSGN=EXP(FNU*HPI*I) TO MINIMIZE LOSSES OF SIGNIFICANCE */ /* WHEN FNU IS LARGE */ /* ----------------------------------------------------------------------- */ cii = 1.; inu = (int32)((float)(*fnu)); inuh = inu / 2; ir = inu - (inuh << 1); arg = (*fnu - (double)((float)(inu - ir))) * hpi; csgnr = cos(arg); csgni = sin(arg); if(inuh % 2 == 0) { goto L40; } csgnr = -csgnr; csgni = -csgni; L40: /* ----------------------------------------------------------------------- */ /* ZN IS IN THE RIGHT HALF PLANE */ /* ----------------------------------------------------------------------- */ znr = *zi; zni = -(*zr); if(*zi >= 0.) { goto L50; } znr = -znr; zni = -zni; csgni = -csgni; cii = -cii; L50: zbinu_(&znr, &zni, fnu, kode, n, &cyr[1], &cyi[1], nz, &rl, &fnul, &tol, &elim, &alim); if(*nz < 0) { goto L130; } nl = *n - *nz; if(nl == 0) { return 0; } rtol = 1. / tol; ascle = d1mach_(&c__1) * rtol * 1e3; i__1 = nl; for(i__ = 1; i__ <= i__1; ++i__) { /* STR = CYR(I)*CSGNR - CYI(I)*CSGNI */ /* CYI(I) = CYR(I)*CSGNI + CYI(I)*CSGNR */ /* CYR(I) = STR */ aa = cyr[i__]; bb = cyi[i__]; atol = 1.; /* Computing MAX */ d__1 = abs(aa), d__2 = abs(bb); if(max(d__1, d__2) > ascle) { goto L55; } aa *= rtol; bb *= rtol; atol = tol; L55: str = aa * csgnr - bb * csgni; sti = aa * csgni + bb * csgnr; cyr[i__] = str * atol; cyi[i__] = sti * atol; str = -csgni * cii; csgni = csgnr * cii; csgnr = str; /* L60: */ } return 0; L130: if(*nz == -2) { goto L140; } *nz = 0; *ierr = 2; return 0; L140: *nz = 0; *ierr = 5; return 0; L260: *nz = 0; *ierr = 4; return 0; } /* zbesj_ */ int zbesk_(double* zr, double* zi, double* fnu, int32* kode, int32* n, double* cyr, double* cyi, int32* nz, int32* ierr) { /* System generated locals */ int32 i__1, i__2; double d__1; int32 k, k1, k2; double aa, bb, fn, az; int32 nn; double rl; int32 mr, nw; double dig, arg, aln, r1m5, ufl; int32 nuf; double tol, alim, elim; double fnul; /* *********************************************************************72 */ /* c ZBESK computes a sequence of System::Complex<float> Bessel K functions. */ /* ***BEGIN PROLOGUE ZBESK */ /* ***DATE WRITTEN 830501 (YYMMDD) */ /* ***REVISION DATE 890801, 930101 (YYMMDD) */ /* ***CATEGORY NO. B5K */ /* ***KEYWORDS K-BESSEL FUNCTION,COMPLEX BESSEL FUNCTION, */ /* MODIFIED BESSEL FUNCTION OF THE SECOND KIND, */ /* BESSEL FUNCTION OF THE THIRD KIND */ /* ***AUTHOR AMOS, DONALD E., SANDIA NATIONAL LABORATORIES */ /* ***PURPOSE TO COMPUTE K-BESSEL FUNCTIONS OF COMPLEX ARGUMENT */ /* ***DESCRIPTION */ /* ***A DOUBLE PRECISION ROUTINE*** */ /* ON KODE=1, ZBESK COMPUTES AN N MEMBER SEQUENCE OF COMPLEX */ /* BESSEL FUNCTIONS CY(J)=K(FNU+J-1,Z) FOR REAL, NONNEGATIVE */ /* ORDERS FNU+J-1, J=1,...,N AND COMPLEX Z.NE.CMPLX(0.0,0.0) */ /* IN THE CUT PLANE -PI.LT.ARG(Z).LE.PI. ON KODE=2, ZBESK */ /* RETURNS THE SCALED K FUNCTIONS, */ /* CY(J)=EXP(Z)*K(FNU+J-1,Z) , J=1,...,N, */ /* WHICH REMOVE THE EXPONENTIAL BEHAVIOR IN BOTH THE LEFT AND */ /* RIGHT HALF PLANES FOR Z TO INFINITY. DEFINITIONS AND */ /* NOTATION ARE FOUND IN THE NBS HANDBOOK OF MATHEMATICAL */ /* FUNCTIONS (REF. 1). */ /* INPUT ZR,ZI,FNU ARE DOUBLE PRECISION */ /* ZR,ZI - Z=CMPLX(ZR,ZI), Z.NE.CMPLX(0.0D0,0.0D0), */ /* -PI.LT.ARG(Z).LE.PI */ /* FNU - ORDER OF INITIAL K FUNCTION, FNU.GE.0.0D0 */ /* N - NUMBER OF MEMBERS OF THE SEQUENCE, N.GE.1 */ /* KODE - A PARAMETER TO INDICATE THE SCALING OPTION */ /* KODE= 1 RETURNS */ /* CY(I)=K(FNU+I-1,Z), I=1,...,N */ /* = 2 RETURNS */ /* CY(I)=K(FNU+I-1,Z)*EXP(Z), I=1,...,N */ /* OUTPUT CYR,CYI ARE DOUBLE PRECISION */ /* CYR,CYI- DOUBLE PRECISION VECTORS WHOSE FIRST N COMPONENTS */ /* CONTAIN REAL AND IMAGINARY PARTS FOR THE SEQUENCE */ /* CY(I)=K(FNU+I-1,Z), I=1,...,N OR */ /* CY(I)=K(FNU+I-1,Z)*EXP(Z), I=1,...,N */ /* DEPENDING ON KODE */ /* NZ - NUMBER OF COMPONENTS SET TO ZERO DUE TO UNDERFLOW. */ /* NZ= 0 , NORMAL RETURN */ /* NZ.GT.0 , FIRST NZ COMPONENTS OF CY SET TO ZERO DUE */ /* TO UNDERFLOW, CY(I)=CMPLX(0.0D0,0.0D0), */ /* I=1,...,N WHEN X.GE.0.0. WHEN X.LT.0.0 */ /* NZ STATES ONLY THE NUMBER OF UNDERFLOWS */ /* IN THE SEQUENCE. */ /* IERR - ERROR FLAG */ /* IERR=0, NORMAL RETURN - COMPUTATION COMPLETED */ /* IERR=1, INPUT ERROR - NO COMPUTATION */ /* IERR=2, OVERFLOW - NO COMPUTATION, FNU IS */ /* TOO LARGE OR CABS(Z) IS TOO SMALL OR BOTH */ /* IERR=3, CABS(Z) OR FNU+N-1 LARGE - COMPUTATION DONE */ /* BUT LOSSES OF SIGNIFCANCE BY ARGUMENT */ /* REDUCTION PRODUCE LESS THAN HALF OF MACHINE */ /* ACCURACY */ /* IERR=4, CABS(Z) OR FNU+N-1 TOO LARGE - NO COMPUTA- */ /* TION BECAUSE OF COMPLETE LOSSES OF SIGNIFI- */ /* CANCE BY ARGUMENT REDUCTION */ /* IERR=5, ERROR - NO COMPUTATION, */ /* ALGORITHM TERMINATION CONDITION NOT MET */ /* ***LONG DESCRIPTION */ /* EQUATIONS OF THE REFERENCE ARE IMPLEMENTED FOR SMALL ORDERS */ /* DNU AND DNU+1.0 IN THE RIGHT HALF PLANE X.GE.0.0. FORWARD */ /* RECURRENCE GENERATES HIGHER ORDERS. K IS CONTINUED TO THE LEFT */ /* HALF PLANE BY THE RELATION */ /* K(FNU,Z*EXP(MP)) = EXP(-MP*FNU)*K(FNU,Z)-MP*I(FNU,Z) */ /* MP=MR*PI*I, MR=+1 OR -1, RE(Z).GT.0, I**2=-1 */ /* WHERE I(FNU,Z) IS THE I BESSEL FUNCTION. */ /* FOR LARGE ORDERS, FNU.GT.FNUL, THE K FUNCTION IS COMPUTED */ /* BY MEANS OF ITS UNIFORM ASYMPTOTIC EXPANSIONS. */ /* FOR NEGATIVE ORDERS, THE FORMULA */ /* K(-FNU,Z) = K(FNU,Z) */ /* CAN BE USED. */ /* ZBESK ASSUMES THAT A SIGNIFICANT DIGIT SINH(X) FUNCTION IS */ /* AVAILABLE. */ /* IN MOST COMPLEX VARIABLE COMPUTATION, ONE MUST EVALUATE ELE- */ /* MENTARY FUNCTIONS. WHEN THE MAGNITUDE OF Z OR FNU+N-1 IS */ /* LARGE, LOSSES OF SIGNIFICANCE BY ARGUMENT REDUCTION OCCUR. */ /* CONSEQUENTLY, IF EITHER ONE EXCEEDS U1=SQRT(0.5/UR), THEN */ /* LOSSES EXCEEDING HALF PRECISION ARE LIKELY AND AN ERROR FLAG */ /* IERR=3 IS TRIGGERED WHERE UR=DMAX1(D1MACH(4),1.0D-18) IS */ /* DOUBLE PRECISION UNIT ROUNDOFF LIMITED TO 18 DIGITS PRECISION. */ /* IF EITHER IS LARGER THAN U2=0.5/UR, THEN ALL SIGNIFICANCE IS */ /* LOST AND IERR=4. IN ORDER TO USE THE INT FUNCTION, ARGUMENTS */ /* MUST BE FURTHER RESTRICTED NOT TO EXCEED THE LARGEST MACHINE */ /* INTEGER, U3=I1MACH(9). THUS, THE MAGNITUDE OF Z AND FNU+N-1 IS */ /* RESTRICTED BY MIN(U2,U3). ON 32 BIT MACHINES, U1,U2, AND U3 */ /* ARE APPROXIMATELY 2.0E+3, 4.2E+6, 2.1E+9 IN SINGLE PRECISION */ /* ARITHMETIC AND 1.3E+8, 1.8E+16, 2.1E+9 IN DOUBLE PRECISION */ /* ARITHMETIC RESPECTIVELY. THIS MAKES U2 AND U3 LIMITING IN */ /* THEIR RESPECTIVE ARITHMETICS. THIS MEANS THAT ONE CAN EXPECT */ /* TO RETAIN, IN THE WORST CASES ON 32 BIT MACHINES, NO DIGITS */ /* IN SINGLE AND ONLY 7 DIGITS IN DOUBLE PRECISION ARITHMETIC. */ /* SIMILAR CONSIDERATIONS HOLD FOR OTHER MACHINES. */ /* THE APPROXIMATE RELATIVE ERROR IN THE MAGNITUDE OF A COMPLEX */ /* BESSEL FUNCTION CAN BE EXPRESSED BY P*10**S WHERE P=MAX(UNIT */ /* ROUNDOFF,1.0E-18) IS THE NOMINAL PRECISION AND 10**S REPRE- */ /* SENTS THE INCREASE IN ERROR DUE TO ARGUMENT REDUCTION IN THE */ /* ELEMENTARY FUNCTIONS. HERE, S=MAX(1,ABS(LOG10(CABS(Z))), */ /* ABS(LOG10(FNU))) APPROXIMATELY (I.E. S=MAX(1,ABS(EXPONENT OF */ /* CABS(Z),ABS(EXPONENT OF FNU)) ). HOWEVER, THE PHASE ANGLE MAY */ /* HAVE ONLY ABSOLUTE ACCURACY. THIS IS MOST LIKELY TO OCCUR WHEN */ /* ONE COMPONENT (IN ABSOLUTE VALUE) IS LARGER THAN THE OTHER BY */ /* SEVERAL ORDERS OF MAGNITUDE. IF ONE COMPONENT IS 10**K LARGER */ /* THAN THE OTHER, THEN ONE CAN EXPECT ONLY MAX(ABS(LOG10(P))-K, */ /* 0) SIGNIFICANT DIGITS; OR, STATED ANOTHER WAY, WHEN K EXCEEDS */ /* THE EXPONENT OF P, NO SIGNIFICANT DIGITS REMAIN IN THE SMALLER */ /* COMPONENT. HOWEVER, THE PHASE ANGLE RETAINS ABSOLUTE ACCURACY */ /* BECAUSE, IN COMPLEX ARITHMETIC WITH PRECISION P, THE SMALLER */ /* COMPONENT WILL NOT (AS A RULE) DECREASE BELOW P TIMES THE */ /* MAGNITUDE OF THE LARGER COMPONENT. IN THESE EXTREME CASES, */ /* THE PRINCIPAL PHASE ANGLE IS ON THE ORDER OF +P, -P, PI/2-P, */ /* OR -PI/2+P. */ /* ***REFERENCES HANDBOOK OF MATHEMATICAL FUNCTIONS BY M. ABRAMOWITZ */ /* AND I. A. STEGUN, NBS AMS SERIES 55, U.S. DEPT. OF */ /* COMMERCE, 1955. */ /* COMPUTATION OF BESSEL FUNCTIONS OF COMPLEX ARGUMENT */ /* BY D. E. AMOS, SAND83-0083, MAY, 1983. */ /* COMPUTATION OF BESSEL FUNCTIONS OF COMPLEX ARGUMENT */ /* AND LARGE ORDER BY D. E. AMOS, SAND83-0643, MAY, 1983. */ /* A SUBROUTINE PACKAGE FOR BESSEL FUNCTIONS OF A COMPLEX */ /* ARGUMENT AND NONNEGATIVE ORDER BY D. E. AMOS, SAND85- */ /* 1018, MAY, 1985 */ /* A PORTABLE PACKAGE FOR BESSEL FUNCTIONS OF A COMPLEX */ /* ARGUMENT AND NONNEGATIVE ORDER BY D. E. AMOS, ACM */ /* TRANS. MATH. SOFTWARE, VOL. 12, NO. 3, SEPTEMBER 1986, */ /* PP 265-273. */ /* ***ROUTINES CALLED ZACON,ZBKNU,ZBUNK,ZUOIK,ZABS,I1MACH,D1MACH */ /* ***END PROLOGUE ZBESK */ /* COMPLEX CY,Z */ /* ***FIRST EXECUTABLE STATEMENT ZBESK */ /* Parameter adjustments */ --cyi; --cyr; /* Function Body */ *ierr = 0; *nz = 0; if(*zi == (float)0. && *zr == (float)0.) { *ierr = 1; } if(*fnu < 0.) { *ierr = 1; } if(*kode < 1 || *kode > 2) { *ierr = 1; } if(*n < 1) { *ierr = 1; } if(*ierr != 0) { return 0; } nn = *n; /* ----------------------------------------------------------------------- */ /* SET PARAMETERS RELATED TO MACHINE CONSTANTS. */ /* TOL IS THE APPROXIMATE UNIT ROUNDOFF LIMITED TO 1.0E-18. */ /* ELIM IS THE APPROXIMATE EXPONENTIAL OVER- AND UNDERFLOW LIMIT. */ /* EXP(-ELIM).LT.EXP(-ALIM)=EXP(-ELIM)/TOL AND */ /* EXP(ELIM).GT.EXP(ALIM)=EXP(ELIM)*TOL ARE INTERVALS NEAR */ /* UNDERFLOW AND OVERFLOW LIMITS WHERE SCALED ARITHMETIC IS DONE. */ /* RL IS THE LOWER BOUNDARY OF THE ASYMPTOTIC EXPANSION FOR LARGE Z. */ /* DIG = NUMBER OF BASE 10 DIGITS IN TOL = 10**(-DIG). */ /* FNUL IS THE LOWER BOUNDARY OF THE ASYMPTOTIC SERIES FOR LARGE FNU */ /* ----------------------------------------------------------------------- */ /* Computing MAX */ d__1 = d1mach_(&c__4); tol = max(d__1, 1e-18); k1 = i1mach_(&c__15); k2 = i1mach_(&c__16); r1m5 = d1mach_(&c__5); /* Computing MIN */ i__1 = abs(k1), i__2 = abs(k2); k = std::min(i__1, i__2); elim = ((double)((float)k) * r1m5 - 3.) * 2.303; k1 = i1mach_(&c__14) - 1; aa = r1m5 * (double)((float)k1); dig = std::min(aa, 18.); aa *= 2.303; /* Computing MAX */ d__1 = -aa; alim = elim + max(d__1, -41.45); fnul = (dig - 3.) * 6. + 10.; rl = dig * 1.2 + 3.; /* ----------------------------------------------------------------------------- */ /* TEST FOR PROPER RANGE */ /* ----------------------------------------------------------------------- */ az = zabs_(zr, zi); fn = *fnu + (double)((float)(nn - 1)); aa = .5 / tol; bb = (double)((float)i1mach_(&c__9)) * .5; aa = std::min(aa, bb); if(az > aa) { goto L260; } if(fn > aa) { goto L260; } aa = sqrt(aa); if(az > aa) { *ierr = 3; } if(fn > aa) { *ierr = 3; } /* ----------------------------------------------------------------------- */ /* OVERFLOW TEST ON THE LAST MEMBER OF THE SEQUENCE */ /* ----------------------------------------------------------------------- */ /* UFL = DEXP(-ELIM) */ ufl = d1mach_(&c__1) * 1e3; if(az < ufl) { goto L180; } if(*fnu > fnul) { goto L80; } if(fn <= 1.) { goto L60; } if(fn > 2.) { goto L50; } if(az > tol) { goto L60; } arg = az * .5; aln = -fn * log(arg); if(aln > elim) { goto L180; } goto L60; L50: zuoik_(zr, zi, fnu, kode, &c__2, &nn, &cyr[1], &cyi[1], &nuf, &tol, &elim, &alim); if(nuf < 0) { goto L180; } *nz += nuf; nn -= nuf; /* ----------------------------------------------------------------------- */ /* HERE NN=N OR NN=0 SINCE NUF=0,NN, OR -1 ON RETURN FROM CUOIK */ /* IF NUF=NN, THEN CY(I)=CZERO FOR ALL I */ /* ----------------------------------------------------------------------- */ if(nn == 0) { goto L100; } L60: if(*zr < 0.) { goto L70; } /* ----------------------------------------------------------------------- */ /* RIGHT HALF PLANE COMPUTATION, REAL(Z).GE.0. */ /* ----------------------------------------------------------------------- */ zbknu_(zr, zi, fnu, kode, &nn, &cyr[1], &cyi[1], &nw, &tol, &elim, &alim); if(nw < 0) { goto L200; } *nz = nw; return 0; /* ----------------------------------------------------------------------- */ /* LEFT HALF PLANE COMPUTATION */ /* PI/2.LT.ARG(Z).LE.PI AND -PI.LT.ARG(Z).LT.-PI/2. */ /* ----------------------------------------------------------------------- */ L70: if(*nz != 0) { goto L180; } mr = 1; if(*zi < 0.) { mr = -1; } zacon_(zr, zi, fnu, kode, &mr, &nn, &cyr[1], &cyi[1], &nw, &rl, &fnul, &tol, &elim, &alim); if(nw < 0) { goto L200; } *nz = nw; return 0; /* ----------------------------------------------------------------------- */ /* UNIFORM ASYMPTOTIC EXPANSIONS FOR FNU.GT.FNUL */ /* ----------------------------------------------------------------------- */ L80: mr = 0; if(*zr >= 0.) { goto L90; } mr = 1; if(*zi < 0.) { mr = -1; } L90: zbunk_(zr, zi, fnu, kode, &mr, &nn, &cyr[1], &cyi[1], &nw, &tol, &elim, &alim); if(nw < 0) { goto L200; } *nz += nw; return 0; L100: if(*zr < 0.) { goto L180; } return 0; L180: *nz = 0; *ierr = 2; return 0; L200: if(nw == -1) { goto L180; } *nz = 0; *ierr = 5; return 0; L260: *nz = 0; *ierr = 4; return 0; } /* zbesk_ */ int zbesy_(double* zr, double* zi, double* fnu, int32* kode, int32* n, double* cyr, double* cyi, int32* nz, double* cwrkr, double* cwrki, int32* ierr) { /* Initialized data */ static double cipr[4] = {1., 0., -1., 0.}; static double cipi[4] = {0., 1., 0., -1.}; static double hpi = 1.57079632679489662; /* System generated locals */ int32 i__1, i__2; double d__1, d__2; int32 i__, k, k1, i4, k2; double ey; int32 nz1, nz2; double d1m5, arg, exi, exr, sti, tay, tol, zni, zui, str, znr, zvi, zzi, zur, zvr, zzr, elim, ffnu, atol, rhpi; int32 ifnu; double rtol, ascle, csgni, csgnr, cspni; double cspnr; /* *********************************************************************72 */ /* c ZBESY computes a sequence of System::Complex<float> Bessel Y functions. */ /* ***BEGIN PROLOGUE ZBESY */ /* ***DATE WRITTEN 830501 (YYMMDD) */ /* ***REVISION DATE 890801, 930101 (YYMMDD) */ /* ***CATEGORY NO. B5K */ /* ***KEYWORDS Y-BESSEL FUNCTION,BESSEL FUNCTION OF COMPLEX ARGUMENT, */ /* BESSEL FUNCTION OF SECOND KIND */ /* ***AUTHOR AMOS, DONALD E., SANDIA NATIONAL LABORATORIES */ /* ***PURPOSE TO COMPUTE THE Y-BESSEL FUNCTION OF A COMPLEX ARGUMENT */ /* ***DESCRIPTION */ /* ***A DOUBLE PRECISION ROUTINE*** */ /* ON KODE=1, ZBESY COMPUTES AN N MEMBER SEQUENCE OF COMPLEX */ /* BESSEL FUNCTIONS CY(I)=Y(FNU+I-1,Z) FOR REAL, NONNEGATIVE */ /* ORDERS FNU+I-1, I=1,...,N AND COMPLEX Z IN THE CUT PLANE */ /* -PI.LT.ARG(Z).LE.PI. ON KODE=2, ZBESY RETURNS THE SCALED */ /* FUNCTIONS */ /* CY(I)=EXP(-ABS(Y))*Y(FNU+I-1,Z) I = 1,...,N , Y=AIMAG(Z) */ /* WHICH REMOVE THE EXPONENTIAL GROWTH IN BOTH THE UPPER AND */ /* LOWER HALF PLANES FOR Z TO INFINITY. DEFINITIONS AND NOTATION */ /* ARE FOUND IN THE NBS HANDBOOK OF MATHEMATICAL FUNCTIONS */ /* (REF. 1). */ /* INPUT ZR,ZI,FNU ARE DOUBLE PRECISION */ /* ZR,ZI - Z=CMPLX(ZR,ZI), Z.NE.CMPLX(0.0D0,0.0D0), */ /* -PI.LT.ARG(Z).LE.PI */ /* FNU - ORDER OF INITIAL Y FUNCTION, FNU.GE.0.0D0 */ /* KODE - A PARAMETER TO INDICATE THE SCALING OPTION */ /* KODE= 1 RETURNS */ /* CY(I)=Y(FNU+I-1,Z), I=1,...,N */ /* = 2 RETURNS */ /* CY(I)=Y(FNU+I-1,Z)*EXP(-ABS(Y)), I=1,...,N */ /* WHERE Y=AIMAG(Z) */ /* N - NUMBER OF MEMBERS OF THE SEQUENCE, N.GE.1 */ /* CWRKR, - DOUBLE PRECISION WORK VECTORS OF DIMENSION AT */ /* CWRKI AT LEAST N */ /* OUTPUT CYR,CYI ARE DOUBLE PRECISION */ /* CYR,CYI- DOUBLE PRECISION VECTORS WHOSE FIRST N COMPONENTS */ /* CONTAIN REAL AND IMAGINARY PARTS FOR THE SEQUENCE */ /* CY(I)=Y(FNU+I-1,Z) OR */ /* CY(I)=Y(FNU+I-1,Z)*EXP(-ABS(Y)) I=1,...,N */ /* DEPENDING ON KODE. */ /* NZ - NZ=0 , A NORMAL RETURN */ /* NZ.GT.0 , NZ COMPONENTS OF CY SET TO ZERO DUE TO */ /* UNDERFLOW (GENERALLY ON KODE=2) */ /* IERR - ERROR FLAG */ /* IERR=0, NORMAL RETURN - COMPUTATION COMPLETED */ /* IERR=1, INPUT ERROR - NO COMPUTATION */ /* IERR=2, OVERFLOW - NO COMPUTATION, FNU IS */ /* TOO LARGE OR CABS(Z) IS TOO SMALL OR BOTH */ /* IERR=3, CABS(Z) OR FNU+N-1 LARGE - COMPUTATION DONE */ /* BUT LOSSES OF SIGNIFCANCE BY ARGUMENT */ /* REDUCTION PRODUCE LESS THAN HALF OF MACHINE */ /* ACCURACY */ /* IERR=4, CABS(Z) OR FNU+N-1 TOO LARGE - NO COMPUTA- */ /* TION BECAUSE OF COMPLETE LOSSES OF SIGNIFI- */ /* CANCE BY ARGUMENT REDUCTION */ /* IERR=5, ERROR - NO COMPUTATION, */ /* ALGORITHM TERMINATION CONDITION NOT MET */ /* ***LONG DESCRIPTION */ /* THE COMPUTATION IS CARRIED OUT IN TERMS OF THE I(FNU,Z) AND */ /* K(FNU,Z) BESSEL FUNCTIONS IN THE RIGHT HALF PLANE BY */ /* Y(FNU,Z) = I*CC*I(FNU,ARG) - (2/PI)*CONJG(CC)*K(FNU,ARG) */ /* Y(FNU,Z) = CONJG(Y(FNU,CONJG(Z))) */ /* FOR AIMAG(Z).GE.0 AND AIMAG(Z).LT.0 RESPECTIVELY, WHERE */ /* CC=EXP(I*PI*FNU/2), ARG=Z*EXP(-I*PI/2) AND I**2=-1. */ /* FOR NEGATIVE ORDERS,THE FORMULA */ /* Y(-FNU,Z) = Y(FNU,Z)*COS(PI*FNU) + J(FNU,Z)*SIN(PI*FNU) */ /* CAN BE USED. HOWEVER,FOR LARGE ORDERS CLOSE TO HALF ODD */ /* INTEGERS THE FUNCTION CHANGES RADICALLY. WHEN FNU IS A LARGE */ /* POSITIVE HALF ODD INTEGER,THE MAGNITUDE OF Y(-FNU,Z)=J(FNU,Z)* */ /* SIN(PI*FNU) IS A LARGE NEGATIVE POWER OF TEN. BUT WHEN FNU IS */ /* NOT A HALF ODD INTEGER, Y(FNU,Z) DOMINATES IN MAGNITUDE WITH A */ /* LARGE POSITIVE POWER OF TEN AND THE MOST THAT THE SECOND TERM */ /* CAN BE REDUCED IS BY UNIT ROUNDOFF FROM THE COEFFICIENT. THUS, */ /* WIDE CHANGES CAN OCCUR WITHIN UNIT ROUNDOFF OF A LARGE HALF */ /* ODD INTEGER. HERE, LARGE MEANS FNU.GT.CABS(Z). */ /* IN MOST COMPLEX VARIABLE COMPUTATION, ONE MUST EVALUATE ELE- */ /* MENTARY FUNCTIONS. WHEN THE MAGNITUDE OF Z OR FNU+N-1 IS */ /* LARGE, LOSSES OF SIGNIFICANCE BY ARGUMENT REDUCTION OCCUR. */ /* CONSEQUENTLY, IF EITHER ONE EXCEEDS U1=SQRT(0.5/UR), THEN */ /* LOSSES EXCEEDING HALF PRECISION ARE LIKELY AND AN ERROR FLAG */ /* IERR=3 IS TRIGGERED WHERE UR=DMAX1(D1MACH(4),1.0D-18) IS */ /* DOUBLE PRECISION UNIT ROUNDOFF LIMITED TO 18 DIGITS PRECISION. */ /* IF EITHER IS LARGER THAN U2=0.5/UR, THEN ALL SIGNIFICANCE IS */ /* LOST AND IERR=4. IN ORDER TO USE THE INT FUNCTION, ARGUMENTS */ /* MUST BE FURTHER RESTRICTED NOT TO EXCEED THE LARGEST MACHINE */ /* INTEGER, U3=I1MACH(9). THUS, THE MAGNITUDE OF Z AND FNU+N-1 IS */ /* RESTRICTED BY MIN(U2,U3). ON 32 BIT MACHINES, U1,U2, AND U3 */ /* ARE APPROXIMATELY 2.0E+3, 4.2E+6, 2.1E+9 IN SINGLE PRECISION */ /* ARITHMETIC AND 1.3E+8, 1.8E+16, 2.1E+9 IN DOUBLE PRECISION */ /* ARITHMETIC RESPECTIVELY. THIS MAKES U2 AND U3 LIMITING IN */ /* THEIR RESPECTIVE ARITHMETICS. THIS MEANS THAT ONE CAN EXPECT */ /* TO RETAIN, IN THE WORST CASES ON 32 BIT MACHINES, NO DIGITS */ /* IN SINGLE AND ONLY 7 DIGITS IN DOUBLE PRECISION ARITHMETIC. */ /* SIMILAR CONSIDERATIONS HOLD FOR OTHER MACHINES. */ /* THE APPROXIMATE RELATIVE ERROR IN THE MAGNITUDE OF A COMPLEX */ /* BESSEL FUNCTION CAN BE EXPRESSED BY P*10**S WHERE P=MAX(UNIT */ /* ROUNDOFF,1.0E-18) IS THE NOMINAL PRECISION AND 10**S REPRE- */ /* SENTS THE INCREASE IN ERROR DUE TO ARGUMENT REDUCTION IN THE */ /* ELEMENTARY FUNCTIONS. HERE, S=MAX(1,ABS(LOG10(CABS(Z))), */ /* ABS(LOG10(FNU))) APPROXIMATELY (I.E. S=MAX(1,ABS(EXPONENT OF */ /* CABS(Z),ABS(EXPONENT OF FNU)) ). HOWEVER, THE PHASE ANGLE MAY */ /* HAVE ONLY ABSOLUTE ACCURACY. THIS IS MOST LIKELY TO OCCUR WHEN */ /* ONE COMPONENT (IN ABSOLUTE VALUE) IS LARGER THAN THE OTHER BY */ /* SEVERAL ORDERS OF MAGNITUDE. IF ONE COMPONENT IS 10**K LARGER */ /* THAN THE OTHER, THEN ONE CAN EXPECT ONLY MAX(ABS(LOG10(P))-K, */ /* 0) SIGNIFICANT DIGITS; OR, STATED ANOTHER WAY, WHEN K EXCEEDS */ /* THE EXPONENT OF P, NO SIGNIFICANT DIGITS REMAIN IN THE SMALLER */ /* COMPONENT. HOWEVER, THE PHASE ANGLE RETAINS ABSOLUTE ACCURACY */ /* BECAUSE, IN COMPLEX ARITHMETIC WITH PRECISION P, THE SMALLER */ /* COMPONENT WILL NOT (AS A RULE) DECREASE BELOW P TIMES THE */ /* MAGNITUDE OF THE LARGER COMPONENT. IN THESE EXTREME CASES, */ /* THE PRINCIPAL PHASE ANGLE IS ON THE ORDER OF +P, -P, PI/2-P, */ /* OR -PI/2+P. */ /* ***REFERENCES HANDBOOK OF MATHEMATICAL FUNCTIONS BY M. ABRAMOWITZ */ /* AND I. A. STEGUN, NBS AMS SERIES 55, U.S. DEPT. OF */ /* COMMERCE, 1955. */ /* COMPUTATION OF BESSEL FUNCTIONS OF COMPLEX ARGUMENT */ /* BY D. E. AMOS, SAND83-0083, MAY, 1983. */ /* COMPUTATION OF BESSEL FUNCTIONS OF COMPLEX ARGUMENT */ /* AND LARGE ORDER BY D. E. AMOS, SAND83-0643, MAY, 1983 */ /* A SUBROUTINE PACKAGE FOR BESSEL FUNCTIONS OF A COMPLEX */ /* ARGUMENT AND NONNEGATIVE ORDER BY D. E. AMOS, SAND85- */ /* 1018, MAY, 1985 */ /* A PORTABLE PACKAGE FOR BESSEL FUNCTIONS OF A COMPLEX */ /* ARGUMENT AND NONNEGATIVE ORDER BY D. E. AMOS, ACM */ /* TRANS. MATH. SOFTWARE, VOL. 12, NO. 3, SEPTEMBER 1986, */ /* PP 265-273. */ /* ***ROUTINES CALLED ZBESI,ZBESK,I1MACH,D1MACH */ /* ***END PROLOGUE ZBESY */ /* COMPLEX CWRK,CY,C1,C2,EX,HCI,Z,ZU,ZV */ /* Parameter adjustments */ --cwrki; --cwrkr; --cyi; --cyr; /* Function Body */ /* ***FIRST EXECUTABLE STATEMENT ZBESY */ *ierr = 0; *nz = 0; if(*zr == 0. && *zi == 0.) { *ierr = 1; } if(*fnu < 0.) { *ierr = 1; } if(*kode < 1 || *kode > 2) { *ierr = 1; } if(*n < 1) { *ierr = 1; } if(*ierr != 0) { return 0; } zzr = *zr; zzi = *zi; if(*zi < 0.) { zzi = -zzi; } znr = zzi; zni = -zzr; zbesi_(&znr, &zni, fnu, kode, n, &cyr[1], &cyi[1], &nz1, ierr); if(*ierr != 0 && *ierr != 3) { goto L90; } zbesk_(&znr, &zni, fnu, kode, n, &cwrkr[1], &cwrki[1], &nz2, ierr); if(*ierr != 0 && *ierr != 3) { goto L90; } *nz = std::min(nz1, nz2); ifnu = (int32)((float)(*fnu)); ffnu = *fnu - (double)((float)ifnu); arg = hpi * ffnu; csgnr = cos(arg); csgni = sin(arg); i4 = ifnu % 4 + 1; str = csgnr * cipr[i4 - 1] - csgni * cipi[i4 - 1]; csgni = csgnr * cipi[i4 - 1] + csgni * cipr[i4 - 1]; csgnr = str; rhpi = 1. / hpi; cspnr = csgnr * rhpi; cspni = -csgni * rhpi; str = -csgni; csgni = csgnr; csgnr = str; if(*kode == 2) { goto L60; } i__1 = *n; for(i__ = 1; i__ <= i__1; ++i__) { /* CY(I) = CSGN*CY(I)-CSPN*CWRK(I) */ str = csgnr * cyr[i__] - csgni * cyi[i__]; str -= cspnr * cwrkr[i__] - cspni * cwrki[i__]; sti = csgnr * cyi[i__] + csgni * cyr[i__]; sti -= cspnr * cwrki[i__] + cspni * cwrkr[i__]; cyr[i__] = str; cyi[i__] = sti; str = -csgni; csgni = csgnr; csgnr = str; str = cspni; cspni = -cspnr; cspnr = str; /* L50: */ } if(*zi < 0.) { i__1 = *n; for(i__ = 1; i__ <= i__1; ++i__) { cyi[i__] = -cyi[i__]; /* L55: */ } } return 0; L60: exr = cos(*zr); exi = sin(*zr); /* Computing MAX */ d__1 = d1mach_(&c__4); tol = max(d__1, 1e-18); k1 = i1mach_(&c__15); k2 = i1mach_(&c__16); /* Computing MIN */ i__1 = abs(k1), i__2 = abs(k2); k = std::min(i__1, i__2); d1m5 = d1mach_(&c__5); /* ----------------------------------------------------------------------- */ /* ELIM IS THE APPROXIMATE EXPONENTIAL UNDER- AND OVERFLOW LIMIT */ /* ----------------------------------------------------------------------- */ elim = ((double)((float)k) * d1m5 - 3.) * 2.303; ey = 0.; tay = (d__1 = *zi + *zi, abs(d__1)); if(tay < elim) { ey = exp(-tay); } str = (exr * cspnr - exi * cspni) * ey; cspni = (exr * cspni + exi * cspnr) * ey; cspnr = str; *nz = 0; rtol = 1. / tol; ascle = d1mach_(&c__1) * rtol * 1e3; i__1 = *n; for(i__ = 1; i__ <= i__1; ++i__) { /* ---------------------------------------------------------------------- */ /* CY(I) = CSGN*CY(I)-CSPN*CWRK(I): PRODUCTS ARE COMPUTED IN */ /* SCALED MODE IF CY(I) OR CWRK(I) ARE CLOSE TO UNDERFLOW TO */ /* PREVENT UNDERFLOW IN AN INTERMEDIATE COMPUTATION. */ /* ---------------------------------------------------------------------- */ zvr = cwrkr[i__]; zvi = cwrki[i__]; atol = 1.; /* Computing MAX */ d__1 = abs(zvr), d__2 = abs(zvi); if(max(d__1, d__2) > ascle) { goto L75; } zvr *= rtol; zvi *= rtol; atol = tol; L75: str = (zvr * cspnr - zvi * cspni) * atol; zvi = (zvr * cspni + zvi * cspnr) * atol; zvr = str; zur = cyr[i__]; zui = cyi[i__]; atol = 1.; /* Computing MAX */ d__1 = abs(zur), d__2 = abs(zui); if(max(d__1, d__2) > ascle) { goto L85; } zur *= rtol; zui *= rtol; atol = tol; L85: str = (zur * csgnr - zui * csgni) * atol; zui = (zur * csgni + zui * csgnr) * atol; zur = str; cyr[i__] = zur - zvr; cyi[i__] = zui - zvi; if(*zi < 0.) { cyi[i__] = -cyi[i__]; } if(cyr[i__] == 0. && cyi[i__] == 0. && ey == 0.) { ++(*nz); } str = -csgni; csgni = csgnr; csgnr = str; str = cspni; cspni = -cspnr; cspnr = str; /* L80: */ } return 0; L90: *nz = 0; return 0; } /* zbesy_ */ int zbinu_(double* zr, double* zi, double* fnu, int32* kode, int32* n, double* cyr, double* cyi, int32* nz, double* rl, double* fnul, double* tol, double* elim, double* alim) { /* Initialized data */ static double zeror = 0.; static double zeroi = 0.; /* System generated locals */ int32 i__1; int32 i__; double az; int32 nn, nw; double cwi[2], cwr[2]; int32 nui, inw; double dfnu; int32 nlast; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE ZBINU */ /* ***REFER TO ZBESH,ZBESI,ZBESJ,ZBESK,ZAIRY,ZBIRY */ /* ZBINU COMPUTES THE I FUNCTION IN THE RIGHT HALF Z PLANE */ /* ***ROUTINES CALLED ZABS,ZASYI,ZBUNI,ZMLRI,ZSERI,ZUOIK,ZWRSK */ /* ***END PROLOGUE ZBINU */ /* Parameter adjustments */ --cyi; --cyr; /* Function Body */ *nz = 0; az = zabs_(zr, zi); nn = *n; dfnu = *fnu + (double)((float)(*n - 1)); if(az <= 2.) { goto L10; } if(az * az * .25 > dfnu + 1.) { goto L20; } L10: /* ----------------------------------------------------------------------- */ /* POWER SERIES */ /* ----------------------------------------------------------------------- */ zseri_(zr, zi, fnu, kode, &nn, &cyr[1], &cyi[1], &nw, tol, elim, alim); inw = abs(nw); *nz += inw; nn -= inw; if(nn == 0) { return 0; } if(nw >= 0) { goto L120; } dfnu = *fnu + (double)((float)(nn - 1)); L20: if(az < *rl) { goto L40; } if(dfnu <= 1.) { goto L30; } if(az + az < dfnu * dfnu) { goto L50; } /* ----------------------------------------------------------------------- */ /* ASYMPTOTIC EXPANSION FOR LARGE Z */ /* ----------------------------------------------------------------------- */ L30: zasyi_(zr, zi, fnu, kode, &nn, &cyr[1], &cyi[1], &nw, rl, tol, elim, alim); if(nw < 0) { goto L130; } goto L120; L40: if(dfnu <= 1.) { goto L70; } L50: /* ----------------------------------------------------------------------- */ /* OVERFLOW AND UNDERFLOW TEST ON I SEQUENCE FOR MILLER ALGORITHM */ /* ----------------------------------------------------------------------- */ zuoik_(zr, zi, fnu, kode, &c__1, &nn, &cyr[1], &cyi[1], &nw, tol, elim, alim); if(nw < 0) { goto L130; } *nz += nw; nn -= nw; if(nn == 0) { return 0; } dfnu = *fnu + (double)((float)(nn - 1)); if(dfnu > *fnul) { goto L110; } if(az > *fnul) { goto L110; } L60: if(az > *rl) { goto L80; } L70: /* ----------------------------------------------------------------------- */ /* MILLER ALGORITHM NORMALIZED BY THE SERIES */ /* ----------------------------------------------------------------------- */ zmlri_(zr, zi, fnu, kode, &nn, &cyr[1], &cyi[1], &nw, tol); if(nw < 0) { goto L130; } goto L120; L80: /* ----------------------------------------------------------------------- */ /* MILLER ALGORITHM NORMALIZED BY THE WRONSKIAN */ /* ----------------------------------------------------------------------- */ /* ----------------------------------------------------------------------- */ /* OVERFLOW TEST ON K FUNCTIONS USED IN WRONSKIAN */ /* ----------------------------------------------------------------------- */ zuoik_(zr, zi, fnu, kode, &c__2, &c__2, cwr, cwi, &nw, tol, elim, alim); if(nw >= 0) { goto L100; } *nz = nn; i__1 = nn; for(i__ = 1; i__ <= i__1; ++i__) { cyr[i__] = zeror; cyi[i__] = zeroi; /* L90: */ } return 0; L100: if(nw > 0) { goto L130; } zwrsk_(zr, zi, fnu, kode, &nn, &cyr[1], &cyi[1], &nw, cwr, cwi, tol, elim, alim); if(nw < 0) { goto L130; } goto L120; L110: /* ----------------------------------------------------------------------- */ /* INCREMENT FNU+NN-1 UP TO FNUL, COMPUTE AND RECUR BACKWARD */ /* ----------------------------------------------------------------------- */ nui = (int32)((float)(*fnul - dfnu)) + 1; nui = max(nui, 0); zbuni_(zr, zi, fnu, kode, &nn, &cyr[1], &cyi[1], &nw, &nui, &nlast, fnul, tol, elim, alim); if(nw < 0) { goto L130; } *nz += nw; if(nlast == 0) { goto L120; } nn = nlast; goto L60; L120: return 0; L130: *nz = -1; if(nw == -2) { *nz = -2; } return 0; } /* zbinu_ */ int zbiry_(double* zr, double* zi, int32* id, int32* kode, double* bir, double* bii, int32* ierr) { /* Initialized data */ static double tth = .666666666666666667; static double c1 = .614926627446000736; static double c2 = .448288357353826359; static double coef = .577350269189625765; static double pi = 3.14159265358979324; static double coner = 1.; static double conei = 0.; /* System generated locals */ int32 i__1, i__2; double d__1; int32 k; double d1, d2; int32 k1, k2; double aa, bb, ad, cc, ak, bk, ck, dk, az, rl; int32 nz; double s1i, az3, s2i, s1r, s2r, z3i, z3r, eaa, fid, dig, cyi[2], fmr, r1m5, fnu, cyr[2], tol, sti, str, sfac, alim, elim; double csqi, atrm, fnul, ztai, csqr; double ztar, trm1i, trm2i, trm1r, trm2r; /* *********************************************************************72 */ /* c ZBIRY computes a sequence of System::Complex<float> Airy Bi functions. */ /* ***BEGIN PROLOGUE ZBIRY */ /* ***DATE WRITTEN 830501 (YYMMDD) */ /* ***REVISION DATE 890801, 930101 (YYMMDD) */ /* ***CATEGORY NO. B5K */ /* ***KEYWORDS AIRY FUNCTION,BESSEL FUNCTIONS OF ORDER ONE THIRD */ /* ***AUTHOR AMOS, DONALD E., SANDIA NATIONAL LABORATORIES */ /* ***PURPOSE TO COMPUTE AIRY FUNCTIONS BI(Z) AND DBI(Z) FOR COMPLEX Z */ /* ***DESCRIPTION */ /* ***A DOUBLE PRECISION ROUTINE*** */ /* ON KODE=1, CBIRY COMPUTES THE COMPLEX AIRY FUNCTION BI(Z) OR */ /* ITS DERIVATIVE DBI(Z)/DZ ON ID=0 OR ID=1 RESPECTIVELY. ON */ /* KODE=2, A SCALING OPTION CEXP(-AXZTA)*BI(Z) OR CEXP(-AXZTA)* */ /* DBI(Z)/DZ IS PROVIDED TO REMOVE THE EXPONENTIAL BEHAVIOR IN */ /* BOTH THE LEFT AND RIGHT HALF PLANES WHERE */ /* ZTA=(2/3)*Z*CSQRT(Z)=CMPLX(XZTA,YZTA) AND AXZTA=ABS(XZTA). */ /* DEFINTIONS AND NOTATION ARE FOUND IN THE NBS HANDBOOK OF */ /* MATHEMATICAL FUNCTIONS (REF. 1). */ /* INPUT ZR,ZI ARE DOUBLE PRECISION */ /* ZR,ZI - Z=CMPLX(ZR,ZI) */ /* ID - ORDER OF DERIVATIVE, ID=0 OR ID=1 */ /* KODE - A PARAMETER TO INDICATE THE SCALING OPTION */ /* KODE= 1 RETURNS */ /* BI=BI(Z) ON ID=0 OR */ /* BI=DBI(Z)/DZ ON ID=1 */ /* = 2 RETURNS */ /* BI=CEXP(-AXZTA)*BI(Z) ON ID=0 OR */ /* BI=CEXP(-AXZTA)*DBI(Z)/DZ ON ID=1 WHERE */ /* ZTA=(2/3)*Z*CSQRT(Z)=CMPLX(XZTA,YZTA) */ /* AND AXZTA=ABS(XZTA) */ /* OUTPUT BIR,BII ARE DOUBLE PRECISION */ /* BIR,BII- COMPLEX ANSWER DEPENDING ON THE CHOICES FOR ID AND */ /* KODE */ /* IERR - ERROR FLAG */ /* IERR=0, NORMAL RETURN - COMPUTATION COMPLETED */ /* IERR=1, INPUT ERROR - NO COMPUTATION */ /* IERR=2, OVERFLOW - NO COMPUTATION, REAL(Z) */ /* TOO LARGE ON KODE=1 */ /* IERR=3, CABS(Z) LARGE - COMPUTATION COMPLETED */ /* LOSSES OF SIGNIFCANCE BY ARGUMENT REDUCTION */ /* PRODUCE LESS THAN HALF OF MACHINE ACCURACY */ /* IERR=4, CABS(Z) TOO LARGE - NO COMPUTATION */ /* COMPLETE LOSS OF ACCURACY BY ARGUMENT */ /* REDUCTION */ /* IERR=5, ERROR - NO COMPUTATION, */ /* ALGORITHM TERMINATION CONDITION NOT MET */ /* ***LONG DESCRIPTION */ /* BI AND DBI ARE COMPUTED FOR CABS(Z).GT.1.0 FROM THE I BESSEL */ /* FUNCTIONS BY */ /* BI(Z)=C*SQRT(Z)*( I(-1/3,ZTA) + I(1/3,ZTA) ) */ /* DBI(Z)=C * Z * ( I(-2/3,ZTA) + I(2/3,ZTA) ) */ /* C=1.0/SQRT(3.0) */ /* ZTA=(2/3)*Z**(3/2) */ /* WITH THE POWER SERIES FOR CABS(Z).LE.1.0. */ /* IN MOST COMPLEX VARIABLE COMPUTATION, ONE MUST EVALUATE ELE- */ /* MENTARY FUNCTIONS. WHEN THE MAGNITUDE OF Z IS LARGE, LOSSES */ /* OF SIGNIFICANCE BY ARGUMENT REDUCTION OCCUR. CONSEQUENTLY, IF */ /* THE MAGNITUDE OF ZETA=(2/3)*Z**1.5 EXCEEDS U1=SQRT(0.5/UR), */ /* THEN LOSSES EXCEEDING HALF PRECISION ARE LIKELY AND AN ERROR */ /* FLAG IERR=3 IS TRIGGERED WHERE UR=DMAX1(D1MACH(4),1.0D-18) IS */ /* DOUBLE PRECISION UNIT ROUNDOFF LIMITED TO 18 DIGITS PRECISION. */ /* ALSO, IF THE MAGNITUDE OF ZETA IS LARGER THAN U2=0.5/UR, THEN */ /* ALL SIGNIFICANCE IS LOST AND IERR=4. IN ORDER TO USE THE INT */ /* FUNCTION, ZETA MUST BE FURTHER RESTRICTED NOT TO EXCEED THE */ /* LARGEST INTEGER, U3=I1MACH(9). THUS, THE MAGNITUDE OF ZETA */ /* MUST BE RESTRICTED BY MIN(U2,U3). ON 32 BIT MACHINES, U1,U2, */ /* AND U3 ARE APPROXIMATELY 2.0E+3, 4.2E+6, 2.1E+9 IN SINGLE */ /* PRECISION ARITHMETIC AND 1.3E+8, 1.8E+16, 2.1E+9 IN DOUBLE */ /* PRECISION ARITHMETIC RESPECTIVELY. THIS MAKES U2 AND U3 LIMIT- */ /* ING IN THEIR RESPECTIVE ARITHMETICS. THIS MEANS THAT THE MAG- */ /* NITUDE OF Z CANNOT EXCEED 3.1E+4 IN SINGLE AND 2.1E+6 IN */ /* DOUBLE PRECISION ARITHMETIC. THIS ALSO MEANS THAT ONE CAN */ /* EXPECT TO RETAIN, IN THE WORST CASES ON 32 BIT MACHINES, */ /* NO DIGITS IN SINGLE PRECISION AND ONLY 7 DIGITS IN DOUBLE */ /* PRECISION ARITHMETIC. SIMILAR CONSIDERATIONS HOLD FOR OTHER */ /* MACHINES. */ /* THE APPROXIMATE RELATIVE ERROR IN THE MAGNITUDE OF A COMPLEX */ /* BESSEL FUNCTION CAN BE EXPRESSED BY P*10**S WHERE P=MAX(UNIT */ /* ROUNDOFF,1.0E-18) IS THE NOMINAL PRECISION AND 10**S REPRE- */ /* SENTS THE INCREASE IN ERROR DUE TO ARGUMENT REDUCTION IN THE */ /* ELEMENTARY FUNCTIONS. HERE, S=MAX(1,ABS(LOG10(CABS(Z))), */ /* ABS(LOG10(FNU))) APPROXIMATELY (I.E. S=MAX(1,ABS(EXPONENT OF */ /* CABS(Z),ABS(EXPONENT OF FNU)) ). HOWEVER, THE PHASE ANGLE MAY */ /* HAVE ONLY ABSOLUTE ACCURACY. THIS IS MOST LIKELY TO OCCUR WHEN */ /* ONE COMPONENT (IN ABSOLUTE VALUE) IS LARGER THAN THE OTHER BY */ /* SEVERAL ORDERS OF MAGNITUDE. IF ONE COMPONENT IS 10**K LARGER */ /* THAN THE OTHER, THEN ONE CAN EXPECT ONLY MAX(ABS(LOG10(P))-K, */ /* 0) SIGNIFICANT DIGITS; OR, STATED ANOTHER WAY, WHEN K EXCEEDS */ /* THE EXPONENT OF P, NO SIGNIFICANT DIGITS REMAIN IN THE SMALLER */ /* COMPONENT. HOWEVER, THE PHASE ANGLE RETAINS ABSOLUTE ACCURACY */ /* BECAUSE, IN COMPLEX ARITHMETIC WITH PRECISION P, THE SMALLER */ /* COMPONENT WILL NOT (AS A RULE) DECREASE BELOW P TIMES THE */ /* MAGNITUDE OF THE LARGER COMPONENT. IN THESE EXTREME CASES, */ /* THE PRINCIPAL PHASE ANGLE IS ON THE ORDER OF +P, -P, PI/2-P, */ /* OR -PI/2+P. */ /* ***REFERENCES HANDBOOK OF MATHEMATICAL FUNCTIONS BY M. ABRAMOWITZ */ /* AND I. A. STEGUN, NBS AMS SERIES 55, U.S. DEPT. OF */ /* COMMERCE, 1955. */ /* COMPUTATION OF BESSEL FUNCTIONS OF COMPLEX ARGUMENT */ /* AND LARGE ORDER BY D. E. AMOS, SAND83-0643, MAY, 1983 */ /* A SUBROUTINE PACKAGE FOR BESSEL FUNCTIONS OF A COMPLEX */ /* ARGUMENT AND NONNEGATIVE ORDER BY D. E. AMOS, SAND85- */ /* 1018, MAY, 1985 */ /* A PORTABLE PACKAGE FOR BESSEL FUNCTIONS OF A COMPLEX */ /* ARGUMENT AND NONNEGATIVE ORDER BY D. E. AMOS, ACM */ /* TRANS. MATH. SOFTWARE, VOL. 12, NO. 3, SEPTEMBER 1986, */ /* PP 265-273. */ /* ***ROUTINES CALLED ZBINU,ZABS,ZDIV,ZSQRT,D1MACH,I1MACH */ /* ***END PROLOGUE ZBIRY */ /* COMPLEX BI,CONE,CSQ,CY,S1,S2,TRM1,TRM2,Z,ZTA,Z3 */ /* ***FIRST EXECUTABLE STATEMENT ZBIRY */ *ierr = 0; nz = 0; if(*id < 0 || *id > 1) { *ierr = 1; } if(*kode < 1 || *kode > 2) { *ierr = 1; } if(*ierr != 0) { return 0; } az = zabs_(zr, zi); /* Computing MAX */ d__1 = d1mach_(&c__4); tol = max(d__1, 1e-18); fid = (double)((float)(*id)); if(az > (float)1.) { goto L70; } /* ----------------------------------------------------------------------- */ /* POWER SERIES FOR CABS(Z).LE.1. */ /* ----------------------------------------------------------------------- */ s1r = coner; s1i = conei; s2r = coner; s2i = conei; if(az < tol) { goto L130; } aa = az * az; if(aa < tol / az) { goto L40; } trm1r = coner; trm1i = conei; trm2r = coner; trm2i = conei; atrm = 1.; str = *zr * *zr - *zi * *zi; sti = *zr * *zi + *zi * *zr; z3r = str * *zr - sti * *zi; z3i = str * *zi + sti * *zr; az3 = az * aa; ak = fid + 2.; bk = 3. - fid - fid; ck = 4. - fid; dk = fid + 3. + fid; d1 = ak * dk; d2 = bk * ck; ad = std::min(d1, d2); ak = fid * 9. + 24.; bk = 30. - fid * 9.; for(k = 1; k <= 25; ++k) { str = (trm1r * z3r - trm1i * z3i) / d1; trm1i = (trm1r * z3i + trm1i * z3r) / d1; trm1r = str; s1r += trm1r; s1i += trm1i; str = (trm2r * z3r - trm2i * z3i) / d2; trm2i = (trm2r * z3i + trm2i * z3r) / d2; trm2r = str; s2r += trm2r; s2i += trm2i; atrm = atrm * az3 / ad; d1 += ak; d2 += bk; ad = std::min(d1, d2); if(atrm < tol * ad) { goto L40; } ak += 18.; bk += 18.; /* L30: */ } L40: if(*id == 1) { goto L50; } *bir = c1 * s1r + c2 * (*zr * s2r - *zi * s2i); *bii = c1 * s1i + c2 * (*zr * s2i + *zi * s2r); if(*kode == 1) { return 0; } zsqrt_(zr, zi, &str, &sti); ztar = tth * (*zr * str - *zi * sti); ztai = tth * (*zr * sti + *zi * str); aa = ztar; aa = -abs(aa); eaa = exp(aa); *bir *= eaa; *bii *= eaa; return 0; L50: *bir = s2r * c2; *bii = s2i * c2; if(az <= tol) { goto L60; } cc = c1 / (fid + 1.); str = s1r * *zr - s1i * *zi; sti = s1r * *zi + s1i * *zr; *bir += cc * (str * *zr - sti * *zi); *bii += cc * (str * *zi + sti * *zr); L60: if(*kode == 1) { return 0; } zsqrt_(zr, zi, &str, &sti); ztar = tth * (*zr * str - *zi * sti); ztai = tth * (*zr * sti + *zi * str); aa = ztar; aa = -abs(aa); eaa = exp(aa); *bir *= eaa; *bii *= eaa; return 0; /* ----------------------------------------------------------------------- */ /* CASE FOR CABS(Z).GT.1.0 */ /* ----------------------------------------------------------------------- */ L70: fnu = (fid + 1.) / 3.; /* ----------------------------------------------------------------------- */ /* SET PARAMETERS RELATED TO MACHINE CONSTANTS. */ /* TOL IS THE APPROXIMATE UNIT ROUNDOFF LIMITED TO 1.0E-18. */ /* ELIM IS THE APPROXIMATE EXPONENTIAL OVER- AND UNDERFLOW LIMIT. */ /* EXP(-ELIM).LT.EXP(-ALIM)=EXP(-ELIM)/TOL AND */ /* EXP(ELIM).GT.EXP(ALIM)=EXP(ELIM)*TOL ARE INTERVALS NEAR */ /* UNDERFLOW AND OVERFLOW LIMITS WHERE SCALED ARITHMETIC IS DONE. */ /* RL IS THE LOWER BOUNDARY OF THE ASYMPTOTIC EXPANSION FOR LARGE Z. */ /* DIG = NUMBER OF BASE 10 DIGITS IN TOL = 10**(-DIG). */ /* FNUL IS THE LOWER BOUNDARY OF THE ASYMPTOTIC SERIES FOR LARGE FNU. */ /* ----------------------------------------------------------------------- */ k1 = i1mach_(&c__15); k2 = i1mach_(&c__16); r1m5 = d1mach_(&c__5); /* Computing MIN */ i__1 = abs(k1), i__2 = abs(k2); k = std::min(i__1, i__2); elim = ((double)((float)k) * r1m5 - 3.) * 2.303; k1 = i1mach_(&c__14) - 1; aa = r1m5 * (double)((float)k1); dig = std::min(aa, 18.); aa *= 2.303; /* Computing MAX */ d__1 = -aa; alim = elim + max(d__1, -41.45); rl = dig * 1.2 + 3.; fnul = (dig - 3.) * 6. + 10.; /* ----------------------------------------------------------------------- */ /* TEST FOR RANGE */ /* ----------------------------------------------------------------------- */ aa = .5 / tol; bb = (double)((float)i1mach_(&c__9)) * .5; aa = std::min(aa, bb); aa = pow_dd(&aa, &tth); if(az > aa) { goto L260; } aa = sqrt(aa); if(az > aa) { *ierr = 3; } zsqrt_(zr, zi, &csqr, &csqi); ztar = tth * (*zr * csqr - *zi * csqi); ztai = tth * (*zr * csqi + *zi * csqr); /* ----------------------------------------------------------------------- */ /* RE(ZTA).LE.0 WHEN RE(Z).LT.0, ESPECIALLY WHEN IM(Z) IS SMALL */ /* ----------------------------------------------------------------------- */ sfac = 1.; ak = ztai; if(*zr >= 0.) { goto L80; } bk = ztar; ck = -abs(bk); ztar = ck; ztai = ak; L80: if(*zi != 0. || *zr > 0.) { goto L90; } ztar = 0.; ztai = ak; L90: aa = ztar; if(*kode == 2) { goto L100; } /* ----------------------------------------------------------------------- */ /* OVERFLOW TEST */ /* ----------------------------------------------------------------------- */ bb = abs(aa); if(bb < alim) { goto L100; } bb += log(az) * .25; sfac = tol; if(bb > elim) { goto L190; } L100: fmr = 0.; if(aa >= 0. && *zr > 0.) { goto L110; } fmr = pi; if(*zi < 0.) { fmr = -pi; } ztar = -ztar; ztai = -ztai; L110: /* ----------------------------------------------------------------------- */ /* AA=FACTOR FOR ANALYTIC CONTINUATION OF I(FNU,ZTA) */ /* KODE=2 RETURNS EXP(-ABS(XZTA))*I(FNU,ZTA) FROM ZBESI */ /* ----------------------------------------------------------------------- */ zbinu_(&ztar, &ztai, &fnu, kode, &c__1, cyr, cyi, &nz, &rl, &fnul, &tol, &elim, &alim); if(nz < 0) { goto L200; } aa = fmr * fnu; z3r = sfac; str = cos(aa); sti = sin(aa); s1r = (str * cyr[0] - sti * cyi[0]) * z3r; s1i = (str * cyi[0] + sti * cyr[0]) * z3r; fnu = (2. - fid) / 3.; zbinu_(&ztar, &ztai, &fnu, kode, &c__2, cyr, cyi, &nz, &rl, &fnul, &tol, &elim, &alim); cyr[0] *= z3r; cyi[0] *= z3r; cyr[1] *= z3r; cyi[1] *= z3r; /* ----------------------------------------------------------------------- */ /* BACKWARD RECUR ONE STEP FOR ORDERS -1/3 OR -2/3 */ /* ----------------------------------------------------------------------- */ zdiv_(cyr, cyi, &ztar, &ztai, &str, &sti); s2r = (fnu + fnu) * str + cyr[1]; s2i = (fnu + fnu) * sti + cyi[1]; aa = fmr * (fnu - 1.); str = cos(aa); sti = sin(aa); s1r = coef * (s1r + s2r * str - s2i * sti); s1i = coef * (s1i + s2r * sti + s2i * str); if(*id == 1) { goto L120; } str = csqr * s1r - csqi * s1i; s1i = csqr * s1i + csqi * s1r; s1r = str; *bir = s1r / sfac; *bii = s1i / sfac; return 0; L120: str = *zr * s1r - *zi * s1i; s1i = *zr * s1i + *zi * s1r; s1r = str; *bir = s1r / sfac; *bii = s1i / sfac; return 0; L130: aa = c1 * (1. - fid) + fid * c2; *bir = aa; *bii = 0.; return 0; L190: *ierr = 2; nz = 0; return 0; L200: if(nz == -1) { goto L190; } nz = 0; *ierr = 5; return 0; L260: *ierr = 4; nz = 0; return 0; } /* zbiry_ */ int zbknu_(double* zr, double* zi, double* fnu, int32* kode, int32* n, double* yr, double* yi, int32* nz, double* tol, double* elim, double* alim) { /* Initialized data */ static int32 kmax = 30; static double czeror = 0.; static double czeroi = 0.; static double coner = 1.; static double conei = 0.; static double ctwor = 2.; static double r1 = 2.; static double dpi = 3.14159265358979324; static double rthpi = 1.25331413731550025; static double spi = 1.90985931710274403; static double hpi = 1.57079632679489662; static double fpi = 1.89769999331517738; static double tth = .666666666666666666; static double cc[8] = {.577215664901532861, -.0420026350340952355, -.0421977345555443367, .00721894324666309954, -2.15241674114950973e-4, -2.01348547807882387e-5, 1.13302723198169588e-6, 6.11609510448141582e-9}; /* System generated locals */ int32 i__1; double d__1; int32 i__, j, k; double s, a1, a2, g1, g2, t1, t2, aa, bb, fc, ak, bk; int32 ic; double fi, fk, as; int32 kk; double fr, pi, qi, tm, pr, qr; int32 nw; double p1i, p2i, s1i, s2i, p2m, p1r, p2r, s1r, s2r, cbi, cbr, cki, caz, csi, ckr, fhs, fks, rak, czi, dnu, csr, elm, zdi, bry[3], pti, czr, sti, zdr, cyr[2], rzi, ptr, cyi[2]; int32 inu; double str, rzr, dnu2, cchi, cchr, alas, cshi; int32 inub, idum; double cshr, fmui, rcaz, csrr[3], cssr[3], fmur; double smui; double smur; int32 iflag, kflag; double coefi; int32 koded; double ascle, coefr, helim, celmr, csclr, crscr; double etest; /* *********************************************************************72 */ /* c ZBKNU computes the K Bessel function in the right half Z plane. */ /* ***BEGIN PROLOGUE ZBKNU */ /* ***REFER TO ZBESI,ZBESK,ZAIRY,ZBESH */ /* ZBKNU COMPUTES THE K BESSEL FUNCTION IN THE RIGHT HALF Z PLANE. */ /* ***ROUTINES CALLED DGAMLN,I1MACH,D1MACH,ZKSCL,ZSHCH,ZUCHK,ZABS,ZDIV, */ /* ZEXP,ZLOG,ZMLT,ZSQRT */ /* ***END PROLOGUE ZBKNU */ /* COMPLEX Z,Y,A,B,RZ,SMU,FU,FMU,F,FLRZ,CZ,S1,S2,CSH,CCH */ /* COMPLEX CK,P,Q,COEF,P1,P2,CBK,PT,CZERO,CONE,CTWO,ST,EZ,CS,DK */ /* Parameter adjustments */ --yi; --yr; /* Function Body */ caz = zabs_(zr, zi); csclr = 1. / *tol; crscr = *tol; cssr[0] = csclr; cssr[1] = 1.; cssr[2] = crscr; csrr[0] = crscr; csrr[1] = 1.; csrr[2] = csclr; bry[0] = d1mach_(&c__1) * 1e3 / *tol; bry[1] = 1. / bry[0]; bry[2] = d1mach_(&c__2); *nz = 0; iflag = 0; koded = *kode; rcaz = 1. / caz; str = *zr * rcaz; sti = -(*zi) * rcaz; rzr = (str + str) * rcaz; rzi = (sti + sti) * rcaz; inu = (int32)(*fnu + .5); dnu = *fnu - (double)((float)inu); if(abs(dnu) == .5) { goto L110; } dnu2 = 0.; if(abs(dnu) > *tol) { dnu2 = dnu * dnu; } if(caz > r1) { goto L110; } /* ----------------------------------------------------------------------- */ /* SERIES FOR CABS(Z).LE.R1 */ /* ----------------------------------------------------------------------- */ fc = 1.; zlog_(&rzr, &rzi, &smur, &smui, &idum); fmur = smur * dnu; fmui = smui * dnu; zshch_(&fmur, &fmui, &cshr, &cshi, &cchr, &cchi); if(dnu == 0.) { goto L10; } fc = dnu * dpi; fc /= sin(fc); smur = cshr / dnu; smui = cshi / dnu; L10: a2 = dnu + 1.; /* ----------------------------------------------------------------------- */ /* GAM(1-Z)*GAM(1+Z)=PI*Z/SIN(PI*Z), T1=1/GAM(1-DNU), T2=1/GAM(1+DNU) */ /* ----------------------------------------------------------------------- */ t2 = exp(-dgamln_(&a2, &idum)); t1 = 1. / (t2 * fc); if(abs(dnu) > .1) { goto L40; } /* ----------------------------------------------------------------------- */ /* SERIES FOR F0 TO RESOLVE INDETERMINACY FOR SMALL ABS(DNU) */ /* ----------------------------------------------------------------------- */ ak = 1.; s = cc[0]; for(k = 2; k <= 8; ++k) { ak *= dnu2; tm = cc[k - 1] * ak; s += tm; if(abs(tm) < *tol) { goto L30; } /* L20: */ } L30: g1 = -s; goto L50; L40: g1 = (t1 - t2) / (dnu + dnu); L50: g2 = (t1 + t2) * .5; fr = fc * (cchr * g1 + smur * g2); fi = fc * (cchi * g1 + smui * g2); zexp_(&fmur, &fmui, &str, &sti); pr = str * .5 / t2; pi = sti * .5 / t2; zdiv_(&c_b876, &c_b877, &str, &sti, &ptr, &pti); qr = ptr / t1; qi = pti / t1; s1r = fr; s1i = fi; s2r = pr; s2i = pi; ak = 1.; a1 = 1.; ckr = coner; cki = conei; bk = 1. - dnu2; if(inu > 0 || *n > 1) { goto L80; } /* ----------------------------------------------------------------------- */ /* GENERATE K(FNU,Z), 0.0D0 .LE. FNU .LT. 0.5D0 AND N=1 */ /* ----------------------------------------------------------------------- */ if(caz < *tol) { goto L70; } zmlt_(zr, zi, zr, zi, &czr, &czi); czr *= .25; czi *= .25; t1 = caz * .25 * caz; L60: fr = (fr * ak + pr + qr) / bk; fi = (fi * ak + pi + qi) / bk; str = 1. / (ak - dnu); pr *= str; pi *= str; str = 1. / (ak + dnu); qr *= str; qi *= str; str = ckr * czr - cki * czi; rak = 1. / ak; cki = (ckr * czi + cki * czr) * rak; ckr = str * rak; s1r = ckr * fr - cki * fi + s1r; s1i = ckr * fi + cki * fr + s1i; a1 = a1 * t1 * rak; bk = bk + ak + ak + 1.; ak += 1.; if(a1 > *tol) { goto L60; } L70: yr[1] = s1r; yi[1] = s1i; if(koded == 1) { return 0; } zexp_(zr, zi, &str, &sti); zmlt_(&s1r, &s1i, &str, &sti, &yr[1], &yi[1]); return 0; /* ----------------------------------------------------------------------- */ /* GENERATE K(DNU,Z) AND K(DNU+1,Z) FOR FORWARD RECURRENCE */ /* ----------------------------------------------------------------------- */ L80: if(caz < *tol) { goto L100; } zmlt_(zr, zi, zr, zi, &czr, &czi); czr *= .25; czi *= .25; t1 = caz * .25 * caz; L90: fr = (fr * ak + pr + qr) / bk; fi = (fi * ak + pi + qi) / bk; str = 1. / (ak - dnu); pr *= str; pi *= str; str = 1. / (ak + dnu); qr *= str; qi *= str; str = ckr * czr - cki * czi; rak = 1. / ak; cki = (ckr * czi + cki * czr) * rak; ckr = str * rak; s1r = ckr * fr - cki * fi + s1r; s1i = ckr * fi + cki * fr + s1i; str = pr - fr * ak; sti = pi - fi * ak; s2r = ckr * str - cki * sti + s2r; s2i = ckr * sti + cki * str + s2i; a1 = a1 * t1 * rak; bk = bk + ak + ak + 1.; ak += 1.; if(a1 > *tol) { goto L90; } L100: kflag = 2; a1 = *fnu + 1.; ak = a1 * abs(smur); if(ak > *alim) { kflag = 3; } str = cssr[kflag - 1]; p2r = s2r * str; p2i = s2i * str; zmlt_(&p2r, &p2i, &rzr, &rzi, &s2r, &s2i); s1r *= str; s1i *= str; if(koded == 1) { goto L210; } zexp_(zr, zi, &fr, &fi); zmlt_(&s1r, &s1i, &fr, &fi, &s1r, &s1i); zmlt_(&s2r, &s2i, &fr, &fi, &s2r, &s2i); goto L210; /* ----------------------------------------------------------------------- */ /* IFLAG=0 MEANS NO UNDERFLOW OCCURRED */ /* IFLAG=1 MEANS AN UNDERFLOW OCCURRED- COMPUTATION PROCEEDS WITH */ /* KODED=2 AND A TEST FOR ON SCALE VALUES IS MADE DURING FORWARD */ /* RECURSION */ /* ----------------------------------------------------------------------- */ L110: zsqrt_(zr, zi, &str, &sti); zdiv_(&rthpi, &czeroi, &str, &sti, &coefr, &coefi); kflag = 2; if(koded == 2) { goto L120; } if(*zr > *alim) { goto L290; } /* BLANK LINE */ str = exp(-(*zr)) * cssr[kflag - 1]; sti = -str * sin(*zi); str *= cos(*zi); zmlt_(&coefr, &coefi, &str, &sti, &coefr, &coefi); L120: if(abs(dnu) == .5) { goto L300; } /* ----------------------------------------------------------------------- */ /* MILLER ALGORITHM FOR CABS(Z).GT.R1 */ /* ----------------------------------------------------------------------- */ ak = cos(dpi * dnu); ak = abs(ak); if(ak == czeror) { goto L300; } fhs = (d__1 = .25 - dnu2, abs(d__1)); if(fhs == czeror) { goto L300; } /* ----------------------------------------------------------------------- */ /* COMPUTE R2=F(E). IF CABS(Z).GE.R2, USE FORWARD RECURRENCE TO */ /* DETERMINE THE BACKWARD INDEX K. R2=F(E) IS A STRAIGHT LINE ON */ /* 12.LE.E.LE.60. E IS COMPUTED FROM 2**(-E)=B**(1-I1MACH(14))= */ /* TOL WHERE B IS THE BASE OF THE ARITHMETIC. */ /* ----------------------------------------------------------------------- */ t1 = (double)((float)(i1mach_(&c__14) - 1)); t1 = t1 * d1mach_(&c__5) * 3.321928094; t1 = max(t1, 12.); t1 = std::min(t1, 60.); t2 = tth * t1 - 6.; if(*zr != 0.) { goto L130; } t1 = hpi; goto L140; L130: t1 = atan(*zi / *zr); t1 = abs(t1); L140: if(t2 > caz) { goto L170; } /* ----------------------------------------------------------------------- */ /* FORWARD RECURRENCE LOOP WHEN CABS(Z).GE.R2 */ /* ----------------------------------------------------------------------- */ etest = ak / (dpi * caz * *tol); fk = coner; if(etest < coner) { goto L180; } fks = ctwor; ckr = caz + caz + ctwor; p1r = czeror; p2r = coner; i__1 = kmax; for(i__ = 1; i__ <= i__1; ++i__) { ak = fhs / fks; cbr = ckr / (fk + coner); ptr = p2r; p2r = cbr * p2r - p1r * ak; p1r = ptr; ckr += ctwor; fks = fks + fk + fk + ctwor; fhs = fhs + fk + fk; fk += coner; str = abs(p2r) * fk; if(etest < str) { goto L160; } /* L150: */ } goto L310; L160: fk += spi * t1 * sqrt(t2 / caz); fhs = (d__1 = .25 - dnu2, abs(d__1)); goto L180; L170: /* ----------------------------------------------------------------------- */ /* COMPUTE BACKWARD INDEX K FOR CABS(Z).LT.R2 */ /* ----------------------------------------------------------------------- */ a2 = sqrt(caz); ak = fpi * ak / (*tol * sqrt(a2)); aa = t1 * 3. / (caz + 1.); bb = t1 * 14.7 / (caz + 28.); ak = (log(ak) + caz * cos(aa) / (caz * .008 + 1.)) / cos(bb); fk = ak * .12125 * ak / caz + 1.5; L180: /* ----------------------------------------------------------------------- */ /* BACKWARD RECURRENCE LOOP FOR MILLER ALGORITHM */ /* ----------------------------------------------------------------------- */ k = (int32)((float)fk); fk = (double)((float)k); fks = fk * fk; p1r = czeror; p1i = czeroi; p2r = *tol; p2i = czeroi; csr = p2r; csi = p2i; i__1 = k; for(i__ = 1; i__ <= i__1; ++i__) { a1 = fks - fk; ak = (fks + fk) / (a1 + fhs); rak = 2. / (fk + coner); cbr = (fk + *zr) * rak; cbi = *zi * rak; ptr = p2r; pti = p2i; p2r = (ptr * cbr - pti * cbi - p1r) * ak; p2i = (pti * cbr + ptr * cbi - p1i) * ak; p1r = ptr; p1i = pti; csr += p2r; csi += p2i; fks = a1 - fk + coner; fk -= coner; /* L190: */ } /* ----------------------------------------------------------------------- */ /* COMPUTE (P2/CS)=(P2/CABS(CS))*(CONJG(CS)/CABS(CS)) FOR BETTER */ /* SCALING */ /* ----------------------------------------------------------------------- */ tm = zabs_(&csr, &csi); ptr = 1. / tm; s1r = p2r * ptr; s1i = p2i * ptr; csr *= ptr; csi = -csi * ptr; zmlt_(&coefr, &coefi, &s1r, &s1i, &str, &sti); zmlt_(&str, &sti, &csr, &csi, &s1r, &s1i); if(inu > 0 || *n > 1) { goto L200; } zdr = *zr; zdi = *zi; if(iflag == 1) { goto L270; } goto L240; L200: /* ----------------------------------------------------------------------- */ /* COMPUTE P1/P2=(P1/CABS(P2)*CONJG(P2)/CABS(P2) FOR SCALING */ /* ----------------------------------------------------------------------- */ tm = zabs_(&p2r, &p2i); ptr = 1. / tm; p1r *= ptr; p1i *= ptr; p2r *= ptr; p2i = -p2i * ptr; zmlt_(&p1r, &p1i, &p2r, &p2i, &ptr, &pti); str = dnu + .5 - ptr; sti = -pti; zdiv_(&str, &sti, zr, zi, &str, &sti); str += 1.; zmlt_(&str, &sti, &s1r, &s1i, &s2r, &s2i); /* ----------------------------------------------------------------------- */ /* FORWARD RECURSION ON THE THREE TERM RECURSION WITH RELATION WITH */ /* SCALING NEAR EXPONENT EXTREMES ON KFLAG=1 OR KFLAG=3 */ /* ----------------------------------------------------------------------- */ L210: str = dnu + 1.; ckr = str * rzr; cki = str * rzi; if(*n == 1) { --inu; } if(inu > 0) { goto L220; } if(*n > 1) { goto L215; } s1r = s2r; s1i = s2i; L215: zdr = *zr; zdi = *zi; if(iflag == 1) { goto L270; } goto L240; L220: inub = 1; if(iflag == 1) { goto L261; } L225: p1r = csrr[kflag - 1]; ascle = bry[kflag - 1]; i__1 = inu; for(i__ = inub; i__ <= i__1; ++i__) { str = s2r; sti = s2i; s2r = ckr * str - cki * sti + s1r; s2i = ckr * sti + cki * str + s1i; s1r = str; s1i = sti; ckr += rzr; cki += rzi; if(kflag >= 3) { goto L230; } p2r = s2r * p1r; p2i = s2i * p1r; str = abs(p2r); sti = abs(p2i); p2m = max(str, sti); if(p2m <= ascle) { goto L230; } ++kflag; ascle = bry[kflag - 1]; s1r *= p1r; s1i *= p1r; s2r = p2r; s2i = p2i; str = cssr[kflag - 1]; s1r *= str; s1i *= str; s2r *= str; s2i *= str; p1r = csrr[kflag - 1]; L230:; } if(*n != 1) { goto L240; } s1r = s2r; s1i = s2i; L240: str = csrr[kflag - 1]; yr[1] = s1r * str; yi[1] = s1i * str; if(*n == 1) { return 0; } yr[2] = s2r * str; yi[2] = s2i * str; if(*n == 2) { return 0; } kk = 2; L250: ++kk; if(kk > *n) { return 0; } p1r = csrr[kflag - 1]; ascle = bry[kflag - 1]; i__1 = *n; for(i__ = kk; i__ <= i__1; ++i__) { p2r = s2r; p2i = s2i; s2r = ckr * p2r - cki * p2i + s1r; s2i = cki * p2r + ckr * p2i + s1i; s1r = p2r; s1i = p2i; ckr += rzr; cki += rzi; p2r = s2r * p1r; p2i = s2i * p1r; yr[i__] = p2r; yi[i__] = p2i; if(kflag >= 3) { goto L260; } str = abs(p2r); sti = abs(p2i); p2m = max(str, sti); if(p2m <= ascle) { goto L260; } ++kflag; ascle = bry[kflag - 1]; s1r *= p1r; s1i *= p1r; s2r = p2r; s2i = p2i; str = cssr[kflag - 1]; s1r *= str; s1i *= str; s2r *= str; s2i *= str; p1r = csrr[kflag - 1]; L260:; } return 0; /* ----------------------------------------------------------------------- */ /* IFLAG=1 CASES, FORWARD RECURRENCE ON SCALED VALUES ON UNDERFLOW */ /* ----------------------------------------------------------------------- */ L261: helim = *elim * .5; elm = exp(-(*elim)); celmr = elm; ascle = bry[0]; zdr = *zr; zdi = *zi; ic = -1; j = 2; i__1 = inu; for(i__ = 1; i__ <= i__1; ++i__) { str = s2r; sti = s2i; s2r = str * ckr - sti * cki + s1r; s2i = sti * ckr + str * cki + s1i; s1r = str; s1i = sti; ckr += rzr; cki += rzi; as = zabs_(&s2r, &s2i); alas = log(as); p2r = -zdr + alas; if(p2r < -(*elim)) { goto L263; } zlog_(&s2r, &s2i, &str, &sti, &idum); p2r = -zdr + str; p2i = -zdi + sti; p2m = exp(p2r) / *tol; p1r = p2m * cos(p2i); p1i = p2m * sin(p2i); zuchk_(&p1r, &p1i, &nw, &ascle, tol); if(nw != 0) { goto L263; } j = 3 - j; cyr[j - 1] = p1r; cyi[j - 1] = p1i; if(ic == i__ - 1) { goto L264; } ic = i__; goto L262; L263: if(alas < helim) { goto L262; } zdr -= *elim; s1r *= celmr; s1i *= celmr; s2r *= celmr; s2i *= celmr; L262:; } if(*n != 1) { goto L270; } s1r = s2r; s1i = s2i; goto L270; L264: kflag = 1; inub = i__ + 1; s2r = cyr[j - 1]; s2i = cyi[j - 1]; j = 3 - j; s1r = cyr[j - 1]; s1i = cyi[j - 1]; if(inub <= inu) { goto L225; } if(*n != 1) { goto L240; } s1r = s2r; s1i = s2i; goto L240; L270: yr[1] = s1r; yi[1] = s1i; if(*n == 1) { goto L280; } yr[2] = s2r; yi[2] = s2i; L280: ascle = bry[0]; zkscl_(&zdr, &zdi, fnu, n, &yr[1], &yi[1], nz, &rzr, &rzi, &ascle, tol, elim); inu = *n - *nz; if(inu <= 0) { return 0; } kk = *nz + 1; s1r = yr[kk]; s1i = yi[kk]; yr[kk] = s1r * csrr[0]; yi[kk] = s1i * csrr[0]; if(inu == 1) { return 0; } kk = *nz + 2; s2r = yr[kk]; s2i = yi[kk]; yr[kk] = s2r * csrr[0]; yi[kk] = s2i * csrr[0]; if(inu == 2) { return 0; } t2 = *fnu + (double)((float)(kk - 1)); ckr = t2 * rzr; cki = t2 * rzi; kflag = 1; goto L250; L290: /* ----------------------------------------------------------------------- */ /* SCALE BY DEXP(Z), IFLAG = 1 CASES */ /* ----------------------------------------------------------------------- */ koded = 2; iflag = 1; kflag = 2; goto L120; /* ----------------------------------------------------------------------- */ /* FNU=HALF ODD INTEGER CASE, DNU=-0.5 */ /* ----------------------------------------------------------------------- */ L300: s1r = coefr; s1i = coefi; s2r = coefr; s2i = coefi; goto L210; L310: *nz = -2; return 0; } /* zbknu_ */ int zbuni_(double* zr, double* zi, double* fnu, int32* kode, int32* n, double* yr, double* yi, int32* nz, int32* nui, int32* nlast, double* fnul, double* tol, double* elim, double* alim) { /* System generated locals */ int32 i__1; int32 i__, k; double ax, ay; int32 nl, nw; double c1i, c1m, c1r, s1i, s2i, s1r, s2r, cyi[2], gnu, raz, cyr[2], sti, bry[3], rzi, str, rzr, dfnu; double fnui; int32 iflag; double ascle, csclr, cscrr; int32 iform; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE ZBUNI */ /* ***REFER TO ZBESI,ZBESK */ /* ZBUNI COMPUTES THE I BESSEL FUNCTION FOR LARGE CABS(Z).GT. */ /* FNUL AND FNU+N-1.LT.FNUL. THE ORDER IS INCREASED FROM */ /* FNU+N-1 GREATER THAN FNUL BY ADDING NUI AND COMPUTING */ /* ACCORDING TO THE UNIFORM ASYMPTOTIC EXPANSION FOR I(FNU,Z) */ /* ON IFORM=1 AND THE EXPANSION FOR J(FNU,Z) ON IFORM=2 */ /* ***ROUTINES CALLED ZUNI1,ZUNI2,ZABS,D1MACH */ /* ***END PROLOGUE ZBUNI */ /* COMPLEX CSCL,CSCR,CY,RZ,ST,S1,S2,Y,Z */ /* Parameter adjustments */ --yi; --yr; /* Function Body */ *nz = 0; ax = abs(*zr) * 1.7321; ay = abs(*zi); iform = 1; if(ay > ax) { iform = 2; } if(*nui == 0) { goto L60; } fnui = (double)((float)(*nui)); dfnu = *fnu + (double)((float)(*n - 1)); gnu = dfnu + fnui; if(iform == 2) { goto L10; } /* ----------------------------------------------------------------------- */ /* ASYMPTOTIC EXPANSION FOR I(FNU,Z) FOR LARGE FNU APPLIED IN */ /* -PI/3.LE.ARG(Z).LE.PI/3 */ /* ----------------------------------------------------------------------- */ zuni1_(zr, zi, &gnu, kode, &c__2, cyr, cyi, &nw, nlast, fnul, tol, elim, alim); goto L20; L10: /* ----------------------------------------------------------------------- */ /* ASYMPTOTIC EXPANSION FOR J(FNU,Z*EXP(M*HPI)) FOR LARGE FNU */ /* APPLIED IN PI/3.LT.ABS(ARG(Z)).LE.PI/2 WHERE M=+I OR -I */ /* AND HPI=PI/2 */ /* ----------------------------------------------------------------------- */ zuni2_(zr, zi, &gnu, kode, &c__2, cyr, cyi, &nw, nlast, fnul, tol, elim, alim); L20: if(nw < 0) { goto L50; } if(nw != 0) { goto L90; } str = zabs_(cyr, cyi); /* ---------------------------------------------------------------------- */ /* SCALE BACKWARD RECURRENCE, BRY(3) IS DEFINED BUT NEVER USED */ /* ---------------------------------------------------------------------- */ bry[0] = d1mach_(&c__1) * 1e3 / *tol; bry[1] = 1. / bry[0]; bry[2] = bry[1]; iflag = 2; ascle = bry[1]; csclr = 1.; if(str > bry[0]) { goto L21; } iflag = 1; ascle = bry[0]; csclr = 1. / *tol; goto L25; L21: if(str < bry[1]) { goto L25; } iflag = 3; ascle = bry[2]; csclr = *tol; L25: cscrr = 1. / csclr; s1r = cyr[1] * csclr; s1i = cyi[1] * csclr; s2r = cyr[0] * csclr; s2i = cyi[0] * csclr; raz = 1. / zabs_(zr, zi); str = *zr * raz; sti = -(*zi) * raz; rzr = (str + str) * raz; rzi = (sti + sti) * raz; i__1 = *nui; for(i__ = 1; i__ <= i__1; ++i__) { str = s2r; sti = s2i; s2r = (dfnu + fnui) * (rzr * str - rzi * sti) + s1r; s2i = (dfnu + fnui) * (rzr * sti + rzi * str) + s1i; s1r = str; s1i = sti; fnui += -1.; if(iflag >= 3) { goto L30; } str = s2r * cscrr; sti = s2i * cscrr; c1r = abs(str); c1i = abs(sti); c1m = max(c1r, c1i); if(c1m <= ascle) { goto L30; } ++iflag; ascle = bry[iflag - 1]; s1r *= cscrr; s1i *= cscrr; s2r = str; s2i = sti; csclr *= *tol; cscrr = 1. / csclr; s1r *= csclr; s1i *= csclr; s2r *= csclr; s2i *= csclr; L30:; } yr[*n] = s2r * cscrr; yi[*n] = s2i * cscrr; if(*n == 1) { return 0; } nl = *n - 1; fnui = (double)((float)nl); k = nl; i__1 = nl; for(i__ = 1; i__ <= i__1; ++i__) { str = s2r; sti = s2i; s2r = (*fnu + fnui) * (rzr * str - rzi * sti) + s1r; s2i = (*fnu + fnui) * (rzr * sti + rzi * str) + s1i; s1r = str; s1i = sti; str = s2r * cscrr; sti = s2i * cscrr; yr[k] = str; yi[k] = sti; fnui += -1.; --k; if(iflag >= 3) { goto L40; } c1r = abs(str); c1i = abs(sti); c1m = max(c1r, c1i); if(c1m <= ascle) { goto L40; } ++iflag; ascle = bry[iflag - 1]; s1r *= cscrr; s1i *= cscrr; s2r = str; s2i = sti; csclr *= *tol; cscrr = 1. / csclr; s1r *= csclr; s1i *= csclr; s2r *= csclr; s2i *= csclr; L40:; } return 0; L50: *nz = -1; if(nw == -2) { *nz = -2; } return 0; L60: if(iform == 2) { goto L70; } /* ----------------------------------------------------------------------- */ /* ASYMPTOTIC EXPANSION FOR I(FNU,Z) FOR LARGE FNU APPLIED IN */ /* -PI/3.LE.ARG(Z).LE.PI/3 */ /* ----------------------------------------------------------------------- */ zuni1_(zr, zi, fnu, kode, n, &yr[1], &yi[1], &nw, nlast, fnul, tol, elim, alim); goto L80; L70: /* ----------------------------------------------------------------------- */ /* ASYMPTOTIC EXPANSION FOR J(FNU,Z*EXP(M*HPI)) FOR LARGE FNU */ /* APPLIED IN PI/3.LT.ABS(ARG(Z)).LE.PI/2 WHERE M=+I OR -I */ /* AND HPI=PI/2 */ /* ----------------------------------------------------------------------- */ zuni2_(zr, zi, fnu, kode, n, &yr[1], &yi[1], &nw, nlast, fnul, tol, elim, alim); L80: if(nw < 0) { goto L50; } *nz = nw; return 0; L90: *nlast = *n; return 0; } /* zbuni_ */ int zbunk_(double* zr, double* zi, double* fnu, int32* kode, int32* mr, int32* n, double* yr, double* yi, int32* nz, double* tol, double* elim, double* alim) { double ax, ay; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE ZBUNK */ /* ***REFER TO ZBESK,ZBESH */ /* ZBUNK COMPUTES THE K BESSEL FUNCTION FOR FNU.GT.FNUL. */ /* ACCORDING TO THE UNIFORM ASYMPTOTIC EXPANSION FOR K(FNU,Z) */ /* IN ZUNK1 AND THE EXPANSION FOR H(2,FNU,Z) IN ZUNK2 */ /* ***ROUTINES CALLED ZUNK1,ZUNK2 */ /* ***END PROLOGUE ZBUNK */ /* COMPLEX Y,Z */ /* Parameter adjustments */ --yi; --yr; /* Function Body */ *nz = 0; ax = abs(*zr) * 1.7321; ay = abs(*zi); if(ay > ax) { goto L10; } /* ----------------------------------------------------------------------- */ /* ASYMPTOTIC EXPANSION FOR K(FNU,Z) FOR LARGE FNU APPLIED IN */ /* -PI/3.LE.ARG(Z).LE.PI/3 */ /* ----------------------------------------------------------------------- */ zunk1_(zr, zi, fnu, kode, mr, n, &yr[1], &yi[1], nz, tol, elim, alim); goto L20; L10: /* ----------------------------------------------------------------------- */ /* ASYMPTOTIC EXPANSION FOR H(2,FNU,Z*EXP(M*HPI)) FOR LARGE FNU */ /* APPLIED IN PI/3.LT.ABS(ARG(Z)).LE.PI/2 WHERE M=+I OR -I */ /* AND HPI=PI/2 */ /* ----------------------------------------------------------------------- */ zunk2_(zr, zi, fnu, kode, mr, n, &yr[1], &yi[1], nz, tol, elim, alim); L20: return 0; } /* zbunk_ */ int zdiv_(double* ar, double* ai, double* br, double* bi, double* cr, double* ci) { double ca, cb, cc, cd, bm; /* *********************************************************************72 */ /* c ZDIV carries out double precision System::Complex<float> division. */ /* ***BEGIN PROLOGUE ZDIV */ /* ***REFER TO ZBESH,ZBESI,ZBESJ,ZBESK,ZBESY,ZAIRY,ZBIRY */ /* DOUBLE PRECISION COMPLEX DIVIDE C=A/B. */ /* ***ROUTINES CALLED ZABS */ /* ***END PROLOGUE ZDIV */ bm = 1. / zabs_(br, bi); cc = *br * bm; cd = *bi * bm; ca = (*ar * cc + *ai * cd) * bm; cb = (*ai * cc - *ar * cd) * bm; *cr = ca; *ci = cb; return 0; } /* zdiv_ */ int zexp_(double* ar, double* ai, double* br, double* bi) { double ca, cb, zm; /* *********************************************************************72 */ /* c ZEXP carries out double precision System::Complex<float> exponentiation. */ /* ***BEGIN PROLOGUE ZEXP */ /* ***REFER TO ZBESH,ZBESI,ZBESJ,ZBESK,ZBESY,ZAIRY,ZBIRY */ /* DOUBLE PRECISION COMPLEX EXPONENTIAL FUNCTION B=EXP(A) */ /* ***ROUTINES CALLED (NONE) */ /* ***END PROLOGUE ZEXP */ zm = exp(*ar); ca = zm * cos(*ai); cb = zm * sin(*ai); *br = ca; *bi = cb; return 0; } /* zexp_ */ int zkscl_(double* zrr, double* zri, double* fnu, int32* n, double* yr, double* yi, int32* nz, double* rzr, double* rzi, double* ascle, double* tol, double* elim) { /* Initialized data */ static double zeror = 0.; static double zeroi = 0.; /* System generated locals */ int32 i__1; int32 i__, ic; double as, fn; int32 kk, nn, nw; double s1i, s2i, s1r, s2r, acs, cki, elm, csi, ckr, cyi[2], zdi, csr, cyr[2], zdr, str, alas; int32 idum; double helim, celmr; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE ZKSCL */ /* ***REFER TO ZBESK */ /* SET K FUNCTIONS TO ZERO ON UNDERFLOW, CONTINUE RECURRENCE */ /* ON SCALED FUNCTIONS UNTIL TWO MEMBERS COME ON SCALE, THEN */ /* RETURN WITH MIN(NZ+2,N) VALUES SCALED BY 1/TOL. */ /* ***ROUTINES CALLED ZUCHK,ZABS,ZLOG */ /* ***END PROLOGUE ZKSCL */ /* COMPLEX CK,CS,CY,CZERO,RZ,S1,S2,Y,ZR,ZD,CELM */ /* Parameter adjustments */ --yi; --yr; /* Function Body */ *nz = 0; ic = 0; nn = std::min(2L, *n); i__1 = nn; for(i__ = 1; i__ <= i__1; ++i__) { s1r = yr[i__]; s1i = yi[i__]; cyr[i__ - 1] = s1r; cyi[i__ - 1] = s1i; as = zabs_(&s1r, &s1i); acs = -(*zrr) + log(as); ++(*nz); yr[i__] = zeror; yi[i__] = zeroi; if(acs < -(*elim)) { goto L10; } zlog_(&s1r, &s1i, &csr, &csi, &idum); csr -= *zrr; csi -= *zri; str = exp(csr) / *tol; csr = str * cos(csi); csi = str * sin(csi); zuchk_(&csr, &csi, &nw, ascle, tol); if(nw != 0) { goto L10; } yr[i__] = csr; yi[i__] = csi; ic = i__; --(*nz); L10:; } if(*n == 1) { return 0; } if(ic > 1) { goto L20; } yr[1] = zeror; yi[1] = zeroi; *nz = 2; L20: if(*n == 2) { return 0; } if(*nz == 0) { return 0; } fn = *fnu + 1.; ckr = fn * *rzr; cki = fn * *rzi; s1r = cyr[0]; s1i = cyi[0]; s2r = cyr[1]; s2i = cyi[1]; helim = *elim * .5; elm = exp(-(*elim)); celmr = elm; zdr = *zrr; zdi = *zri; /* FIND TWO CONSECUTIVE Y VALUES ON SCALE. SCALE RECURRENCE IF */ /* S2 GETS LARGER THAN EXP(ELIM/2) */ i__1 = *n; for(i__ = 3; i__ <= i__1; ++i__) { kk = i__; csr = s2r; csi = s2i; s2r = ckr * csr - cki * csi + s1r; s2i = cki * csr + ckr * csi + s1i; s1r = csr; s1i = csi; ckr += *rzr; cki += *rzi; as = zabs_(&s2r, &s2i); alas = log(as); acs = -zdr + alas; ++(*nz); yr[i__] = zeror; yi[i__] = zeroi; if(acs < -(*elim)) { goto L25; } zlog_(&s2r, &s2i, &csr, &csi, &idum); csr -= zdr; csi -= zdi; str = exp(csr) / *tol; csr = str * cos(csi); csi = str * sin(csi); zuchk_(&csr, &csi, &nw, ascle, tol); if(nw != 0) { goto L25; } yr[i__] = csr; yi[i__] = csi; --(*nz); if(ic == kk - 1) { goto L40; } ic = kk; goto L30; L25: if(alas < helim) { goto L30; } zdr -= *elim; s1r *= celmr; s1i *= celmr; s2r *= celmr; s2i *= celmr; L30:; } *nz = *n; if(ic == *n) { *nz = *n - 1; } goto L45; L40: *nz = kk - 2; L45: i__1 = *nz; for(i__ = 1; i__ <= i__1; ++i__) { yr[i__] = zeror; yi[i__] = zeroi; /* L50: */ } return 0; } /* zkscl_ */ int zlog_(double* ar, double* ai, double* br, double* bi, int32* ierr) { /* Initialized data */ static double dpi = 3.141592653589793238462643383; static double dhpi = 1.570796326794896619231321696; double zm; double dtheta; /* *********************************************************************72 */ /* c ZLOG carries out double precision System::Complex<float> logarithms */ /* ***BEGIN PROLOGUE ZLOG */ /* ***REFER TO ZBESH,ZBESI,ZBESJ,ZBESK,ZBESY,ZAIRY,ZBIRY */ /* DOUBLE PRECISION COMPLEX LOGARITHM B=CLOG(A) */ /* IERR=0,NORMAL RETURN IERR=1, Z=CMPLX(0.0,0.0) */ /* ***ROUTINES CALLED ZABS */ /* ***END PROLOGUE ZLOG */ *ierr = 0; if(*ar == 0.) { goto L10; } if(*ai == 0.) { goto L20; } dtheta = atan(*ai / *ar); if(dtheta <= 0.) { goto L40; } if(*ar < 0.) { dtheta -= dpi; } goto L50; L10: if(*ai == 0.) { goto L60; } *bi = dhpi; *br = log((abs(*ai))); if(*ai < 0.) { *bi = -(*bi); } return 0; L20: if(*ar > 0.) { goto L30; } *br = log((abs(*ar))); *bi = dpi; return 0; L30: *br = log(*ar); *bi = 0.; return 0; L40: if(*ar < 0.) { dtheta += dpi; } L50: zm = zabs_(ar, ai); *br = log(zm); *bi = dtheta; return 0; L60: *ierr = 1; return 0; } /* zlog_ */ int zmlri_(double* zr, double* zi, double* fnu, int32* kode, int32* n, double* yr, double* yi, int32* nz, double* tol) { /* Initialized data */ static double zeror = 0.; static double zeroi = 0.; static double coner = 1.; static double conei = 0.; /* System generated locals */ int32 i__1, i__2; double d__1, d__2, d__3; int32 i__, k, m; double ak, bk, ap, at; int32 kk, km; double az, p1i, p2i, p1r, p2r, ack, cki, fnf, fkk, ckr; int32 iaz; double rho; int32 inu; double pti, raz, sti, rzi, ptr, str, tst, rzr, rho2, flam, fkap, scle, tfnf; int32 idum; int32 ifnu; double sumi, sumr; int32 itime; double cnormi, cnormr; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE ZMLRI */ /* ***REFER TO ZBESI,ZBESK */ /* ZMLRI COMPUTES THE I BESSEL FUNCTION FOR RE(Z).GE.0.0 BY THE */ /* MILLER ALGORITHM NORMALIZED BY A NEUMANN SERIES. */ /* ***ROUTINES CALLED DGAMLN,D1MACH,ZABS,ZEXP,ZLOG,ZMLT */ /* ***END PROLOGUE ZMLRI */ /* COMPLEX CK,CNORM,CONE,CTWO,CZERO,PT,P1,P2,RZ,SUM,Y,Z */ /* Parameter adjustments */ --yi; --yr; /* Function Body */ scle = d1mach_(&c__1) / *tol; *nz = 0; az = zabs_(zr, zi); iaz = (int32)((float)az); ifnu = (int32)((float)(*fnu)); inu = ifnu + *n - 1; at = (double)((float)iaz) + 1.; raz = 1. / az; str = *zr * raz; sti = -(*zi) * raz; ckr = str * at * raz; cki = sti * at * raz; rzr = (str + str) * raz; rzi = (sti + sti) * raz; p1r = zeror; p1i = zeroi; p2r = coner; p2i = conei; ack = (at + 1.) * raz; rho = ack + sqrt(ack * ack - 1.); rho2 = rho * rho; tst = (rho2 + rho2) / ((rho2 - 1.) * (rho - 1.)); tst /= *tol; /* ----------------------------------------------------------------------- */ /* COMPUTE RELATIVE TRUNCATION ERROR INDEX FOR SERIES */ /* ----------------------------------------------------------------------- */ ak = at; for(i__ = 1; i__ <= 80; ++i__) { ptr = p2r; pti = p2i; p2r = p1r - (ckr * ptr - cki * pti); p2i = p1i - (cki * ptr + ckr * pti); p1r = ptr; p1i = pti; ckr += rzr; cki += rzi; ap = zabs_(&p2r, &p2i); if(ap > tst * ak * ak) { goto L20; } ak += 1.; /* L10: */ } goto L110; L20: ++i__; k = 0; if(inu < iaz) { goto L40; } /* ----------------------------------------------------------------------- */ /* COMPUTE RELATIVE TRUNCATION ERROR FOR RATIOS */ /* ----------------------------------------------------------------------- */ p1r = zeror; p1i = zeroi; p2r = coner; p2i = conei; at = (double)((float)inu) + 1.; str = *zr * raz; sti = -(*zi) * raz; ckr = str * at * raz; cki = sti * at * raz; ack = at * raz; tst = sqrt(ack / *tol); itime = 1; for(k = 1; k <= 80; ++k) { ptr = p2r; pti = p2i; p2r = p1r - (ckr * ptr - cki * pti); p2i = p1i - (ckr * pti + cki * ptr); p1r = ptr; p1i = pti; ckr += rzr; cki += rzi; ap = zabs_(&p2r, &p2i); if(ap < tst) { goto L30; } if(itime == 2) { goto L40; } ack = zabs_(&ckr, &cki); flam = ack + sqrt(ack * ack - 1.); fkap = ap / zabs_(&p1r, &p1i); rho = std::min(flam, fkap); tst *= sqrt(rho / (rho * rho - 1.)); itime = 2; L30:; } goto L110; L40: /* ----------------------------------------------------------------------- */ /* BACKWARD RECURRENCE AND SUM NORMALIZING RELATION */ /* ----------------------------------------------------------------------- */ ++k; /* Computing MAX */ i__1 = i__ + iaz, i__2 = k + inu; kk = max(i__1, i__2); fkk = (double)((float)kk); p1r = zeror; p1i = zeroi; /* ----------------------------------------------------------------------- */ /* SCALE P2 AND SUM BY SCLE */ /* ----------------------------------------------------------------------- */ p2r = scle; p2i = zeroi; fnf = *fnu - (double)((float)ifnu); tfnf = fnf + fnf; d__1 = fkk + tfnf + 1.; d__2 = fkk + 1.; d__3 = tfnf + 1.; bk = dgamln_(&d__1, &idum) - dgamln_(&d__2, &idum) - dgamln_(&d__3, &idum); bk = exp(bk); sumr = zeror; sumi = zeroi; km = kk - inu; i__1 = km; for(i__ = 1; i__ <= i__1; ++i__) { ptr = p2r; pti = p2i; p2r = p1r + (fkk + fnf) * (rzr * ptr - rzi * pti); p2i = p1i + (fkk + fnf) * (rzi * ptr + rzr * pti); p1r = ptr; p1i = pti; ak = 1. - tfnf / (fkk + tfnf); ack = bk * ak; sumr += (ack + bk) * p1r; sumi += (ack + bk) * p1i; bk = ack; fkk += -1.; /* L50: */ } yr[*n] = p2r; yi[*n] = p2i; if(*n == 1) { goto L70; } i__1 = *n; for(i__ = 2; i__ <= i__1; ++i__) { ptr = p2r; pti = p2i; p2r = p1r + (fkk + fnf) * (rzr * ptr - rzi * pti); p2i = p1i + (fkk + fnf) * (rzi * ptr + rzr * pti); p1r = ptr; p1i = pti; ak = 1. - tfnf / (fkk + tfnf); ack = bk * ak; sumr += (ack + bk) * p1r; sumi += (ack + bk) * p1i; bk = ack; fkk += -1.; m = *n - i__ + 1; yr[m] = p2r; yi[m] = p2i; /* L60: */ } L70: if(ifnu <= 0) { goto L90; } i__1 = ifnu; for(i__ = 1; i__ <= i__1; ++i__) { ptr = p2r; pti = p2i; p2r = p1r + (fkk + fnf) * (rzr * ptr - rzi * pti); p2i = p1i + (fkk + fnf) * (rzr * pti + rzi * ptr); p1r = ptr; p1i = pti; ak = 1. - tfnf / (fkk + tfnf); ack = bk * ak; sumr += (ack + bk) * p1r; sumi += (ack + bk) * p1i; bk = ack; fkk += -1.; /* L80: */ } L90: ptr = *zr; pti = *zi; if(*kode == 2) { ptr = zeror; } zlog_(&rzr, &rzi, &str, &sti, &idum); p1r = -fnf * str + ptr; p1i = -fnf * sti + pti; d__1 = fnf + 1.; ap = dgamln_(&d__1, &idum); ptr = p1r - ap; pti = p1i; /* ----------------------------------------------------------------------- */ /* THE DIVISION CEXP(PT)/(SUM+P2) IS ALTERED TO AVOID OVERFLOW */ /* IN THE DENOMINATOR BY SQUARING LARGE QUANTITIES */ /* ----------------------------------------------------------------------- */ p2r += sumr; p2i += sumi; ap = zabs_(&p2r, &p2i); p1r = 1. / ap; zexp_(&ptr, &pti, &str, &sti); ckr = str * p1r; cki = sti * p1r; ptr = p2r * p1r; pti = -p2i * p1r; zmlt_(&ckr, &cki, &ptr, &pti, &cnormr, &cnormi); i__1 = *n; for(i__ = 1; i__ <= i__1; ++i__) { str = yr[i__] * cnormr - yi[i__] * cnormi; yi[i__] = yr[i__] * cnormi + yi[i__] * cnormr; yr[i__] = str; /* L100: */ } return 0; L110: *nz = -2; return 0; } /* zmlri_ */ int zmlt_(double* ar, double* ai, double* br, double* bi, double* cr, double* ci) { double ca, cb; /* *********************************************************************72 */ /* c ZMLT carries out double precision System::Complex<float> multiplication. */ /* ***BEGIN PROLOGUE ZMLT */ /* ***REFER TO ZBESH,ZBESI,ZBESJ,ZBESK,ZBESY,ZAIRY,ZBIRY */ /* DOUBLE PRECISION COMPLEX MULTIPLY, C=A*B. */ /* ***ROUTINES CALLED (NONE) */ /* ***END PROLOGUE ZMLT */ ca = *ar * *br - *ai * *bi; cb = *ar * *bi + *ai * *br; *cr = ca; *ci = cb; return 0; } /* zmlt_ */ int zrati_(double* zr, double* zi, double* fnu, int32* n, double* cyr, double* cyi, double* tol) { /* Initialized data */ static double czeror = 0.; static double czeroi = 0.; static double coner = 1.; static double conei = 0.; static double rt2 = 1.41421356237309505; /* System generated locals */ int32 i__1; double d__1; int32 i__, k; double ak; int32 id, kk; double az, ap1, ap2, p1i, p2i, t1i, p1r, p2r, t1r, arg, rak, rho; int32 inu; double pti, tti, rzi, ptr, ttr, rzr, rap1, flam, dfnu, fdnu; int32 magz; int32 idnu; double fnup; double test, test1, amagz; int32 itime; double cdfnui, cdfnur; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE ZRATI */ /* ***REFER TO ZBESI,ZBESK,ZBESH */ /* ZRATI COMPUTES RATIOS OF I BESSEL FUNCTIONS BY BACKWARD */ /* RECURRENCE. THE STARTING INDEX IS DETERMINED BY FORWARD */ /* RECURRENCE AS DESCRIBED IN J. RES. OF NAT. BUR. OF STANDARDS-B, */ /* MATHEMATICAL SCIENCES, VOL 77B, P111-114, SEPTEMBER, 1973, */ /* BESSEL FUNCTIONS I AND J OF COMPLEX ARGUMENT AND INTEGER ORDER, */ /* BY D. J. SOOKNE. */ /* ***ROUTINES CALLED ZABS,ZDIV */ /* ***END PROLOGUE ZRATI */ /* COMPLEX Z,CY(1),CONE,CZERO,P1,P2,T1,RZ,PT,CDFNU */ /* Parameter adjustments */ --cyi; --cyr; /* Function Body */ az = zabs_(zr, zi); inu = (int32)((float)(*fnu)); idnu = inu + *n - 1; magz = (int32)((float)az); amagz = (double)((float)(magz + 1)); fdnu = (double)((float)idnu); fnup = max(amagz, fdnu); id = idnu - magz - 1; itime = 1; k = 1; ptr = 1. / az; rzr = ptr * (*zr + *zr) * ptr; rzi = -ptr * (*zi + *zi) * ptr; t1r = rzr * fnup; t1i = rzi * fnup; p2r = -t1r; p2i = -t1i; p1r = coner; p1i = conei; t1r += rzr; t1i += rzi; if(id > 0) { id = 0; } ap2 = zabs_(&p2r, &p2i); ap1 = zabs_(&p1r, &p1i); /* ----------------------------------------------------------------------- */ /* THE OVERFLOW TEST ON K(FNU+I-1,Z) BEFORE THE CALL TO CBKNU */ /* GUARANTEES THAT P2 IS ON SCALE. SCALE TEST1 AND ALL SUBSEQUENT */ /* P2 VALUES BY AP1 TO ENSURE THAT AN OVERFLOW DOES NOT OCCUR */ /* PREMATURELY. */ /* ----------------------------------------------------------------------- */ arg = (ap2 + ap2) / (ap1 * *tol); test1 = sqrt(arg); test = test1; rap1 = 1. / ap1; p1r *= rap1; p1i *= rap1; p2r *= rap1; p2i *= rap1; ap2 *= rap1; L10: ++k; ap1 = ap2; ptr = p2r; pti = p2i; p2r = p1r - (t1r * ptr - t1i * pti); p2i = p1i - (t1r * pti + t1i * ptr); p1r = ptr; p1i = pti; t1r += rzr; t1i += rzi; ap2 = zabs_(&p2r, &p2i); if(ap1 <= test) { goto L10; } if(itime == 2) { goto L20; } ak = zabs_(&t1r, &t1i) * .5; flam = ak + sqrt(ak * ak - 1.); /* Computing MIN */ d__1 = ap2 / ap1; rho = std::min(d__1, flam); test = test1 * sqrt(rho / (rho * rho - 1.)); itime = 2; goto L10; L20: kk = k + 1 - id; ak = (double)((float)kk); t1r = ak; t1i = czeroi; dfnu = *fnu + (double)((float)(*n - 1)); p1r = 1. / ap2; p1i = czeroi; p2r = czeror; p2i = czeroi; i__1 = kk; for(i__ = 1; i__ <= i__1; ++i__) { ptr = p1r; pti = p1i; rap1 = dfnu + t1r; ttr = rzr * rap1; tti = rzi * rap1; p1r = ptr * ttr - pti * tti + p2r; p1i = ptr * tti + pti * ttr + p2i; p2r = ptr; p2i = pti; t1r -= coner; /* L30: */ } if(p1r != czeror || p1i != czeroi) { goto L40; } p1r = *tol; p1i = *tol; L40: zdiv_(&p2r, &p2i, &p1r, &p1i, &cyr[*n], &cyi[*n]); if(*n == 1) { return 0; } k = *n - 1; ak = (double)((float)k); t1r = ak; t1i = czeroi; cdfnur = *fnu * rzr; cdfnui = *fnu * rzi; i__1 = *n; for(i__ = 2; i__ <= i__1; ++i__) { ptr = cdfnur + (t1r * rzr - t1i * rzi) + cyr[k + 1]; pti = cdfnui + (t1r * rzi + t1i * rzr) + cyi[k + 1]; ak = zabs_(&ptr, &pti); if(ak != czeror) { goto L50; } ptr = *tol; pti = *tol; ak = *tol * rt2; L50: rak = coner / ak; cyr[k] = rak * ptr * rak; cyi[k] = -rak * pti * rak; t1r -= coner; --k; /* L60: */ } return 0; } /* zrati_ */ int zs1s2_(double* zrr, double* zri, double* s1r, double* s1i, double* s2r, double* s2i, int32* nz, double* ascle, double* alim, int32* iuf) { /* Initialized data */ static double zeror = 0.; static double zeroi = 0.; double aa, c1i, as1, as2, c1r, aln, s1di, s1dr; int32 idum; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE ZS1S2 */ /* ***REFER TO ZBESK,ZAIRY */ /* ZS1S2 TESTS FOR A POSSIBLE UNDERFLOW RESULTING FROM THE */ /* ADDITION OF THE I AND K FUNCTIONS IN THE ANALYTIC CON- */ /* TINUATION FORMULA WHERE S1=K FUNCTION AND S2=I FUNCTION. */ /* ON KODE=1 THE I AND K FUNCTIONS ARE DIFFERENT ORDERS OF */ /* MAGNITUDE, BUT FOR KODE=2 THEY CAN BE OF THE SAME ORDER */ /* OF MAGNITUDE AND THE MAXIMUM MUST BE AT LEAST ONE */ /* PRECISION ABOVE THE UNDERFLOW LIMIT. */ /* ***ROUTINES CALLED ZABS,ZEXP,ZLOG */ /* ***END PROLOGUE ZS1S2 */ /* COMPLEX CZERO,C1,S1,S1D,S2,ZR */ *nz = 0; as1 = zabs_(s1r, s1i); as2 = zabs_(s2r, s2i); if(*s1r == 0. && *s1i == 0.) { goto L10; } if(as1 == 0.) { goto L10; } aln = -(*zrr) - *zrr + log(as1); s1dr = *s1r; s1di = *s1i; *s1r = zeror; *s1i = zeroi; as1 = zeror; if(aln < -(*alim)) { goto L10; } zlog_(&s1dr, &s1di, &c1r, &c1i, &idum); c1r = c1r - *zrr - *zrr; c1i = c1i - *zri - *zri; zexp_(&c1r, &c1i, s1r, s1i); as1 = zabs_(s1r, s1i); ++(*iuf); L10: aa = max(as1, as2); if(aa > *ascle) { return 0; } *s1r = zeror; *s1i = zeroi; *s2r = zeror; *s2i = zeroi; *nz = 1; *iuf = 0; return 0; } /* zs1s2_ */ int zseri_(double* zr, double* zi, double* fnu, int32* kode, int32* n, double* yr, double* yi, int32* nz, double* tol, double* elim, double* alim) { /* Initialized data */ static double zeror = 0.; static double zeroi = 0.; static double coner = 1.; static double conei = 0.; /* System generated locals */ int32 i__1; int32 i__, k, l, m; double s, aa; int32 ib; double ak; int32 il; double az; int32 nn; double wi[2], rs, ss; int32 nw; double wr[2], s1i, s2i, s1r, s2r, cki, acz, arm, ckr, czi, hzi, raz, czr, sti, hzr, rzi, str, rzr, ak1i, ak1r, rtr1, dfnu; int32 idum; double atol, fnup; int32 iflag; double coefi, ascle, coefr, crscr; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE ZSERI */ /* ***REFER TO ZBESI,ZBESK */ /* ZSERI COMPUTES THE I BESSEL FUNCTION FOR REAL(Z).GE.0.0 BY */ /* MEANS OF THE POWER SERIES FOR LARGE CABS(Z) IN THE */ /* REGION CABS(Z).LE.2*SQRT(FNU+1). NZ=0 IS A NORMAL RETURN. */ /* NZ.GT.0 MEANS THAT THE LAST NZ COMPONENTS WERE SET TO ZERO */ /* DUE TO UNDERFLOW. NZ.LT.0 MEANS UNDERFLOW OCCURRED, BUT THE */ /* CONDITION CABS(Z).LE.2*SQRT(FNU+1) WAS VIOLATED AND THE */ /* COMPUTATION MUST BE COMPLETED IN ANOTHER ROUTINE WITH N=N-ABS(NZ). */ /* ***ROUTINES CALLED DGAMLN,D1MACH,ZUCHK,ZABS,ZDIV,ZLOG,ZMLT */ /* ***END PROLOGUE ZSERI */ /* COMPLEX AK1,CK,COEF,CONE,CRSC,CSCL,CZ,CZERO,HZ,RZ,S1,S2,Y,Z */ /* Parameter adjustments */ --yi; --yr; /* Function Body */ *nz = 0; az = zabs_(zr, zi); if(az == 0.) { goto L160; } arm = d1mach_(&c__1) * 1e3; rtr1 = sqrt(arm); crscr = 1.; iflag = 0; if(az < arm) { goto L150; } hzr = *zr * .5; hzi = *zi * .5; czr = zeror; czi = zeroi; if(az <= rtr1) { goto L10; } zmlt_(&hzr, &hzi, &hzr, &hzi, &czr, &czi); L10: acz = zabs_(&czr, &czi); nn = *n; zlog_(&hzr, &hzi, &ckr, &cki, &idum); L20: dfnu = *fnu + (double)((float)(nn - 1)); fnup = dfnu + 1.; /* ----------------------------------------------------------------------- */ /* UNDERFLOW TEST */ /* ----------------------------------------------------------------------- */ ak1r = ckr * dfnu; ak1i = cki * dfnu; ak = dgamln_(&fnup, &idum); ak1r -= ak; if(*kode == 2) { ak1r -= *zr; } if(ak1r > -(*elim)) { goto L40; } L30: ++(*nz); yr[nn] = zeror; yi[nn] = zeroi; if(acz > dfnu) { goto L190; } --nn; if(nn == 0) { return 0; } goto L20; L40: if(ak1r > -(*alim)) { goto L50; } iflag = 1; ss = 1. / *tol; crscr = *tol; ascle = arm * ss; L50: aa = exp(ak1r); if(iflag == 1) { aa *= ss; } coefr = aa * cos(ak1i); coefi = aa * sin(ak1i); atol = *tol * acz / fnup; il = std::min(2L, nn); i__1 = il; for(i__ = 1; i__ <= i__1; ++i__) { dfnu = *fnu + (double)((float)(nn - i__)); fnup = dfnu + 1.; s1r = coner; s1i = conei; if(acz < *tol * fnup) { goto L70; } ak1r = coner; ak1i = conei; ak = fnup + 2.; s = fnup; aa = 2.; L60: rs = 1. / s; str = ak1r * czr - ak1i * czi; sti = ak1r * czi + ak1i * czr; ak1r = str * rs; ak1i = sti * rs; s1r += ak1r; s1i += ak1i; s += ak; ak += 2.; aa = aa * acz * rs; if(aa > atol) { goto L60; } L70: s2r = s1r * coefr - s1i * coefi; s2i = s1r * coefi + s1i * coefr; wr[i__ - 1] = s2r; wi[i__ - 1] = s2i; if(iflag == 0) { goto L80; } zuchk_(&s2r, &s2i, &nw, &ascle, tol); if(nw != 0) { goto L30; } L80: m = nn - i__ + 1; yr[m] = s2r * crscr; yi[m] = s2i * crscr; if(i__ == il) { goto L90; } zdiv_(&coefr, &coefi, &hzr, &hzi, &str, &sti); coefr = str * dfnu; coefi = sti * dfnu; L90:; } if(nn <= 2) { return 0; } k = nn - 2; ak = (double)((float)k); raz = 1. / az; str = *zr * raz; sti = -(*zi) * raz; rzr = (str + str) * raz; rzi = (sti + sti) * raz; if(iflag == 1) { goto L120; } ib = 3; L100: i__1 = nn; for(i__ = ib; i__ <= i__1; ++i__) { yr[k] = (ak + *fnu) * (rzr * yr[k + 1] - rzi * yi[k + 1]) + yr[k + 2]; yi[k] = (ak + *fnu) * (rzr * yi[k + 1] + rzi * yr[k + 1]) + yi[k + 2]; ak += -1.; --k; /* L110: */ } return 0; /* ----------------------------------------------------------------------- */ /* RECUR BACKWARD WITH SCALED VALUES */ /* ----------------------------------------------------------------------- */ L120: /* ----------------------------------------------------------------------- */ /* EXP(-ALIM)=EXP(-ELIM)/TOL=APPROX. ONE PRECISION ABOVE THE */ /* UNDERFLOW LIMIT = ASCLE = D1MACH(1)*SS*1.0D+3 */ /* ----------------------------------------------------------------------- */ s1r = wr[0]; s1i = wi[0]; s2r = wr[1]; s2i = wi[1]; i__1 = nn; for(l = 3; l <= i__1; ++l) { ckr = s2r; cki = s2i; s2r = s1r + (ak + *fnu) * (rzr * ckr - rzi * cki); s2i = s1i + (ak + *fnu) * (rzr * cki + rzi * ckr); s1r = ckr; s1i = cki; ckr = s2r * crscr; cki = s2i * crscr; yr[k] = ckr; yi[k] = cki; ak += -1.; --k; if(zabs_(&ckr, &cki) > ascle) { goto L140; } /* L130: */ } return 0; L140: ib = l + 1; if(ib > nn) { return 0; } goto L100; L150: *nz = *n; if(*fnu == 0.) { --(*nz); } L160: yr[1] = zeror; yi[1] = zeroi; if(*fnu != 0.) { goto L170; } yr[1] = coner; yi[1] = conei; L170: if(*n == 1) { return 0; } i__1 = *n; for(i__ = 2; i__ <= i__1; ++i__) { yr[i__] = zeror; yi[i__] = zeroi; /* L180: */ } return 0; /* ----------------------------------------------------------------------- */ /* RETURN WITH NZ.LT.0 IF CABS(Z*Z/4).GT.FNU+N-NZ-1 COMPLETE */ /* THE CALCULATION IN CBINU WITH N=N-IABS(NZ) */ /* ----------------------------------------------------------------------- */ L190: *nz = -(*nz); return 0; } /* zseri_ */ int zshch_(double* zr, double* zi, double* cshr, double* cshi, double* cchr, double* cchi) { double ch, cn, sh, sn; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE ZSHCH */ /* ***REFER TO ZBESK,ZBESH */ /* ZSHCH COMPUTES THE COMPLEX HYPERBOLIC FUNCTIONS CSH=SINH(X+I*Y) */ /* AND CCH=COSH(X+I*Y), WHERE I**2=-1. */ /* ***ROUTINES CALLED (NONE) */ /* ***END PROLOGUE ZSHCH */ sh = sinh(*zr); ch = cosh(*zr); sn = sin(*zi); cn = cos(*zi); *cshr = sh * cn; *cshi = ch * sn; *cchr = ch * cn; *cchi = sh * sn; return 0; } /* zshch_ */ int zsqrt_(double* ar, double* ai, double* br, double* bi) { /* Initialized data */ static double drt = .7071067811865475244008443621; static double dpi = 3.141592653589793238462643383; double zm; double dtheta; /* *********************************************************************72 */ /* c ZSQRT carries out double precision System::Complex<float> square roots. */ /* ***BEGIN PROLOGUE ZSQRT */ /* ***REFER TO ZBESH,ZBESI,ZBESJ,ZBESK,ZBESY,ZAIRY,ZBIRY */ /* DOUBLE PRECISION COMPLEX SQUARE ROOT, B=CSQRT(A) */ /* ***ROUTINES CALLED ZABS */ /* ***END PROLOGUE ZSQRT */ zm = zabs_(ar, ai); zm = sqrt(zm); if(*ar == 0.) { goto L10; } if(*ai == 0.) { goto L20; } dtheta = atan(*ai / *ar); if(dtheta <= 0.) { goto L40; } if(*ar < 0.) { dtheta -= dpi; } goto L50; L10: if(*ai > 0.) { goto L60; } if(*ai < 0.) { goto L70; } *br = 0.; *bi = 0.; return 0; L20: if(*ar > 0.) { goto L30; } *br = 0.; *bi = sqrt((abs(*ar))); return 0; L30: *br = sqrt(*ar); *bi = 0.; return 0; L40: if(*ar < 0.) { dtheta += dpi; } L50: dtheta *= .5; *br = zm * cos(dtheta); *bi = zm * sin(dtheta); return 0; L60: *br = zm * drt; *bi = zm * drt; return 0; L70: *br = zm * drt; *bi = -zm * drt; return 0; } /* zsqrt_ */ int zuchk_(double* yr, double* yi, int32* nz, double* ascle, double* tol) { double wi, ss, st, wr; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE ZUCHK */ /* ***REFER TO ZSERI,ZUOIK,ZUNK1,ZUNK2,ZUNI1,ZUNI2,ZKSCL */ /* Y ENTERS AS A SCALED QUANTITY WHOSE MAGNITUDE IS GREATER THAN */ /* EXP(-ALIM)=ASCLE=1.0E+3*D1MACH(1)/TOL. THE TEST IS MADE TO SEE */ /* IF THE MAGNITUDE OF THE REAL OR IMAGINARY PART WOULD UNDERFLOW */ /* WHEN Y IS SCALED (BY TOL) TO ITS PROPER VALUE. Y IS ACCEPTED */ /* IF THE UNDERFLOW IS AT LEAST ONE PRECISION BELOW THE MAGNITUDE */ /* OF THE LARGEST COMPONENT; OTHERWISE THE PHASE ANGLE DOES NOT HAVE */ /* ABSOLUTE ACCURACY AND AN UNDERFLOW IS ASSUMED. */ /* ***ROUTINES CALLED (NONE) */ /* ***END PROLOGUE ZUCHK */ /* COMPLEX Y */ *nz = 0; wr = abs(*yr); wi = abs(*yi); st = std::min(wr, wi); if(st > *ascle) { return 0; } ss = max(wr, wi); st /= *tol; if(ss < st) { *nz = 1; } return 0; } /* zuchk_ */ int zunhj_(double* zr, double* zi, double* fnu, int32* ipmtr, double* tol, double* phir, double* phii, double* argr, double* argi, double* zeta1r, double* zeta1i, double* zeta2r, double* zeta2i, double* asumr, double* asumi, double* bsumr, double* bsumi) { /* Initialized data */ static double ar[14] = {1., .104166666666666667, .0835503472222222222, .12822657455632716, .291849026464140464, .881627267443757652, 3.32140828186276754, 14.9957629868625547, 78.9230130115865181, 474.451538868264323, 3207.49009089066193, 24086.5496408740049, 198923.119169509794, 1791902.00777534383}; static double br[14] = {1., -.145833333333333333, -.0987413194444444444, -.143312053915895062, -.317227202678413548, -.942429147957120249, -3.51120304082635426, -15.7272636203680451, -82.2814390971859444, -492.355370523670524, -3316.21856854797251, -24827.6742452085896, -204526.587315129788, -1838444.9170682099}; static double c__[105] = {1., -.208333333333333333, .125, .334201388888888889, -.401041666666666667, .0703125, -1.02581259645061728, 1.84646267361111111, -.8912109375, .0732421875, 4.66958442342624743, -11.2070026162229938, 8.78912353515625, -2.3640869140625, .112152099609375, -28.2120725582002449, 84.6362176746007346, -91.8182415432400174, 42.5349987453884549, -7.3687943594796317, .227108001708984375, 212.570130039217123, -765.252468141181642, 1059.99045252799988, -699.579627376132541, 218.19051174421159, -26.4914304869515555, .572501420974731445, -1919.457662318407, 8061.72218173730938, -13586.5500064341374, 11655.3933368645332, -5305.64697861340311, 1200.90291321635246, -108.090919788394656, 1.7277275025844574, 20204.2913309661486, -96980.5983886375135, 192547.001232531532, -203400.177280415534, 122200.46498301746, -41192.6549688975513, 7109.51430248936372, -493.915304773088012, 6.07404200127348304, -242919.187900551333, 1311763.6146629772, -2998015.91853810675, 3763271.297656404, -2813563.22658653411, 1268365.27332162478, -331645.172484563578, 45218.7689813627263, -2499.83048181120962, 24.3805296995560639, 3284469.85307203782, -19706819.1184322269, 50952602.4926646422, -74105148.2115326577, 66344512.2747290267, -37567176.6607633513, 13288767.1664218183, -2785618.12808645469, 308186.404612662398, -13886.0897537170405, 110.017140269246738, -49329253.664509962, 325573074.185765749, -939462359.681578403, 1553596899.57058006, -1621080552.10833708, 1106842816.82301447, -495889784.275030309, 142062907.797533095, -24474062.7257387285, 2243768.17792244943, -84005.4336030240853, 551.335896122020586, 814789096.118312115, -5866481492.05184723, 18688207509.2958249, -34632043388.1587779, 41280185579.753974, -33026599749.8007231, 17954213731.1556001, -6563293792.61928433, 1559279864.87925751, -225105661.889415278, 17395107.5539781645, -549842.327572288687, 3038.09051092238427, -14679261247.6956167, 114498237732.02581, -399096175224.466498, 819218669548.577329, -1098375156081.22331, 1008158106865.38209, -645364869245.376503, 287900649906.150589, -87867072178.0232657, 17634730606.8349694, -2167164983.22379509, 143157876.718888981, -3871833.44257261262, 18257.7554742931747}; static double alfa[180] = { -.00444444444444444444, -9.22077922077922078e-4, -8.84892884892884893e-5, 1.65927687832449737e-4, 2.4669137274179291e-4, 2.6599558934625478e-4, 2.61824297061500945e-4, 2.48730437344655609e-4, 2.32721040083232098e-4, 2.16362485712365082e-4, 2.00738858762752355e-4, 1.86267636637545172e-4, 1.73060775917876493e-4, 1.61091705929015752e-4, 1.50274774160908134e-4, 1.40503497391269794e-4, 1.31668816545922806e-4, 1.23667445598253261e-4, 1.16405271474737902e-4, 1.09798298372713369e-4, 1.03772410422992823e-4, 9.82626078369363448e-5, 9.32120517249503256e-5, 8.85710852478711718e-5, 8.42963105715700223e-5, 8.03497548407791151e-5, 7.66981345359207388e-5, 7.33122157481777809e-5, 7.01662625163141333e-5, 6.72375633790160292e-5, 6.93735541354588974e-4, 2.32241745182921654e-4, -1.41986273556691197e-5, -1.1644493167204864e-4, -1.50803558053048762e-4, -1.55121924918096223e-4, -1.46809756646465549e-4, -1.33815503867491367e-4, -1.19744975684254051e-4, -1.0618431920797402e-4, -9.37699549891194492e-5, -8.26923045588193274e-5, -7.29374348155221211e-5, -6.44042357721016283e-5, -5.69611566009369048e-5, -5.04731044303561628e-5, -4.48134868008882786e-5, -3.98688727717598864e-5, -3.55400532972042498e-5, -3.1741425660902248e-5, -2.83996793904174811e-5, -2.54522720634870566e-5, -2.28459297164724555e-5, -2.05352753106480604e-5, -1.84816217627666085e-5, -1.66519330021393806e-5, -1.50179412980119482e-5, -1.35554031379040526e-5, -1.22434746473858131e-5, -1.10641884811308169e-5, -3.54211971457743841e-4, -1.56161263945159416e-4, 3.0446550359493641e-5, 1.30198655773242693e-4, 1.67471106699712269e-4, 1.70222587683592569e-4, 1.56501427608594704e-4, 1.3633917097744512e-4, 1.14886692029825128e-4, 9.45869093034688111e-5, 7.64498419250898258e-5, 6.07570334965197354e-5, 4.74394299290508799e-5, 3.62757512005344297e-5, 2.69939714979224901e-5, 1.93210938247939253e-5, 1.30056674793963203e-5, 7.82620866744496661e-6, 3.59257485819351583e-6, 1.44040049814251817e-7, -2.65396769697939116e-6, -4.9134686709848591e-6, -6.72739296091248287e-6, -8.17269379678657923e-6, -9.31304715093561232e-6, -1.02011418798016441e-5, -1.0880596251059288e-5, -1.13875481509603555e-5, -1.17519675674556414e-5, -1.19987364870944141e-5, 3.78194199201772914e-4, 2.02471952761816167e-4, -6.37938506318862408e-5, -2.38598230603005903e-4, -3.10916256027361568e-4, -3.13680115247576316e-4, -2.78950273791323387e-4, -2.28564082619141374e-4, -1.75245280340846749e-4, -1.25544063060690348e-4, -8.22982872820208365e-5, -4.62860730588116458e-5, -1.72334302366962267e-5, 5.60690482304602267e-6, 2.313954431482868e-5, 3.62642745856793957e-5, 4.58006124490188752e-5, 5.2459529495911405e-5, 5.68396208545815266e-5, 5.94349820393104052e-5, 6.06478527578421742e-5, 6.08023907788436497e-5, 6.01577894539460388e-5, 5.891996573446985e-5, 5.72515823777593053e-5, 5.52804375585852577e-5, 5.3106377380288017e-5, 5.08069302012325706e-5, 4.84418647620094842e-5, 4.6056858160747537e-5, -6.91141397288294174e-4, -4.29976633058871912e-4, 1.83067735980039018e-4, 6.60088147542014144e-4, 8.75964969951185931e-4, 8.77335235958235514e-4, 7.49369585378990637e-4, 5.63832329756980918e-4, 3.68059319971443156e-4, 1.88464535514455599e-4, 3.70663057664904149e-5, -8.28520220232137023e-5, -1.72751952869172998e-4, -2.36314873605872983e-4, -2.77966150694906658e-4, -3.02079514155456919e-4, -3.12594712643820127e-4, -3.12872558758067163e-4, -3.05678038466324377e-4, -2.93226470614557331e-4, -2.77255655582934777e-4, -2.59103928467031709e-4, -2.39784014396480342e-4, -2.20048260045422848e-4, -2.00443911094971498e-4, -1.81358692210970687e-4, -1.63057674478657464e-4, -1.45712672175205844e-4, -1.29425421983924587e-4, -1.14245691942445952e-4, .00192821964248775885, .00135592576302022234, -7.17858090421302995e-4, -.00258084802575270346, -.00349271130826168475, -.00346986299340960628, -.00282285233351310182, -.00188103076404891354, -8.895317183839476e-4, 3.87912102631035228e-6, 7.28688540119691412e-4, .00126566373053457758, .00162518158372674427, .00183203153216373172, .00191588388990527909, .00190588846755546138, .00182798982421825727, .0017038950642112153, .00155097127171097686, .00138261421852276159, .00120881424230064774, .00103676532638344962, 8.71437918068619115e-4, 7.16080155297701002e-4, 5.72637002558129372e-4, 4.42089819465802277e-4, 3.24724948503090564e-4, 2.20342042730246599e-4, 1.28412898401353882e-4, 4.82005924552095464e-5}; static double beta[210] = { .0179988721413553309, .00559964911064388073, .00288501402231132779, .00180096606761053941, .00124753110589199202, 9.22878876572938311e-4, 7.14430421727287357e-4, 5.71787281789704872e-4, 4.69431007606481533e-4, 3.93232835462916638e-4, 3.34818889318297664e-4, 2.88952148495751517e-4, 2.52211615549573284e-4, 2.22280580798883327e-4, 1.97541838033062524e-4, 1.76836855019718004e-4, 1.59316899661821081e-4, 1.44347930197333986e-4, 1.31448068119965379e-4, 1.20245444949302884e-4, 1.10449144504599392e-4, 1.01828770740567258e-4, 9.41998224204237509e-5, 8.74130545753834437e-5, 8.13466262162801467e-5, 7.59002269646219339e-5, 7.09906300634153481e-5, 6.65482874842468183e-5, 6.25146958969275078e-5, 5.88403394426251749e-5, -.00149282953213429172, -8.78204709546389328e-4, -5.02916549572034614e-4, -2.94822138512746025e-4, -1.75463996970782828e-4, -1.04008550460816434e-4, -5.96141953046457895e-5, -3.1203892907609834e-5, -1.26089735980230047e-5, -2.42892608575730389e-7, 8.05996165414273571e-6, 1.36507009262147391e-5, 1.73964125472926261e-5, 1.9867297884213378e-5, 2.14463263790822639e-5, 2.23954659232456514e-5, 2.28967783814712629e-5, 2.30785389811177817e-5, 2.30321976080909144e-5, 2.28236073720348722e-5, 2.25005881105292418e-5, 2.20981015361991429e-5, 2.16418427448103905e-5, 2.11507649256220843e-5, 2.06388749782170737e-5, 2.01165241997081666e-5, 1.95913450141179244e-5, 1.9068936791043674e-5, 1.85533719641636667e-5, 1.80475722259674218e-5, 5.5221307672129279e-4, 4.47932581552384646e-4, 2.79520653992020589e-4, 1.52468156198446602e-4, 6.93271105657043598e-5, 1.76258683069991397e-5, -1.35744996343269136e-5, -3.17972413350427135e-5, -4.18861861696693365e-5, -4.69004889379141029e-5, -4.87665447413787352e-5, -4.87010031186735069e-5, -4.74755620890086638e-5, -4.55813058138628452e-5, -4.33309644511266036e-5, -4.09230193157750364e-5, -3.84822638603221274e-5, -3.60857167535410501e-5, -3.37793306123367417e-5, -3.15888560772109621e-5, -2.95269561750807315e-5, -2.75978914828335759e-5, -2.58006174666883713e-5, -2.413083567612802e-5, -2.25823509518346033e-5, -2.11479656768912971e-5, -1.98200638885294927e-5, -1.85909870801065077e-5, -1.74532699844210224e-5, -1.63997823854497997e-5, -4.74617796559959808e-4, -4.77864567147321487e-4, -3.20390228067037603e-4, -1.61105016119962282e-4, -4.25778101285435204e-5, 3.44571294294967503e-5, 7.97092684075674924e-5, 1.031382367082722e-4, 1.12466775262204158e-4, 1.13103642108481389e-4, 1.08651634848774268e-4, 1.01437951597661973e-4, 9.29298396593363896e-5, 8.40293133016089978e-5, 7.52727991349134062e-5, 6.69632521975730872e-5, 5.92564547323194704e-5, 5.22169308826975567e-5, 4.58539485165360646e-5, 4.01445513891486808e-5, 3.50481730031328081e-5, 3.05157995034346659e-5, 2.64956119950516039e-5, 2.29363633690998152e-5, 1.97893056664021636e-5, 1.70091984636412623e-5, 1.45547428261524004e-5, 1.23886640995878413e-5, 1.04775876076583236e-5, 8.79179954978479373e-6, 7.36465810572578444e-4, 8.72790805146193976e-4, 6.22614862573135066e-4, 2.85998154194304147e-4, 3.84737672879366102e-6, -1.87906003636971558e-4, -2.97603646594554535e-4, -3.45998126832656348e-4, -3.53382470916037712e-4, -3.35715635775048757e-4, -3.04321124789039809e-4, -2.66722723047612821e-4, -2.27654214122819527e-4, -1.89922611854562356e-4, -1.5505891859909387e-4, -1.2377824076187363e-4, -9.62926147717644187e-5, -7.25178327714425337e-5, -5.22070028895633801e-5, -3.50347750511900522e-5, -2.06489761035551757e-5, -8.70106096849767054e-6, 1.1369868667510029e-6, 9.16426474122778849e-6, 1.5647778542887262e-5, 2.08223629482466847e-5, 2.48923381004595156e-5, 2.80340509574146325e-5, 3.03987774629861915e-5, 3.21156731406700616e-5, -.00180182191963885708, -.00243402962938042533, -.00183422663549856802, -7.62204596354009765e-4, 2.39079475256927218e-4, 9.49266117176881141e-4, .00134467449701540359, .00148457495259449178, .00144732339830617591, .00130268261285657186, .00110351597375642682, 8.86047440419791759e-4, 6.73073208165665473e-4, 4.77603872856582378e-4, 3.05991926358789362e-4, 1.6031569459472163e-4, 4.00749555270613286e-5, -5.66607461635251611e-5, -1.32506186772982638e-4, -1.90296187989614057e-4, -2.32811450376937408e-4, -2.62628811464668841e-4, -2.82050469867598672e-4, -2.93081563192861167e-4, -2.97435962176316616e-4, -2.96557334239348078e-4, -2.91647363312090861e-4, -2.83696203837734166e-4, -2.73512317095673346e-4, -2.6175015580676858e-4, .00638585891212050914, .00962374215806377941, .00761878061207001043, .00283219055545628054, -.0020984135201272009, -.00573826764216626498, -.0077080424449541462, -.00821011692264844401, -.00765824520346905413, -.00647209729391045177, -.00499132412004966473, -.0034561228971313328, -.00201785580014170775, -7.59430686781961401e-4, 2.84173631523859138e-4, .00110891667586337403, .00172901493872728771, .00216812590802684701, .00245357710494539735, .00261281821058334862, .00267141039656276912, .0026520307339598043, .00257411652877287315, .00245389126236094427, .00230460058071795494, .00213684837686712662, .00195896528478870911, .00177737008679454412, .00159690280765839059, .00142111975664438546}; static double gama[30] = {.629960524947436582, .251984209978974633, .154790300415655846, .110713062416159013, .0857309395527394825, .0697161316958684292, .0586085671893713576, .0504698873536310685, .0442600580689154809, .0393720661543509966, .0354283195924455368, .0321818857502098231, .0294646240791157679, .0271581677112934479, .0251768272973861779, .0234570755306078891, .0219508390134907203, .020621082823564624, .0194388240897880846, .0183810633800683158, .0174293213231963172, .0165685837786612353, .0157865285987918445, .0150729501494095594, .0144193250839954639, .0138184805735341786, .0132643378994276568, .0127517121970498651, .0122761545318762767, .0118338262398482403}; static double ex1 = .333333333333333333; static double ex2 = .666666666666666667; static double hpi = 1.57079632679489662; static double gpi = 3.14159265358979324; static double thpi = 4.71238898038468986; static double zeror = 0.; static double zeroi = 0.; static double coner = 1.; static double conei = 0.; /* System generated locals */ int32 i__1, i__2; double d__1; int32 j, k, l, m, l1, l2; double ac, ap[30], pi[30]; int32 is, jr, ks, ju; double pp, wi, pr[30]; int32 lr; double wr, aw2; int32 kp1; double t2i, w2i, t2r, w2r, ang, fn13, fn23; int32 ias; double cri[14], dri[14]; int32 ibs; double zai, zbi, zci, crr[14], drr[14], raw, zar, upi[14], sti, zbr, zcr, upr[14], str, raw2; int32 lrp1; double rfn13; int32 idum; double atol, btol, tfni; int32 kmax; double azth, tzai, tfnr, rfnu; double zthi, test, tzar, zthr, rfnu2, zetai, ptfni, sumai, sumbi, zetar, ptfnr, razth, sumar, sumbr, rzthi; double rzthr, rtzti; double rtztr, przthi, przthr; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE ZUNHJ */ /* ***REFER TO ZBESI,ZBESK */ /* REFERENCES */ /* HANDBOOK OF MATHEMATICAL FUNCTIONS BY M. ABRAMOWITZ AND I.A. */ /* STEGUN, AMS55, NATIONAL BUREAU OF STANDARDS, 1965, CHAPTER 9. */ /* ASYMPTOTICS AND SPECIAL FUNCTIONS BY F.W.J. OLVER, ACADEMIC */ /* PRESS, N.Y., 1974, PAGE 420 */ /* ABSTRACT */ /* ZUNHJ COMPUTES PARAMETERS FOR BESSEL FUNCTIONS C(FNU,Z) = */ /* J(FNU,Z), Y(FNU,Z) OR H(I,FNU,Z) I=1,2 FOR LARGE ORDERS FNU */ /* BY MEANS OF THE UNIFORM ASYMPTOTIC EXPANSION */ /* C(FNU,Z)=C1*PHI*( ASUM*AIRY(ARG) + C2*BSUM*DAIRY(ARG) ) */ /* FOR PROPER CHOICES OF C1, C2, AIRY AND DAIRY WHERE AIRY IS */ /* AN AIRY FUNCTION AND DAIRY IS ITS DERIVATIVE. */ /* (2/3)*FNU*ZETA**1.5 = ZETA1-ZETA2, */ /* ZETA1=0.5*FNU*CLOG((1+W)/(1-W)), ZETA2=FNU*W FOR SCALING */ /* PURPOSES IN AIRY FUNCTIONS FROM CAIRY OR CBIRY. */ /* MCONJ=SIGN OF AIMAG(Z), BUT IS AMBIGUOUS WHEN Z IS REAL AND */ /* MUST BE SPECIFIED. IPMTR=0 RETURNS ALL PARAMETERS. IPMTR= */ /* 1 COMPUTES ALL EXCEPT ASUM AND BSUM. */ /* ***ROUTINES CALLED ZABS,ZDIV,ZLOG,ZSQRT,D1MACH */ /* ***END PROLOGUE ZUNHJ */ /* COMPLEX ARG,ASUM,BSUM,CFNU,CONE,CR,CZERO,DR,P,PHI,PRZTH,PTFN, */ /* *RFN13,RTZTA,RZTH,SUMA,SUMB,TFN,T2,UP,W,W2,Z,ZA,ZB,ZC,ZETA,ZETA1, */ /* *ZETA2,ZTH */ rfnu = 1. / *fnu; /* ----------------------------------------------------------------------- */ /* OVERFLOW TEST (Z/FNU TOO SMALL) */ /* ----------------------------------------------------------------------- */ test = d1mach_(&c__1) * 1e3; ac = *fnu * test; if(abs(*zr) > ac || abs(*zi) > ac) { goto L15; } *zeta1r = (d__1 = log(test), abs(d__1)) * 2. + *fnu; *zeta1i = 0.; *zeta2r = *fnu; *zeta2i = 0.; *phir = 1.; *phii = 0.; *argr = 1.; *argi = 0.; return 0; L15: zbr = *zr * rfnu; zbi = *zi * rfnu; rfnu2 = rfnu * rfnu; /* ----------------------------------------------------------------------- */ /* COMPUTE IN THE FOURTH QUADRANT */ /* ----------------------------------------------------------------------- */ fn13 = pow_dd(fnu, &ex1); fn23 = fn13 * fn13; rfn13 = 1. / fn13; w2r = coner - zbr * zbr + zbi * zbi; w2i = conei - zbr * zbi - zbr * zbi; aw2 = zabs_(&w2r, &w2i); if(aw2 > .25) { goto L130; } /* ----------------------------------------------------------------------- */ /* POWER SERIES FOR CABS(W2).LE.0.25D0 */ /* ----------------------------------------------------------------------- */ k = 1; pr[0] = coner; pi[0] = conei; sumar = gama[0]; sumai = zeroi; ap[0] = 1.; if(aw2 < *tol) { goto L20; } for(k = 2; k <= 30; ++k) { pr[k - 1] = pr[k - 2] * w2r - pi[k - 2] * w2i; pi[k - 1] = pr[k - 2] * w2i + pi[k - 2] * w2r; sumar += pr[k - 1] * gama[k - 1]; sumai += pi[k - 1] * gama[k - 1]; ap[k - 1] = ap[k - 2] * aw2; if(ap[k - 1] < *tol) { goto L20; } /* L10: */ } k = 30; L20: kmax = k; zetar = w2r * sumar - w2i * sumai; zetai = w2r * sumai + w2i * sumar; *argr = zetar * fn23; *argi = zetai * fn23; zsqrt_(&sumar, &sumai, &zar, &zai); zsqrt_(&w2r, &w2i, &str, &sti); *zeta2r = str * *fnu; *zeta2i = sti * *fnu; str = coner + ex2 * (zetar * zar - zetai * zai); sti = conei + ex2 * (zetar * zai + zetai * zar); *zeta1r = str * *zeta2r - sti * *zeta2i; *zeta1i = str * *zeta2i + sti * *zeta2r; zar += zar; zai += zai; zsqrt_(&zar, &zai, &str, &sti); *phir = str * rfn13; *phii = sti * rfn13; if(*ipmtr == 1) { goto L120; } /* ----------------------------------------------------------------------- */ /* SUM SERIES FOR ASUM AND BSUM */ /* ----------------------------------------------------------------------- */ sumbr = zeror; sumbi = zeroi; i__1 = kmax; for(k = 1; k <= i__1; ++k) { sumbr += pr[k - 1] * beta[k - 1]; sumbi += pi[k - 1] * beta[k - 1]; /* L30: */ } *asumr = zeror; *asumi = zeroi; *bsumr = sumbr; *bsumi = sumbi; l1 = 0; l2 = 30; btol = *tol * (abs(*bsumr) + abs(*bsumi)); atol = *tol; pp = 1.; ias = 0; ibs = 0; if(rfnu2 < *tol) { goto L110; } for(is = 2; is <= 7; ++is) { atol /= rfnu2; pp *= rfnu2; if(ias == 1) { goto L60; } sumar = zeror; sumai = zeroi; i__1 = kmax; for(k = 1; k <= i__1; ++k) { m = l1 + k; sumar += pr[k - 1] * alfa[m - 1]; sumai += pi[k - 1] * alfa[m - 1]; if(ap[k - 1] < atol) { goto L50; } /* L40: */ } L50: *asumr += sumar * pp; *asumi += sumai * pp; if(pp < *tol) { ias = 1; } L60: if(ibs == 1) { goto L90; } sumbr = zeror; sumbi = zeroi; i__1 = kmax; for(k = 1; k <= i__1; ++k) { m = l2 + k; sumbr += pr[k - 1] * beta[m - 1]; sumbi += pi[k - 1] * beta[m - 1]; if(ap[k - 1] < atol) { goto L80; } /* L70: */ } L80: *bsumr += sumbr * pp; *bsumi += sumbi * pp; if(pp < btol) { ibs = 1; } L90: if(ias == 1 && ibs == 1) { goto L110; } l1 += 30; l2 += 30; /* L100: */ } L110: *asumr += coner; pp = rfnu * rfn13; *bsumr *= pp; *bsumi *= pp; L120: return 0; /* ----------------------------------------------------------------------- */ /* CABS(W2).GT.0.25D0 */ /* ----------------------------------------------------------------------- */ L130: zsqrt_(&w2r, &w2i, &wr, &wi); if(wr < 0.) { wr = 0.; } if(wi < 0.) { wi = 0.; } str = coner + wr; sti = wi; zdiv_(&str, &sti, &zbr, &zbi, &zar, &zai); zlog_(&zar, &zai, &zcr, &zci, &idum); if(zci < 0.) { zci = 0.; } if(zci > hpi) { zci = hpi; } if(zcr < 0.) { zcr = 0.; } zthr = (zcr - wr) * 1.5; zthi = (zci - wi) * 1.5; *zeta1r = zcr * *fnu; *zeta1i = zci * *fnu; *zeta2r = wr * *fnu; *zeta2i = wi * *fnu; azth = zabs_(&zthr, &zthi); ang = thpi; if(zthr >= 0. && zthi < 0.) { goto L140; } ang = hpi; if(zthr == 0.) { goto L140; } ang = atan(zthi / zthr); if(zthr < 0.) { ang += gpi; } L140: pp = pow_dd(&azth, &ex2); ang *= ex2; zetar = pp * cos(ang); zetai = pp * sin(ang); if(zetai < 0.) { zetai = 0.; } *argr = zetar * fn23; *argi = zetai * fn23; zdiv_(&zthr, &zthi, &zetar, &zetai, &rtztr, &rtzti); zdiv_(&rtztr, &rtzti, &wr, &wi, &zar, &zai); tzar = zar + zar; tzai = zai + zai; zsqrt_(&tzar, &tzai, &str, &sti); *phir = str * rfn13; *phii = sti * rfn13; if(*ipmtr == 1) { goto L120; } raw = 1. / sqrt(aw2); str = wr * raw; sti = -wi * raw; tfnr = str * rfnu * raw; tfni = sti * rfnu * raw; razth = 1. / azth; str = zthr * razth; sti = -zthi * razth; rzthr = str * razth * rfnu; rzthi = sti * razth * rfnu; zcr = rzthr * ar[1]; zci = rzthi * ar[1]; raw2 = 1. / aw2; str = w2r * raw2; sti = -w2i * raw2; t2r = str * raw2; t2i = sti * raw2; str = t2r * c__[1] + c__[2]; sti = t2i * c__[1]; upr[1] = str * tfnr - sti * tfni; upi[1] = str * tfni + sti * tfnr; *bsumr = upr[1] + zcr; *bsumi = upi[1] + zci; *asumr = zeror; *asumi = zeroi; if(rfnu < *tol) { goto L220; } przthr = rzthr; przthi = rzthi; ptfnr = tfnr; ptfni = tfni; upr[0] = coner; upi[0] = conei; pp = 1.; btol = *tol * (abs(*bsumr) + abs(*bsumi)); ks = 0; kp1 = 2; l = 3; ias = 0; ibs = 0; for(lr = 2; lr <= 12; lr += 2) { lrp1 = lr + 1; /* ----------------------------------------------------------------------- */ /* COMPUTE TWO ADDITIONAL CR, DR, AND UP FOR TWO MORE TERMS IN */ /* NEXT SUMA AND SUMB */ /* ----------------------------------------------------------------------- */ i__1 = lrp1; for(k = lr; k <= i__1; ++k) { ++ks; ++kp1; ++l; zar = c__[l - 1]; zai = zeroi; i__2 = kp1; for(j = 2; j <= i__2; ++j) { ++l; str = zar * t2r - t2i * zai + c__[l - 1]; zai = zar * t2i + zai * t2r; zar = str; /* L150: */ } str = ptfnr * tfnr - ptfni * tfni; ptfni = ptfnr * tfni + ptfni * tfnr; ptfnr = str; upr[kp1 - 1] = ptfnr * zar - ptfni * zai; upi[kp1 - 1] = ptfni * zar + ptfnr * zai; crr[ks - 1] = przthr * br[ks]; cri[ks - 1] = przthi * br[ks]; str = przthr * rzthr - przthi * rzthi; przthi = przthr * rzthi + przthi * rzthr; przthr = str; drr[ks - 1] = przthr * ar[ks + 1]; dri[ks - 1] = przthi * ar[ks + 1]; /* L160: */ } pp *= rfnu2; if(ias == 1) { goto L180; } sumar = upr[lrp1 - 1]; sumai = upi[lrp1 - 1]; ju = lrp1; i__1 = lr; for(jr = 1; jr <= i__1; ++jr) { --ju; sumar = sumar + crr[jr - 1] * upr[ju - 1] - cri[jr - 1] * upi[ju - 1]; sumai = sumai + crr[jr - 1] * upi[ju - 1] + cri[jr - 1] * upr[ju - 1]; /* L170: */ } *asumr += sumar; *asumi += sumai; test = abs(sumar) + abs(sumai); if(pp < *tol && test < *tol) { ias = 1; } L180: if(ibs == 1) { goto L200; } sumbr = upr[lr + 1] + upr[lrp1 - 1] * zcr - upi[lrp1 - 1] * zci; sumbi = upi[lr + 1] + upr[lrp1 - 1] * zci + upi[lrp1 - 1] * zcr; ju = lrp1; i__1 = lr; for(jr = 1; jr <= i__1; ++jr) { --ju; sumbr = sumbr + drr[jr - 1] * upr[ju - 1] - dri[jr - 1] * upi[ju - 1]; sumbi = sumbi + drr[jr - 1] * upi[ju - 1] + dri[jr - 1] * upr[ju - 1]; /* L190: */ } *bsumr += sumbr; *bsumi += sumbi; test = abs(sumbr) + abs(sumbi); if(pp < btol && test < btol) { ibs = 1; } L200: if(ias == 1 && ibs == 1) { goto L220; } /* L210: */ } L220: *asumr += coner; str = -(*bsumr) * rfn13; sti = -(*bsumi) * rfn13; zdiv_(&str, &sti, &rtztr, &rtzti, bsumr, bsumi); goto L120; } /* zunhj_ */ int zuni1_(double* zr, double* zi, double* fnu, int32* kode, int32* n, double* yr, double* yi, int32* nz, int32* nlast, double* fnul, double* tol, double* elim, double* alim) { /* Initialized data */ static double zeror = 0.; static double zeroi = 0.; static double coner = 1.; /* System generated locals */ int32 i__1; int32 i__, k, m, nd; double fn; int32 nn, nw; double c2i, c2m, c1r, c2r, s1i, s2i, rs1, s1r, s2r, cyi[2]; int32 nuf; double bry[3], cyr[2], sti, rzi, str, rzr, aphi, cscl, phii, crsc; double phir; int32 init; double csrr[3], cssr[3], rast, sumi, sumr; int32 iflag; double ascle, cwrki[16]; double cwrkr[16]; double zeta1i, zeta2i, zeta1r, zeta2r; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE ZUNI1 */ /* ***REFER TO ZBESI,ZBESK */ /* ZUNI1 COMPUTES I(FNU,Z) BY MEANS OF THE UNIFORM ASYMPTOTIC */ /* EXPANSION FOR I(FNU,Z) IN -PI/3.LE.ARG Z.LE.PI/3. */ /* FNUL IS THE SMALLEST ORDER PERMITTED FOR THE ASYMPTOTIC */ /* EXPANSION. NLAST=0 MEANS ALL OF THE Y VALUES WERE SET. */ /* NLAST.NE.0 IS THE NUMBER LEFT TO BE COMPUTED BY ANOTHER */ /* FORMULA FOR ORDERS FNU TO FNU+NLAST-1 BECAUSE FNU+NLAST-1.LT.FNUL. */ /* Y(I)=CZERO FOR I=NLAST+1,N */ /* ***ROUTINES CALLED ZUCHK,ZUNIK,ZUOIK,D1MACH,ZABS */ /* ***END PROLOGUE ZUNI1 */ /* COMPLEX CFN,CONE,CRSC,CSCL,CSR,CSS,CWRK,CZERO,C1,C2,PHI,RZ,SUM,S1, */ /* *S2,Y,Z,ZETA1,ZETA2 */ /* Parameter adjustments */ --yi; --yr; /* Function Body */ *nz = 0; nd = *n; *nlast = 0; /* ----------------------------------------------------------------------- */ /* COMPUTED VALUES WITH EXPONENTS BETWEEN ALIM AND ELIM IN MAG- */ /* NITUDE ARE SCALED TO KEEP INTERMEDIATE ARITHMETIC ON SCALE, */ /* EXP(ALIM)=EXP(ELIM)*TOL */ /* ----------------------------------------------------------------------- */ cscl = 1. / *tol; crsc = *tol; cssr[0] = cscl; cssr[1] = coner; cssr[2] = crsc; csrr[0] = crsc; csrr[1] = coner; csrr[2] = cscl; bry[0] = d1mach_(&c__1) * 1e3 / *tol; /* ----------------------------------------------------------------------- */ /* CHECK FOR UNDERFLOW AND OVERFLOW ON FIRST MEMBER */ /* ----------------------------------------------------------------------- */ fn = max(*fnu, 1.); init = 0; zunik_(zr, zi, &fn, &c__1, &c__1, tol, &init, &phir, &phii, &zeta1r, &zeta1i, &zeta2r, &zeta2i, &sumr, &sumi, cwrkr, cwrki); if(*kode == 1) { goto L10; } str = *zr + zeta2r; sti = *zi + zeta2i; rast = fn / zabs_(&str, &sti); str = str * rast * rast; sti = -sti * rast * rast; s1r = -zeta1r + str; s1i = -zeta1i + sti; goto L20; L10: s1r = -zeta1r + zeta2r; s1i = -zeta1i + zeta2i; L20: rs1 = s1r; if(abs(rs1) > *elim) { goto L130; } L30: nn = std::min(2L, nd); i__1 = nn; for(i__ = 1; i__ <= i__1; ++i__) { fn = *fnu + (double)((float)(nd - i__)); init = 0; zunik_(zr, zi, &fn, &c__1, &c__0, tol, &init, &phir, &phii, &zeta1r, &zeta1i, &zeta2r, &zeta2i, &sumr, &sumi, cwrkr, cwrki); if(*kode == 1) { goto L40; } str = *zr + zeta2r; sti = *zi + zeta2i; rast = fn / zabs_(&str, &sti); str = str * rast * rast; sti = -sti * rast * rast; s1r = -zeta1r + str; s1i = -zeta1i + sti + *zi; goto L50; L40: s1r = -zeta1r + zeta2r; s1i = -zeta1i + zeta2i; L50: /* ----------------------------------------------------------------------- */ /* TEST FOR UNDERFLOW AND OVERFLOW */ /* ----------------------------------------------------------------------- */ rs1 = s1r; if(abs(rs1) > *elim) { goto L110; } if(i__ == 1) { iflag = 2; } if(abs(rs1) < *alim) { goto L60; } /* ----------------------------------------------------------------------- */ /* REFINE TEST AND SCALE */ /* ----------------------------------------------------------------------- */ aphi = zabs_(&phir, &phii); rs1 += log(aphi); if(abs(rs1) > *elim) { goto L110; } if(i__ == 1) { iflag = 1; } if(rs1 < 0.) { goto L60; } if(i__ == 1) { iflag = 3; } L60: /* ----------------------------------------------------------------------- */ /* SCALE S1 IF CABS(S1).LT.ASCLE */ /* ----------------------------------------------------------------------- */ s2r = phir * sumr - phii * sumi; s2i = phir * sumi + phii * sumr; str = exp(s1r) * cssr[iflag - 1]; s1r = str * cos(s1i); s1i = str * sin(s1i); str = s2r * s1r - s2i * s1i; s2i = s2r * s1i + s2i * s1r; s2r = str; if(iflag != 1) { goto L70; } zuchk_(&s2r, &s2i, &nw, bry, tol); if(nw != 0) { goto L110; } L70: cyr[i__ - 1] = s2r; cyi[i__ - 1] = s2i; m = nd - i__ + 1; yr[m] = s2r * csrr[iflag - 1]; yi[m] = s2i * csrr[iflag - 1]; /* L80: */ } if(nd <= 2) { goto L100; } rast = 1. / zabs_(zr, zi); str = *zr * rast; sti = -(*zi) * rast; rzr = (str + str) * rast; rzi = (sti + sti) * rast; bry[1] = 1. / bry[0]; bry[2] = d1mach_(&c__2); s1r = cyr[0]; s1i = cyi[0]; s2r = cyr[1]; s2i = cyi[1]; c1r = csrr[iflag - 1]; ascle = bry[iflag - 1]; k = nd - 2; fn = (double)((float)k); i__1 = nd; for(i__ = 3; i__ <= i__1; ++i__) { c2r = s2r; c2i = s2i; s2r = s1r + (*fnu + fn) * (rzr * c2r - rzi * c2i); s2i = s1i + (*fnu + fn) * (rzr * c2i + rzi * c2r); s1r = c2r; s1i = c2i; c2r = s2r * c1r; c2i = s2i * c1r; yr[k] = c2r; yi[k] = c2i; --k; fn += -1.; if(iflag >= 3) { goto L90; } str = abs(c2r); sti = abs(c2i); c2m = max(str, sti); if(c2m <= ascle) { goto L90; } ++iflag; ascle = bry[iflag - 1]; s1r *= c1r; s1i *= c1r; s2r = c2r; s2i = c2i; s1r *= cssr[iflag - 1]; s1i *= cssr[iflag - 1]; s2r *= cssr[iflag - 1]; s2i *= cssr[iflag - 1]; c1r = csrr[iflag - 1]; L90:; } L100: return 0; /* ----------------------------------------------------------------------- */ /* SET UNDERFLOW AND UPDATE PARAMETERS */ /* ----------------------------------------------------------------------- */ L110: if(rs1 > 0.) { goto L120; } yr[nd] = zeror; yi[nd] = zeroi; ++(*nz); --nd; if(nd == 0) { goto L100; } zuoik_(zr, zi, fnu, kode, &c__1, &nd, &yr[1], &yi[1], &nuf, tol, elim, alim); if(nuf < 0) { goto L120; } nd -= nuf; *nz += nuf; if(nd == 0) { goto L100; } fn = *fnu + (double)((float)(nd - 1)); if(fn >= *fnul) { goto L30; } *nlast = nd; return 0; L120: *nz = -1; return 0; L130: if(rs1 > 0.) { goto L120; } *nz = *n; i__1 = *n; for(i__ = 1; i__ <= i__1; ++i__) { yr[i__] = zeror; yi[i__] = zeroi; /* L140: */ } return 0; } /* zuni1_ */ int zuni2_(double* zr, double* zi, double* fnu, int32* kode, int32* n, double* yr, double* yi, int32* nz, int32* nlast, double* fnul, double* tol, double* elim, double* alim) { /* Initialized data */ static double zeror = 0.; static double zeroi = 0.; static double coner = 1.; static double cipr[4] = {1., 0., -1., 0.}; static double cipi[4] = {0., 1., 0., -1.}; static double hpi = 1.57079632679489662; static double aic = 1.265512123484645396; /* System generated locals */ int32 i__1; int32 i__, j, k, nd; double fn; int32 in, nn, nw; double c2i, c2m, c1r, c2r, s1i, s2i, rs1, s1r, s2r, aii, ang, car; int32 nai; double air, zbi, cyi[2], sar; int32 nuf, inu; double bry[3], raz, sti, zbr, zni, cyr[2], rzi, str, znr, rzr, daii, cidi, aarg; int32 ndai; double dair, aphi, argi, cscl, phii, crsc, argr; int32 idum; double phir, csrr[3], cssr[3], rast; int32 iflag; double ascle, asumi, bsumi; double asumr, bsumr; double zeta1i, zeta2i, zeta1r, zeta2r; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE ZUNI2 */ /* ***REFER TO ZBESI,ZBESK */ /* ZUNI2 COMPUTES I(FNU,Z) IN THE RIGHT HALF PLANE BY MEANS OF */ /* UNIFORM ASYMPTOTIC EXPANSION FOR J(FNU,ZN) WHERE ZN IS Z*I */ /* OR -Z*I AND ZN IS IN THE RIGHT HALF PLANE ALSO. */ /* FNUL IS THE SMALLEST ORDER PERMITTED FOR THE ASYMPTOTIC */ /* EXPANSION. NLAST=0 MEANS ALL OF THE Y VALUES WERE SET. */ /* NLAST.NE.0 IS THE NUMBER LEFT TO BE COMPUTED BY ANOTHER */ /* FORMULA FOR ORDERS FNU TO FNU+NLAST-1 BECAUSE FNU+NLAST-1.LT.FNUL. */ /* Y(I)=CZERO FOR I=NLAST+1,N */ /* ***ROUTINES CALLED ZAIRY,ZUCHK,ZUNHJ,ZUOIK,D1MACH,ZABS */ /* ***END PROLOGUE ZUNI2 */ /* COMPLEX AI,ARG,ASUM,BSUM,CFN,CI,CID,CIP,CONE,CRSC,CSCL,CSR,CSS, */ /* *CZERO,C1,C2,DAI,PHI,RZ,S1,S2,Y,Z,ZB,ZETA1,ZETA2,ZN */ /* Parameter adjustments */ --yi; --yr; /* Function Body */ *nz = 0; nd = *n; *nlast = 0; /* ----------------------------------------------------------------------- */ /* COMPUTED VALUES WITH EXPONENTS BETWEEN ALIM AND ELIM IN MAG- */ /* NITUDE ARE SCALED TO KEEP INTERMEDIATE ARITHMETIC ON SCALE, */ /* EXP(ALIM)=EXP(ELIM)*TOL */ /* ----------------------------------------------------------------------- */ cscl = 1. / *tol; crsc = *tol; cssr[0] = cscl; cssr[1] = coner; cssr[2] = crsc; csrr[0] = crsc; csrr[1] = coner; csrr[2] = cscl; bry[0] = d1mach_(&c__1) * 1e3 / *tol; /* ----------------------------------------------------------------------- */ /* ZN IS IN THE RIGHT HALF PLANE AFTER ROTATION BY CI OR -CI */ /* ----------------------------------------------------------------------- */ znr = *zi; zni = -(*zr); zbr = *zr; zbi = *zi; cidi = -coner; inu = (int32)((float)(*fnu)); ang = hpi * (*fnu - (double)((float)inu)); c2r = cos(ang); c2i = sin(ang); car = c2r; sar = c2i; in = inu + *n - 1; in = in % 4 + 1; str = c2r * cipr[in - 1] - c2i * cipi[in - 1]; c2i = c2r * cipi[in - 1] + c2i * cipr[in - 1]; c2r = str; if(*zi > 0.) { goto L10; } znr = -znr; zbi = -zbi; cidi = -cidi; c2i = -c2i; L10: /* ----------------------------------------------------------------------- */ /* CHECK FOR UNDERFLOW AND OVERFLOW ON FIRST MEMBER */ /* ----------------------------------------------------------------------- */ fn = max(*fnu, 1.); zunhj_(&znr, &zni, &fn, &c__1, tol, &phir, &phii, &argr, &argi, &zeta1r, &zeta1i, &zeta2r, &zeta2i, &asumr, &asumi, &bsumr, &bsumi); if(*kode == 1) { goto L20; } str = zbr + zeta2r; sti = zbi + zeta2i; rast = fn / zabs_(&str, &sti); str = str * rast * rast; sti = -sti * rast * rast; s1r = -zeta1r + str; s1i = -zeta1i + sti; goto L30; L20: s1r = -zeta1r + zeta2r; s1i = -zeta1i + zeta2i; L30: rs1 = s1r; if(abs(rs1) > *elim) { goto L150; } L40: nn = std::min(2L, nd); i__1 = nn; for(i__ = 1; i__ <= i__1; ++i__) { fn = *fnu + (double)((float)(nd - i__)); zunhj_(&znr, &zni, &fn, &c__0, tol, &phir, &phii, &argr, &argi, &zeta1r, &zeta1i, &zeta2r, &zeta2i, &asumr, &asumi, &bsumr, &bsumi); if(*kode == 1) { goto L50; } str = zbr + zeta2r; sti = zbi + zeta2i; rast = fn / zabs_(&str, &sti); str = str * rast * rast; sti = -sti * rast * rast; s1r = -zeta1r + str; s1i = -zeta1i + sti + abs(*zi); goto L60; L50: s1r = -zeta1r + zeta2r; s1i = -zeta1i + zeta2i; L60: /* ----------------------------------------------------------------------- */ /* TEST FOR UNDERFLOW AND OVERFLOW */ /* ----------------------------------------------------------------------- */ rs1 = s1r; if(abs(rs1) > *elim) { goto L120; } if(i__ == 1) { iflag = 2; } if(abs(rs1) < *alim) { goto L70; } /* ----------------------------------------------------------------------- */ /* REFINE TEST AND SCALE */ /* ----------------------------------------------------------------------- */ /* ----------------------------------------------------------------------- */ aphi = zabs_(&phir, &phii); aarg = zabs_(&argr, &argi); rs1 = rs1 + log(aphi) - log(aarg) * .25 - aic; if(abs(rs1) > *elim) { goto L120; } if(i__ == 1) { iflag = 1; } if(rs1 < 0.) { goto L70; } if(i__ == 1) { iflag = 3; } L70: /* ----------------------------------------------------------------------- */ /* SCALE S1 TO KEEP INTERMEDIATE ARITHMETIC ON SCALE NEAR */ /* EXPONENT EXTREMES */ /* ----------------------------------------------------------------------- */ zairy_(&argr, &argi, &c__0, &c__2, &air, &aii, &nai, &idum); zairy_(&argr, &argi, &c__1, &c__2, &dair, &daii, &ndai, &idum); str = dair * bsumr - daii * bsumi; sti = dair * bsumi + daii * bsumr; str += air * asumr - aii * asumi; sti += air * asumi + aii * asumr; s2r = phir * str - phii * sti; s2i = phir * sti + phii * str; str = exp(s1r) * cssr[iflag - 1]; s1r = str * cos(s1i); s1i = str * sin(s1i); str = s2r * s1r - s2i * s1i; s2i = s2r * s1i + s2i * s1r; s2r = str; if(iflag != 1) { goto L80; } zuchk_(&s2r, &s2i, &nw, bry, tol); if(nw != 0) { goto L120; } L80: if(*zi <= 0.) { s2i = -s2i; } str = s2r * c2r - s2i * c2i; s2i = s2r * c2i + s2i * c2r; s2r = str; cyr[i__ - 1] = s2r; cyi[i__ - 1] = s2i; j = nd - i__ + 1; yr[j] = s2r * csrr[iflag - 1]; yi[j] = s2i * csrr[iflag - 1]; str = -c2i * cidi; c2i = c2r * cidi; c2r = str; /* L90: */ } if(nd <= 2) { goto L110; } raz = 1. / zabs_(zr, zi); str = *zr * raz; sti = -(*zi) * raz; rzr = (str + str) * raz; rzi = (sti + sti) * raz; bry[1] = 1. / bry[0]; bry[2] = d1mach_(&c__2); s1r = cyr[0]; s1i = cyi[0]; s2r = cyr[1]; s2i = cyi[1]; c1r = csrr[iflag - 1]; ascle = bry[iflag - 1]; k = nd - 2; fn = (double)((float)k); i__1 = nd; for(i__ = 3; i__ <= i__1; ++i__) { c2r = s2r; c2i = s2i; s2r = s1r + (*fnu + fn) * (rzr * c2r - rzi * c2i); s2i = s1i + (*fnu + fn) * (rzr * c2i + rzi * c2r); s1r = c2r; s1i = c2i; c2r = s2r * c1r; c2i = s2i * c1r; yr[k] = c2r; yi[k] = c2i; --k; fn += -1.; if(iflag >= 3) { goto L100; } str = abs(c2r); sti = abs(c2i); c2m = max(str, sti); if(c2m <= ascle) { goto L100; } ++iflag; ascle = bry[iflag - 1]; s1r *= c1r; s1i *= c1r; s2r = c2r; s2i = c2i; s1r *= cssr[iflag - 1]; s1i *= cssr[iflag - 1]; s2r *= cssr[iflag - 1]; s2i *= cssr[iflag - 1]; c1r = csrr[iflag - 1]; L100:; } L110: return 0; L120: if(rs1 > 0.) { goto L140; } /* ----------------------------------------------------------------------- */ /* SET UNDERFLOW AND UPDATE PARAMETERS */ /* ----------------------------------------------------------------------- */ yr[nd] = zeror; yi[nd] = zeroi; ++(*nz); --nd; if(nd == 0) { goto L110; } zuoik_(zr, zi, fnu, kode, &c__1, &nd, &yr[1], &yi[1], &nuf, tol, elim, alim); if(nuf < 0) { goto L140; } nd -= nuf; *nz += nuf; if(nd == 0) { goto L110; } fn = *fnu + (double)((float)(nd - 1)); if(fn < *fnul) { goto L130; } /* FN = CIDI */ /* J = NUF + 1 */ /* K = MOD(J,4) + 1 */ /* S1R = CIPR(K) */ /* S1I = CIPI(K) */ /* IF (FN.LT.0.0D0) S1I = -S1I */ /* STR = C2R*S1R - C2I*S1I */ /* C2I = C2R*S1I + C2I*S1R */ /* C2R = STR */ in = inu + nd - 1; in = in % 4 + 1; c2r = car * cipr[in - 1] - sar * cipi[in - 1]; c2i = car * cipi[in - 1] + sar * cipr[in - 1]; if(*zi <= 0.) { c2i = -c2i; } goto L40; L130: *nlast = nd; return 0; L140: *nz = -1; return 0; L150: if(rs1 > 0.) { goto L140; } *nz = *n; i__1 = *n; for(i__ = 1; i__ <= i__1; ++i__) { yr[i__] = zeror; yi[i__] = zeroi; /* L160: */ } return 0; } /* zuni2_ */ int zunik_(double* zrr, double* zri, double* fnu, int32* ikflg, int32* ipmtr, double* tol, int32* init, double* phir, double* phii, double* zeta1r, double* zeta1i, double* zeta2r, double* zeta2i, double* sumr, double* sumi, double* cwrkr, double* cwrki) { /* Initialized data */ static double zeror = 0.; static double zeroi = 0.; static double coner = 1.; static double conei = 0.; static double con[2] = {.398942280401432678, 1.25331413731550025}; static double c__[120] = {1., -.208333333333333333, .125, .334201388888888889, -.401041666666666667, .0703125, -1.02581259645061728, 1.84646267361111111, -.8912109375, .0732421875, 4.66958442342624743, -11.2070026162229938, 8.78912353515625, -2.3640869140625, .112152099609375, -28.2120725582002449, 84.6362176746007346, -91.8182415432400174, 42.5349987453884549, -7.3687943594796317, .227108001708984375, 212.570130039217123, -765.252468141181642, 1059.99045252799988, -699.579627376132541, 218.19051174421159, -26.4914304869515555, .572501420974731445, -1919.457662318407, 8061.72218173730938, -13586.5500064341374, 11655.3933368645332, -5305.64697861340311, 1200.90291321635246, -108.090919788394656, 1.7277275025844574, 20204.2913309661486, -96980.5983886375135, 192547.001232531532, -203400.177280415534, 122200.46498301746, -41192.6549688975513, 7109.51430248936372, -493.915304773088012, 6.07404200127348304, -242919.187900551333, 1311763.6146629772, -2998015.91853810675, 3763271.297656404, -2813563.22658653411, 1268365.27332162478, -331645.172484563578, 45218.7689813627263, -2499.83048181120962, 24.3805296995560639, 3284469.85307203782, -19706819.1184322269, 50952602.4926646422, -74105148.2115326577, 66344512.2747290267, -37567176.6607633513, 13288767.1664218183, -2785618.12808645469, 308186.404612662398, -13886.0897537170405, 110.017140269246738, -49329253.664509962, 325573074.185765749, -939462359.681578403, 1553596899.57058006, -1621080552.10833708, 1106842816.82301447, -495889784.275030309, 142062907.797533095, -24474062.7257387285, 2243768.17792244943, -84005.4336030240853, 551.335896122020586, 814789096.118312115, -5866481492.05184723, 18688207509.2958249, -34632043388.1587779, 41280185579.753974, -33026599749.8007231, 17954213731.1556001, -6563293792.61928433, 1559279864.87925751, -225105661.889415278, 17395107.5539781645, -549842.327572288687, 3038.09051092238427, -14679261247.6956167, 114498237732.02581, -399096175224.466498, 819218669548.577329, -1098375156081.22331, 1008158106865.38209, -645364869245.376503, 287900649906.150589, -87867072178.0232657, 17634730606.8349694, -2167164983.22379509, 143157876.718888981, -3871833.44257261262, 18257.7554742931747, 286464035717.679043, -2406297900028.50396, 9109341185239.89896, -20516899410934.4374, 30565125519935.3206, -31667088584785.1584, 23348364044581.8409, -12320491305598.2872, 4612725780849.13197, -1196552880196.1816, 205914503232.410016, -21822927757.5292237, 1247009293.51271032, -29188388.1222208134, 118838.426256783253}; /* System generated locals */ int32 i__1; double d__1, d__2; int32 i__, j, k, l; double ac, si, ti, sr, tr, t2i, t2r, rfn, sri, sti, zni, srr, str, znr; int32 idum; double test, crfni, crfnr; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE ZUNIK */ /* ***REFER TO ZBESI,ZBESK */ /* ZUNIK COMPUTES PARAMETERS FOR THE UNIFORM ASYMPTOTIC */ /* EXPANSIONS OF THE I AND K FUNCTIONS ON IKFLG= 1 OR 2 */ /* RESPECTIVELY BY */ /* W(FNU,ZR) = PHI*EXP(ZETA)*SUM */ /* WHERE ZETA=-ZETA1 + ZETA2 OR */ /* ZETA1 - ZETA2 */ /* THE FIRST CALL MUST HAVE INIT=0. SUBSEQUENT CALLS WITH THE */ /* SAME ZR AND FNU WILL RETURN THE I OR K FUNCTION ON IKFLG= */ /* 1 OR 2 WITH NO CHANGE IN INIT. CWRK IS A COMPLEX WORK */ /* ARRAY. IPMTR=0 COMPUTES ALL PARAMETERS. IPMTR=1 COMPUTES PHI, */ /* ZETA1,ZETA2. */ /* ***ROUTINES CALLED ZDIV,ZLOG,ZSQRT,D1MACH */ /* ***END PROLOGUE ZUNIK */ /* COMPLEX CFN,CON,CONE,CRFN,CWRK,CZERO,PHI,S,SR,SUM,T,T2,ZETA1, */ /* *ZETA2,ZN,ZR */ /* Parameter adjustments */ --cwrki; --cwrkr; /* Function Body */ if(*init != 0) { goto L40; } /* ----------------------------------------------------------------------- */ /* INITIALIZE ALL VARIABLES */ /* ----------------------------------------------------------------------- */ rfn = 1. / *fnu; /* ----------------------------------------------------------------------- */ /* OVERFLOW TEST (ZR/FNU TOO SMALL) */ /* ----------------------------------------------------------------------- */ test = d1mach_(&c__1) * 1e3; ac = *fnu * test; if(abs(*zrr) > ac || abs(*zri) > ac) { goto L15; } *zeta1r = (d__1 = log(test), abs(d__1)) * 2. + *fnu; *zeta1i = 0.; *zeta2r = *fnu; *zeta2i = 0.; *phir = 1.; *phii = 0.; return 0; L15: tr = *zrr * rfn; ti = *zri * rfn; sr = coner + (tr * tr - ti * ti); si = conei + (tr * ti + ti * tr); zsqrt_(&sr, &si, &srr, &sri); str = coner + srr; sti = conei + sri; zdiv_(&str, &sti, &tr, &ti, &znr, &zni); zlog_(&znr, &zni, &str, &sti, &idum); *zeta1r = *fnu * str; *zeta1i = *fnu * sti; *zeta2r = *fnu * srr; *zeta2i = *fnu * sri; zdiv_(&coner, &conei, &srr, &sri, &tr, &ti); srr = tr * rfn; sri = ti * rfn; zsqrt_(&srr, &sri, &cwrkr[16], &cwrki[16]); *phir = cwrkr[16] * con[*ikflg - 1]; *phii = cwrki[16] * con[*ikflg - 1]; if(*ipmtr != 0) { return 0; } zdiv_(&coner, &conei, &sr, &si, &t2r, &t2i); cwrkr[1] = coner; cwrki[1] = conei; crfnr = coner; crfni = conei; ac = 1.; l = 1; for(k = 2; k <= 15; ++k) { sr = zeror; si = zeroi; i__1 = k; for(j = 1; j <= i__1; ++j) { ++l; str = sr * t2r - si * t2i + c__[l - 1]; si = sr * t2i + si * t2r; sr = str; /* L10: */ } str = crfnr * srr - crfni * sri; crfni = crfnr * sri + crfni * srr; crfnr = str; cwrkr[k] = crfnr * sr - crfni * si; cwrki[k] = crfnr * si + crfni * sr; ac *= rfn; test = (d__1 = cwrkr[k], abs(d__1)) + (d__2 = cwrki[k], abs(d__2)); if(ac < *tol && test < *tol) { goto L30; } /* L20: */ } k = 15; L30: *init = k; L40: if(*ikflg == 2) { goto L60; } /* ----------------------------------------------------------------------- */ /* COMPUTE SUM FOR THE I FUNCTION */ /* ----------------------------------------------------------------------- */ sr = zeror; si = zeroi; i__1 = *init; for(i__ = 1; i__ <= i__1; ++i__) { sr += cwrkr[i__]; si += cwrki[i__]; /* L50: */ } *sumr = sr; *sumi = si; *phir = cwrkr[16] * con[0]; *phii = cwrki[16] * con[0]; return 0; L60: /* ----------------------------------------------------------------------- */ /* COMPUTE SUM FOR THE K FUNCTION */ /* ----------------------------------------------------------------------- */ sr = zeror; si = zeroi; tr = coner; i__1 = *init; for(i__ = 1; i__ <= i__1; ++i__) { sr += tr * cwrkr[i__]; si += tr * cwrki[i__]; tr = -tr; /* L70: */ } *sumr = sr; *sumi = si; *phir = cwrkr[16] * con[1]; *phii = cwrki[16] * con[1]; return 0; } /* zunik_ */ int zunk1_(double* zr, double* zi, double* fnu, int32* kode, int32* mr, int32* n, double* yr, double* yi, int32* nz, double* tol, double* elim, double* alim) { /* Initialized data */ static double zeror = 0.; static double zeroi = 0.; static double coner = 1.; static double pi = 3.14159265358979324; /* System generated locals */ int32 i__1; int32 i__, j, k, m, ib, ic; double fn; int32 il, kk, nw; double c1i, c2i, c2m, c1r, c2r, s1i, s2i, rs1, s1r, s2r, ang, asc, cki, fnf; int32 ifn; double ckr; int32 iuf; double cyi[2], fmr, csr, sgn; int32 inu; double bry[3], cyr[2], sti, rzi, zri, str, rzr, zrr, aphi, cscl, phii[2], crsc; double phir[2]; int32 init[2]; double csrr[3], cssr[3], rast, sumi[2], razr; double sumr[2]; int32 iflag, kflag; double ascle; int32 kdflg; double phidi; int32 ipard; double csgni, phidr; int32 initd; double cspni, cwrki[48] /* was [16][3] */, sumdi; double cspnr, cwrkr[48] /* was [16][3] */, sumdr; double zeta1i[2], zeta2i[2], zet1di, zet2di, zeta1r[2], zeta2r[2], zet1dr, zet2dr; #define cwrki_ref(a_1, a_2) cwrki[(a_2)*16 + a_1 - 17] #define cwrkr_ref(a_1, a_2) cwrkr[(a_2)*16 + a_1 - 17] /* *********************************************************************72 */ /* ***BEGIN PROLOGUE ZUNK1 */ /* ***REFER TO ZBESK */ /* ZUNK1 COMPUTES K(FNU,Z) AND ITS ANALYTIC CONTINUATION FROM THE */ /* RIGHT HALF PLANE TO THE LEFT HALF PLANE BY MEANS OF THE */ /* UNIFORM ASYMPTOTIC EXPANSION. */ /* MR INDICATES THE DIRECTION OF ROTATION FOR ANALYTIC CONTINUATION. */ /* NZ=-1 MEANS AN OVERFLOW WILL OCCUR */ /* ***ROUTINES CALLED ZKSCL,ZS1S2,ZUCHK,ZUNIK,D1MACH,ZABS */ /* ***END PROLOGUE ZUNK1 */ /* COMPLEX CFN,CK,CONE,CRSC,CS,CSCL,CSGN,CSPN,CSR,CSS,CWRK,CY,CZERO, */ /* *C1,C2,PHI,PHID,RZ,SUM,SUMD,S1,S2,Y,Z,ZETA1,ZETA1D,ZETA2,ZETA2D,ZR */ /* Parameter adjustments */ --yi; --yr; /* Function Body */ kdflg = 1; *nz = 0; /* ----------------------------------------------------------------------- */ /* EXP(-ALIM)=EXP(-ELIM)/TOL=APPROX. ONE PRECISION GREATER THAN */ /* THE UNDERFLOW LIMIT */ /* ----------------------------------------------------------------------- */ cscl = 1. / *tol; crsc = *tol; cssr[0] = cscl; cssr[1] = coner; cssr[2] = crsc; csrr[0] = crsc; csrr[1] = coner; csrr[2] = cscl; bry[0] = d1mach_(&c__1) * 1e3 / *tol; bry[1] = 1. / bry[0]; bry[2] = d1mach_(&c__2); zrr = *zr; zri = *zi; if(*zr >= 0.) { goto L10; } zrr = -(*zr); zri = -(*zi); L10: j = 2; i__1 = *n; for(i__ = 1; i__ <= i__1; ++i__) { /* ----------------------------------------------------------------------- */ /* J FLIP FLOPS BETWEEN 1 AND 2 IN J = 3 - J */ /* ----------------------------------------------------------------------- */ j = 3 - j; fn = *fnu + (double)((float)(i__ - 1)); init[j - 1] = 0; zunik_(&zrr, &zri, &fn, &c__2, &c__0, tol, &init[j - 1], &phir[j - 1], &phii[j - 1], &zeta1r[j - 1], &zeta1i[j - 1], &zeta2r[j - 1], &zeta2i[j - 1], &sumr[j - 1], &sumi[j - 1], &cwrkr_ref(1, j), &cwrki_ref(1, j)); if(*kode == 1) { goto L20; } str = zrr + zeta2r[j - 1]; sti = zri + zeta2i[j - 1]; rast = fn / zabs_(&str, &sti); str = str * rast * rast; sti = -sti * rast * rast; s1r = zeta1r[j - 1] - str; s1i = zeta1i[j - 1] - sti; goto L30; L20: s1r = zeta1r[j - 1] - zeta2r[j - 1]; s1i = zeta1i[j - 1] - zeta2i[j - 1]; L30: rs1 = s1r; /* ----------------------------------------------------------------------- */ /* TEST FOR UNDERFLOW AND OVERFLOW */ /* ----------------------------------------------------------------------- */ if(abs(rs1) > *elim) { goto L60; } if(kdflg == 1) { kflag = 2; } if(abs(rs1) < *alim) { goto L40; } /* ----------------------------------------------------------------------- */ /* REFINE TEST AND SCALE */ /* ----------------------------------------------------------------------- */ aphi = zabs_(&phir[j - 1], &phii[j - 1]); rs1 += log(aphi); if(abs(rs1) > *elim) { goto L60; } if(kdflg == 1) { kflag = 1; } if(rs1 < 0.) { goto L40; } if(kdflg == 1) { kflag = 3; } L40: /* ----------------------------------------------------------------------- */ /* SCALE S1 TO KEEP INTERMEDIATE ARITHMETIC ON SCALE NEAR */ /* EXPONENT EXTREMES */ /* ----------------------------------------------------------------------- */ s2r = phir[j - 1] * sumr[j - 1] - phii[j - 1] * sumi[j - 1]; s2i = phir[j - 1] * sumi[j - 1] + phii[j - 1] * sumr[j - 1]; str = exp(s1r) * cssr[kflag - 1]; s1r = str * cos(s1i); s1i = str * sin(s1i); str = s2r * s1r - s2i * s1i; s2i = s1r * s2i + s2r * s1i; s2r = str; if(kflag != 1) { goto L50; } zuchk_(&s2r, &s2i, &nw, bry, tol); if(nw != 0) { goto L60; } L50: cyr[kdflg - 1] = s2r; cyi[kdflg - 1] = s2i; yr[i__] = s2r * csrr[kflag - 1]; yi[i__] = s2i * csrr[kflag - 1]; if(kdflg == 2) { goto L75; } kdflg = 2; goto L70; L60: if(rs1 > 0.) { goto L300; } /* ----------------------------------------------------------------------- */ /* FOR ZR.LT.0.0, THE I FUNCTION TO BE ADDED WILL OVERFLOW */ /* ----------------------------------------------------------------------- */ if(*zr < 0.) { goto L300; } kdflg = 1; yr[i__] = zeror; yi[i__] = zeroi; ++(*nz); if(i__ == 1) { goto L70; } if(yr[i__ - 1] == zeror && yi[i__ - 1] == zeroi) { goto L70; } yr[i__ - 1] = zeror; yi[i__ - 1] = zeroi; ++(*nz); L70:; } i__ = *n; L75: razr = 1. / zabs_(&zrr, &zri); str = zrr * razr; sti = -zri * razr; rzr = (str + str) * razr; rzi = (sti + sti) * razr; ckr = fn * rzr; cki = fn * rzi; ib = i__ + 1; if(*n < ib) { goto L160; } /* ----------------------------------------------------------------------- */ /* TEST LAST MEMBER FOR UNDERFLOW AND OVERFLOW. SET SEQUENCE TO ZERO */ /* ON UNDERFLOW. */ /* ----------------------------------------------------------------------- */ fn = *fnu + (double)((float)(*n - 1)); ipard = 1; if(*mr != 0) { ipard = 0; } initd = 0; zunik_(&zrr, &zri, &fn, &c__2, &ipard, tol, &initd, &phidr, &phidi, &zet1dr, &zet1di, &zet2dr, &zet2di, &sumdr, &sumdi, &cwrkr_ref(1, 3), &cwrki_ref(1, 3)); if(*kode == 1) { goto L80; } str = zrr + zet2dr; sti = zri + zet2di; rast = fn / zabs_(&str, &sti); str = str * rast * rast; sti = -sti * rast * rast; s1r = zet1dr - str; s1i = zet1di - sti; goto L90; L80: s1r = zet1dr - zet2dr; s1i = zet1di - zet2di; L90: rs1 = s1r; if(abs(rs1) > *elim) { goto L95; } if(abs(rs1) < *alim) { goto L100; } /* ---------------------------------------------------------------------------- */ /* REFINE ESTIMATE AND TEST */ /* ------------------------------------------------------------------------- */ aphi = zabs_(&phidr, &phidi); rs1 += log(aphi); if(abs(rs1) < *elim) { goto L100; } L95: if(abs(rs1) > 0.) { goto L300; } /* ----------------------------------------------------------------------- */ /* FOR ZR.LT.0.0, THE I FUNCTION TO BE ADDED WILL OVERFLOW */ /* ----------------------------------------------------------------------- */ if(*zr < 0.) { goto L300; } *nz = *n; i__1 = *n; for(i__ = 1; i__ <= i__1; ++i__) { yr[i__] = zeror; yi[i__] = zeroi; /* L96: */ } return 0; /* --------------------------------------------------------------------------- */ /* FORWARD RECUR FOR REMAINDER OF THE SEQUENCE */ /* ---------------------------------------------------------------------------- */ L100: s1r = cyr[0]; s1i = cyi[0]; s2r = cyr[1]; s2i = cyi[1]; c1r = csrr[kflag - 1]; ascle = bry[kflag - 1]; i__1 = *n; for(i__ = ib; i__ <= i__1; ++i__) { c2r = s2r; c2i = s2i; s2r = ckr * c2r - cki * c2i + s1r; s2i = ckr * c2i + cki * c2r + s1i; s1r = c2r; s1i = c2i; ckr += rzr; cki += rzi; c2r = s2r * c1r; c2i = s2i * c1r; yr[i__] = c2r; yi[i__] = c2i; if(kflag >= 3) { goto L120; } str = abs(c2r); sti = abs(c2i); c2m = max(str, sti); if(c2m <= ascle) { goto L120; } ++kflag; ascle = bry[kflag - 1]; s1r *= c1r; s1i *= c1r; s2r = c2r; s2i = c2i; s1r *= cssr[kflag - 1]; s1i *= cssr[kflag - 1]; s2r *= cssr[kflag - 1]; s2i *= cssr[kflag - 1]; c1r = csrr[kflag - 1]; L120:; } L160: if(*mr == 0) { return 0; } /* ----------------------------------------------------------------------- */ /* ANALYTIC CONTINUATION FOR RE(Z).LT.0.0D0 */ /* ----------------------------------------------------------------------- */ *nz = 0; fmr = (double)((float)(*mr)); sgn = -d_sign(&pi, &fmr); /* ----------------------------------------------------------------------- */ /* CSPN AND CSGN ARE COEFF OF K AND I FUNCTIONS RESP. */ /* ----------------------------------------------------------------------- */ csgni = sgn; inu = (int32)((float)(*fnu)); fnf = *fnu - (double)((float)inu); ifn = inu + *n - 1; ang = fnf * sgn; cspnr = cos(ang); cspni = sin(ang); if(ifn % 2 == 0) { goto L170; } cspnr = -cspnr; cspni = -cspni; L170: asc = bry[0]; iuf = 0; kk = *n; kdflg = 1; --ib; ic = ib - 1; i__1 = *n; for(k = 1; k <= i__1; ++k) { fn = *fnu + (double)((float)(kk - 1)); /* ----------------------------------------------------------------------- */ /* LOGIC TO SORT OUT CASES WHOSE PARAMETERS WERE SET FOR THE K */ /* FUNCTION ABOVE */ /* ----------------------------------------------------------------------- */ m = 3; if(*n > 2) { goto L175; } L172: initd = init[j - 1]; phidr = phir[j - 1]; phidi = phii[j - 1]; zet1dr = zeta1r[j - 1]; zet1di = zeta1i[j - 1]; zet2dr = zeta2r[j - 1]; zet2di = zeta2i[j - 1]; sumdr = sumr[j - 1]; sumdi = sumi[j - 1]; m = j; j = 3 - j; goto L180; L175: if(kk == *n && ib < *n) { goto L180; } if(kk == ib || kk == ic) { goto L172; } initd = 0; L180: zunik_(&zrr, &zri, &fn, &c__1, &c__0, tol, &initd, &phidr, &phidi, &zet1dr, &zet1di, &zet2dr, &zet2di, &sumdr, &sumdi, &cwrkr_ref(1, m), &cwrki_ref(1, m)); if(*kode == 1) { goto L200; } str = zrr + zet2dr; sti = zri + zet2di; rast = fn / zabs_(&str, &sti); str = str * rast * rast; sti = -sti * rast * rast; s1r = -zet1dr + str; s1i = -zet1di + sti; goto L210; L200: s1r = -zet1dr + zet2dr; s1i = -zet1di + zet2di; L210: /* ----------------------------------------------------------------------- */ /* TEST FOR UNDERFLOW AND OVERFLOW */ /* ----------------------------------------------------------------------- */ rs1 = s1r; if(abs(rs1) > *elim) { goto L260; } if(kdflg == 1) { iflag = 2; } if(abs(rs1) < *alim) { goto L220; } /* ----------------------------------------------------------------------- */ /* REFINE TEST AND SCALE */ /* ----------------------------------------------------------------------- */ aphi = zabs_(&phidr, &phidi); rs1 += log(aphi); if(abs(rs1) > *elim) { goto L260; } if(kdflg == 1) { iflag = 1; } if(rs1 < 0.) { goto L220; } if(kdflg == 1) { iflag = 3; } L220: str = phidr * sumdr - phidi * sumdi; sti = phidr * sumdi + phidi * sumdr; s2r = -csgni * sti; s2i = csgni * str; str = exp(s1r) * cssr[iflag - 1]; s1r = str * cos(s1i); s1i = str * sin(s1i); str = s2r * s1r - s2i * s1i; s2i = s2r * s1i + s2i * s1r; s2r = str; if(iflag != 1) { goto L230; } zuchk_(&s2r, &s2i, &nw, bry, tol); if(nw == 0) { goto L230; } s2r = zeror; s2i = zeroi; L230: cyr[kdflg - 1] = s2r; cyi[kdflg - 1] = s2i; c2r = s2r; c2i = s2i; s2r *= csrr[iflag - 1]; s2i *= csrr[iflag - 1]; /* ----------------------------------------------------------------------- */ /* ADD I AND K FUNCTIONS, K SEQUENCE IN Y(I), I=1,N */ /* ----------------------------------------------------------------------- */ s1r = yr[kk]; s1i = yi[kk]; if(*kode == 1) { goto L250; } zs1s2_(&zrr, &zri, &s1r, &s1i, &s2r, &s2i, &nw, &asc, alim, &iuf); *nz += nw; L250: yr[kk] = s1r * cspnr - s1i * cspni + s2r; yi[kk] = cspnr * s1i + cspni * s1r + s2i; --kk; cspnr = -cspnr; cspni = -cspni; if(c2r != 0. || c2i != 0.) { goto L255; } kdflg = 1; goto L270; L255: if(kdflg == 2) { goto L275; } kdflg = 2; goto L270; L260: if(rs1 > 0.) { goto L300; } s2r = zeror; s2i = zeroi; goto L230; L270:; } k = *n; L275: il = *n - k; if(il == 0) { return 0; } /* ----------------------------------------------------------------------- */ /* RECUR BACKWARD FOR REMAINDER OF I SEQUENCE AND ADD IN THE */ /* K FUNCTIONS, SCALING THE I SEQUENCE DURING RECURRENCE TO KEEP */ /* INTERMEDIATE ARITHMETIC ON SCALE NEAR EXPONENT EXTREMES. */ /* ----------------------------------------------------------------------- */ s1r = cyr[0]; s1i = cyi[0]; s2r = cyr[1]; s2i = cyi[1]; csr = csrr[iflag - 1]; ascle = bry[iflag - 1]; fn = (double)((float)(inu + il)); i__1 = il; for(i__ = 1; i__ <= i__1; ++i__) { c2r = s2r; c2i = s2i; s2r = s1r + (fn + fnf) * (rzr * c2r - rzi * c2i); s2i = s1i + (fn + fnf) * (rzr * c2i + rzi * c2r); s1r = c2r; s1i = c2i; fn += -1.; c2r = s2r * csr; c2i = s2i * csr; ckr = c2r; cki = c2i; c1r = yr[kk]; c1i = yi[kk]; if(*kode == 1) { goto L280; } zs1s2_(&zrr, &zri, &c1r, &c1i, &c2r, &c2i, &nw, &asc, alim, &iuf); *nz += nw; L280: yr[kk] = c1r * cspnr - c1i * cspni + c2r; yi[kk] = c1r * cspni + c1i * cspnr + c2i; --kk; cspnr = -cspnr; cspni = -cspni; if(iflag >= 3) { goto L290; } c2r = abs(ckr); c2i = abs(cki); c2m = max(c2r, c2i); if(c2m <= ascle) { goto L290; } ++iflag; ascle = bry[iflag - 1]; s1r *= csr; s1i *= csr; s2r = ckr; s2i = cki; s1r *= cssr[iflag - 1]; s1i *= cssr[iflag - 1]; s2r *= cssr[iflag - 1]; s2i *= cssr[iflag - 1]; csr = csrr[iflag - 1]; L290:; } return 0; L300: *nz = -1; return 0; } /* zunk1_ */ #undef cwrkr_ref #undef cwrki_ref int zunk2_(double* zr, double* zi, double* fnu, int32* kode, int32* mr, int32* n, double* yr, double* yi, int32* nz, double* tol, double* elim, double* alim) { /* Initialized data */ static double zeror = 0.; static double zeroi = 0.; static double coner = 1.; static double cr1r = 1.; static double cr1i = 1.73205080756887729; static double cr2r = -.5; static double cr2i = -.866025403784438647; static double hpi = 1.57079632679489662; static double pi = 3.14159265358979324; static double aic = 1.26551212348464539; static double cipr[4] = {1., 0., -1., 0.}; static double cipi[4] = {0., -1., 0., 1.}; /* System generated locals */ int32 i__1; int32 i__, j, k, ib, ic; double fn; int32 il, kk, in, nw; double yy, c1i, c2i, c2m, c1r, c2r, s1i, s2i, rs1, s1r, s2r, aii, ang, asc, car, cki, fnf; int32 nai; double air; int32 ifn; double csi, ckr; int32 iuf; double cyi[2], fmr, sar, csr, sgn, zbi; int32 inu; double bry[3], cyr[2], pti, sti, zbr, zni, rzi, ptr, zri, str, znr, rzr, zrr, daii, aarg; int32 ndai; double dair, aphi, argi[2], cscl, phii[2], crsc, argr[2]; int32 idum; double phir[2], csrr[3], cssr[3], rast, razr; int32 iflag, kflag; double argdi, ascle; int32 kdflg; double phidi, argdr; int32 ipard; double csgni, phidr, cspni, asumi[2], bsumi[2]; double cspnr, asumr[2], bsumr[2]; double zeta1i[2], zeta2i[2], zet1di, zet2di, zeta1r[2], zeta2r[2], zet1dr, zet2dr, asumdi, bsumdi, asumdr, bsumdr; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE ZUNK2 */ /* ***REFER TO ZBESK */ /* ZUNK2 COMPUTES K(FNU,Z) AND ITS ANALYTIC CONTINUATION FROM THE */ /* RIGHT HALF PLANE TO THE LEFT HALF PLANE BY MEANS OF THE */ /* UNIFORM ASYMPTOTIC EXPANSIONS FOR H(KIND,FNU,ZN) AND J(FNU,ZN) */ /* WHERE ZN IS IN THE RIGHT HALF PLANE, KIND=(3-MR)/2, MR=+1 OR */ /* -1. HERE ZN=ZR*I OR -ZR*I WHERE ZR=Z IF Z IS IN THE RIGHT */ /* HALF PLANE OR ZR=-Z IF Z IS IN THE LEFT HALF PLANE. MR INDIC- */ /* ATES THE DIRECTION OF ROTATION FOR ANALYTIC CONTINUATION. */ /* NZ=-1 MEANS AN OVERFLOW WILL OCCUR */ /* ***ROUTINES CALLED ZAIRY,ZKSCL,ZS1S2,ZUCHK,ZUNHJ,D1MACH,ZABS */ /* ***END PROLOGUE ZUNK2 */ /* COMPLEX AI,ARG,ARGD,ASUM,ASUMD,BSUM,BSUMD,CFN,CI,CIP,CK,CONE,CRSC, */ /* *CR1,CR2,CS,CSCL,CSGN,CSPN,CSR,CSS,CY,CZERO,C1,C2,DAI,PHI,PHID,RZ, */ /* *S1,S2,Y,Z,ZB,ZETA1,ZETA1D,ZETA2,ZETA2D,ZN,ZR */ /* Parameter adjustments */ --yi; --yr; /* Function Body */ kdflg = 1; *nz = 0; /* ----------------------------------------------------------------------- */ /* EXP(-ALIM)=EXP(-ELIM)/TOL=APPROX. ONE PRECISION GREATER THAN */ /* THE UNDERFLOW LIMIT */ /* ----------------------------------------------------------------------- */ cscl = 1. / *tol; crsc = *tol; cssr[0] = cscl; cssr[1] = coner; cssr[2] = crsc; csrr[0] = crsc; csrr[1] = coner; csrr[2] = cscl; bry[0] = d1mach_(&c__1) * 1e3 / *tol; bry[1] = 1. / bry[0]; bry[2] = d1mach_(&c__2); zrr = *zr; zri = *zi; if(*zr >= 0.) { goto L10; } zrr = -(*zr); zri = -(*zi); L10: yy = zri; znr = zri; zni = -zrr; zbr = zrr; zbi = zri; inu = (int32)((float)(*fnu)); fnf = *fnu - (double)((float)inu); ang = -hpi * fnf; car = cos(ang); sar = sin(ang); c2r = hpi * sar; c2i = -hpi * car; kk = inu % 4 + 1; str = c2r * cipr[kk - 1] - c2i * cipi[kk - 1]; sti = c2r * cipi[kk - 1] + c2i * cipr[kk - 1]; csr = cr1r * str - cr1i * sti; csi = cr1r * sti + cr1i * str; if(yy > 0.) { goto L20; } znr = -znr; zbi = -zbi; L20: /* ----------------------------------------------------------------------- */ /* K(FNU,Z) IS COMPUTED FROM H(2,FNU,-I*Z) WHERE Z IS IN THE FIRST */ /* QUADRANT. FOURTH QUADRANT VALUES (YY.LE.0.0E0) ARE COMPUTED BY */ /* CONJUGATION SINCE THE K FUNCTION IS REAL ON THE POSITIVE REAL AXIS */ /* ----------------------------------------------------------------------- */ j = 2; i__1 = *n; for(i__ = 1; i__ <= i__1; ++i__) { /* ----------------------------------------------------------------------- */ /* J FLIP FLOPS BETWEEN 1 AND 2 IN J = 3 - J */ /* ----------------------------------------------------------------------- */ j = 3 - j; fn = *fnu + (double)((float)(i__ - 1)); zunhj_(&znr, &zni, &fn, &c__0, tol, &phir[j - 1], &phii[j - 1], &argr[j - 1], &argi[j - 1], &zeta1r[j - 1], &zeta1i[j - 1], &zeta2r[j - 1], &zeta2i[j - 1], &asumr[j - 1], &asumi[j - 1], &bsumr[j - 1], &bsumi[j - 1]); if(*kode == 1) { goto L30; } str = zbr + zeta2r[j - 1]; sti = zbi + zeta2i[j - 1]; rast = fn / zabs_(&str, &sti); str = str * rast * rast; sti = -sti * rast * rast; s1r = zeta1r[j - 1] - str; s1i = zeta1i[j - 1] - sti; goto L40; L30: s1r = zeta1r[j - 1] - zeta2r[j - 1]; s1i = zeta1i[j - 1] - zeta2i[j - 1]; L40: /* ----------------------------------------------------------------------- */ /* TEST FOR UNDERFLOW AND OVERFLOW */ /* ----------------------------------------------------------------------- */ rs1 = s1r; if(abs(rs1) > *elim) { goto L70; } if(kdflg == 1) { kflag = 2; } if(abs(rs1) < *alim) { goto L50; } /* ----------------------------------------------------------------------- */ /* REFINE TEST AND SCALE */ /* ----------------------------------------------------------------------- */ aphi = zabs_(&phir[j - 1], &phii[j - 1]); aarg = zabs_(&argr[j - 1], &argi[j - 1]); rs1 = rs1 + log(aphi) - log(aarg) * .25 - aic; if(abs(rs1) > *elim) { goto L70; } if(kdflg == 1) { kflag = 1; } if(rs1 < 0.) { goto L50; } if(kdflg == 1) { kflag = 3; } L50: /* ----------------------------------------------------------------------- */ /* SCALE S1 TO KEEP INTERMEDIATE ARITHMETIC ON SCALE NEAR */ /* EXPONENT EXTREMES */ /* ----------------------------------------------------------------------- */ c2r = argr[j - 1] * cr2r - argi[j - 1] * cr2i; c2i = argr[j - 1] * cr2i + argi[j - 1] * cr2r; zairy_(&c2r, &c2i, &c__0, &c__2, &air, &aii, &nai, &idum); zairy_(&c2r, &c2i, &c__1, &c__2, &dair, &daii, &ndai, &idum); str = dair * bsumr[j - 1] - daii * bsumi[j - 1]; sti = dair * bsumi[j - 1] + daii * bsumr[j - 1]; ptr = str * cr2r - sti * cr2i; pti = str * cr2i + sti * cr2r; str = ptr + (air * asumr[j - 1] - aii * asumi[j - 1]); sti = pti + (air * asumi[j - 1] + aii * asumr[j - 1]); ptr = str * phir[j - 1] - sti * phii[j - 1]; pti = str * phii[j - 1] + sti * phir[j - 1]; s2r = ptr * csr - pti * csi; s2i = ptr * csi + pti * csr; str = exp(s1r) * cssr[kflag - 1]; s1r = str * cos(s1i); s1i = str * sin(s1i); str = s2r * s1r - s2i * s1i; s2i = s1r * s2i + s2r * s1i; s2r = str; if(kflag != 1) { goto L60; } zuchk_(&s2r, &s2i, &nw, bry, tol); if(nw != 0) { goto L70; } L60: if(yy <= 0.) { s2i = -s2i; } cyr[kdflg - 1] = s2r; cyi[kdflg - 1] = s2i; yr[i__] = s2r * csrr[kflag - 1]; yi[i__] = s2i * csrr[kflag - 1]; str = csi; csi = -csr; csr = str; if(kdflg == 2) { goto L85; } kdflg = 2; goto L80; L70: if(rs1 > 0.) { goto L320; } /* ----------------------------------------------------------------------- */ /* FOR ZR.LT.0.0, THE I FUNCTION TO BE ADDED WILL OVERFLOW */ /* ----------------------------------------------------------------------- */ if(*zr < 0.) { goto L320; } kdflg = 1; yr[i__] = zeror; yi[i__] = zeroi; ++(*nz); str = csi; csi = -csr; csr = str; if(i__ == 1) { goto L80; } if(yr[i__ - 1] == zeror && yi[i__ - 1] == zeroi) { goto L80; } yr[i__ - 1] = zeror; yi[i__ - 1] = zeroi; ++(*nz); L80:; } i__ = *n; L85: razr = 1. / zabs_(&zrr, &zri); str = zrr * razr; sti = -zri * razr; rzr = (str + str) * razr; rzi = (sti + sti) * razr; ckr = fn * rzr; cki = fn * rzi; ib = i__ + 1; if(*n < ib) { goto L180; } /* ----------------------------------------------------------------------- */ /* TEST LAST MEMBER FOR UNDERFLOW AND OVERFLOW. SET SEQUENCE TO ZERO */ /* ON UNDERFLOW. */ /* ----------------------------------------------------------------------- */ fn = *fnu + (double)((float)(*n - 1)); ipard = 1; if(*mr != 0) { ipard = 0; } zunhj_(&znr, &zni, &fn, &ipard, tol, &phidr, &phidi, &argdr, &argdi, &zet1dr, &zet1di, &zet2dr, &zet2di, &asumdr, &asumdi, &bsumdr, &bsumdi); if(*kode == 1) { goto L90; } str = zbr + zet2dr; sti = zbi + zet2di; rast = fn / zabs_(&str, &sti); str = str * rast * rast; sti = -sti * rast * rast; s1r = zet1dr - str; s1i = zet1di - sti; goto L100; L90: s1r = zet1dr - zet2dr; s1i = zet1di - zet2di; L100: rs1 = s1r; if(abs(rs1) > *elim) { goto L105; } if(abs(rs1) < *alim) { goto L120; } /* ---------------------------------------------------------------------------- */ /* REFINE ESTIMATE AND TEST */ /* ------------------------------------------------------------------------- */ aphi = zabs_(&phidr, &phidi); rs1 += log(aphi); if(abs(rs1) < *elim) { goto L120; } L105: if(rs1 > 0.) { goto L320; } /* ----------------------------------------------------------------------- */ /* FOR ZR.LT.0.0, THE I FUNCTION TO BE ADDED WILL OVERFLOW */ /* ----------------------------------------------------------------------- */ if(*zr < 0.) { goto L320; } *nz = *n; i__1 = *n; for(i__ = 1; i__ <= i__1; ++i__) { yr[i__] = zeror; yi[i__] = zeroi; /* L106: */ } return 0; L120: s1r = cyr[0]; s1i = cyi[0]; s2r = cyr[1]; s2i = cyi[1]; c1r = csrr[kflag - 1]; ascle = bry[kflag - 1]; i__1 = *n; for(i__ = ib; i__ <= i__1; ++i__) { c2r = s2r; c2i = s2i; s2r = ckr * c2r - cki * c2i + s1r; s2i = ckr * c2i + cki * c2r + s1i; s1r = c2r; s1i = c2i; ckr += rzr; cki += rzi; c2r = s2r * c1r; c2i = s2i * c1r; yr[i__] = c2r; yi[i__] = c2i; if(kflag >= 3) { goto L130; } str = abs(c2r); sti = abs(c2i); c2m = max(str, sti); if(c2m <= ascle) { goto L130; } ++kflag; ascle = bry[kflag - 1]; s1r *= c1r; s1i *= c1r; s2r = c2r; s2i = c2i; s1r *= cssr[kflag - 1]; s1i *= cssr[kflag - 1]; s2r *= cssr[kflag - 1]; s2i *= cssr[kflag - 1]; c1r = csrr[kflag - 1]; L130:; } L180: if(*mr == 0) { return 0; } /* ----------------------------------------------------------------------- */ /* ANALYTIC CONTINUATION FOR RE(Z).LT.0.0D0 */ /* ----------------------------------------------------------------------- */ *nz = 0; fmr = (double)((float)(*mr)); sgn = -d_sign(&pi, &fmr); /* ----------------------------------------------------------------------- */ /* CSPN AND CSGN ARE COEFF OF K AND I FUNCIONS RESP. */ /* ----------------------------------------------------------------------- */ csgni = sgn; if(yy <= 0.) { csgni = -csgni; } ifn = inu + *n - 1; ang = fnf * sgn; cspnr = cos(ang); cspni = sin(ang); if(ifn % 2 == 0) { goto L190; } cspnr = -cspnr; cspni = -cspni; L190: /* ----------------------------------------------------------------------- */ /* CS=COEFF OF THE J FUNCTION TO GET THE I FUNCTION. I(FNU,Z) IS */ /* COMPUTED FROM EXP(I*FNU*HPI)*J(FNU,-I*Z) WHERE Z IS IN THE FIRST */ /* QUADRANT. FOURTH QUADRANT VALUES (YY.LE.0.0E0) ARE COMPUTED BY */ /* CONJUGATION SINCE THE I FUNCTION IS REAL ON THE POSITIVE REAL AXIS */ /* ----------------------------------------------------------------------- */ csr = sar * csgni; csi = car * csgni; in = ifn % 4 + 1; c2r = cipr[in - 1]; c2i = cipi[in - 1]; str = csr * c2r + csi * c2i; csi = -csr * c2i + csi * c2r; csr = str; asc = bry[0]; iuf = 0; kk = *n; kdflg = 1; --ib; ic = ib - 1; i__1 = *n; for(k = 1; k <= i__1; ++k) { fn = *fnu + (double)((float)(kk - 1)); /* ----------------------------------------------------------------------- */ /* LOGIC TO SORT OUT CASES WHOSE PARAMETERS WERE SET FOR THE K */ /* FUNCTION ABOVE */ /* ----------------------------------------------------------------------- */ if(*n > 2) { goto L175; } L172: phidr = phir[j - 1]; phidi = phii[j - 1]; argdr = argr[j - 1]; argdi = argi[j - 1]; zet1dr = zeta1r[j - 1]; zet1di = zeta1i[j - 1]; zet2dr = zeta2r[j - 1]; zet2di = zeta2i[j - 1]; asumdr = asumr[j - 1]; asumdi = asumi[j - 1]; bsumdr = bsumr[j - 1]; bsumdi = bsumi[j - 1]; j = 3 - j; goto L210; L175: if(kk == *n && ib < *n) { goto L210; } if(kk == ib || kk == ic) { goto L172; } zunhj_(&znr, &zni, &fn, &c__0, tol, &phidr, &phidi, &argdr, &argdi, &zet1dr, &zet1di, &zet2dr, &zet2di, &asumdr, &asumdi, &bsumdr, &bsumdi); L210: if(*kode == 1) { goto L220; } str = zbr + zet2dr; sti = zbi + zet2di; rast = fn / zabs_(&str, &sti); str = str * rast * rast; sti = -sti * rast * rast; s1r = -zet1dr + str; s1i = -zet1di + sti; goto L230; L220: s1r = -zet1dr + zet2dr; s1i = -zet1di + zet2di; L230: /* ----------------------------------------------------------------------- */ /* TEST FOR UNDERFLOW AND OVERFLOW */ /* ----------------------------------------------------------------------- */ rs1 = s1r; if(abs(rs1) > *elim) { goto L280; } if(kdflg == 1) { iflag = 2; } if(abs(rs1) < *alim) { goto L240; } /* ----------------------------------------------------------------------- */ /* REFINE TEST AND SCALE */ /* ----------------------------------------------------------------------- */ aphi = zabs_(&phidr, &phidi); aarg = zabs_(&argdr, &argdi); rs1 = rs1 + log(aphi) - log(aarg) * .25 - aic; if(abs(rs1) > *elim) { goto L280; } if(kdflg == 1) { iflag = 1; } if(rs1 < 0.) { goto L240; } if(kdflg == 1) { iflag = 3; } L240: zairy_(&argdr, &argdi, &c__0, &c__2, &air, &aii, &nai, &idum); zairy_(&argdr, &argdi, &c__1, &c__2, &dair, &daii, &ndai, &idum); str = dair * bsumdr - daii * bsumdi; sti = dair * bsumdi + daii * bsumdr; str += air * asumdr - aii * asumdi; sti += air * asumdi + aii * asumdr; ptr = str * phidr - sti * phidi; pti = str * phidi + sti * phidr; s2r = ptr * csr - pti * csi; s2i = ptr * csi + pti * csr; str = exp(s1r) * cssr[iflag - 1]; s1r = str * cos(s1i); s1i = str * sin(s1i); str = s2r * s1r - s2i * s1i; s2i = s2r * s1i + s2i * s1r; s2r = str; if(iflag != 1) { goto L250; } zuchk_(&s2r, &s2i, &nw, bry, tol); if(nw == 0) { goto L250; } s2r = zeror; s2i = zeroi; L250: if(yy <= 0.) { s2i = -s2i; } cyr[kdflg - 1] = s2r; cyi[kdflg - 1] = s2i; c2r = s2r; c2i = s2i; s2r *= csrr[iflag - 1]; s2i *= csrr[iflag - 1]; /* ----------------------------------------------------------------------- */ /* ADD I AND K FUNCTIONS, K SEQUENCE IN Y(I), I=1,N */ /* ----------------------------------------------------------------------- */ s1r = yr[kk]; s1i = yi[kk]; if(*kode == 1) { goto L270; } zs1s2_(&zrr, &zri, &s1r, &s1i, &s2r, &s2i, &nw, &asc, alim, &iuf); *nz += nw; L270: yr[kk] = s1r * cspnr - s1i * cspni + s2r; yi[kk] = s1r * cspni + s1i * cspnr + s2i; --kk; cspnr = -cspnr; cspni = -cspni; str = csi; csi = -csr; csr = str; if(c2r != 0. || c2i != 0.) { goto L255; } kdflg = 1; goto L290; L255: if(kdflg == 2) { goto L295; } kdflg = 2; goto L290; L280: if(rs1 > 0.) { goto L320; } s2r = zeror; s2i = zeroi; goto L250; L290:; } k = *n; L295: il = *n - k; if(il == 0) { return 0; } /* ----------------------------------------------------------------------- */ /* RECUR BACKWARD FOR REMAINDER OF I SEQUENCE AND ADD IN THE */ /* K FUNCTIONS, SCALING THE I SEQUENCE DURING RECURRENCE TO KEEP */ /* INTERMEDIATE ARITHMETIC ON SCALE NEAR EXPONENT EXTREMES. */ /* ----------------------------------------------------------------------- */ s1r = cyr[0]; s1i = cyi[0]; s2r = cyr[1]; s2i = cyi[1]; csr = csrr[iflag - 1]; ascle = bry[iflag - 1]; fn = (double)((float)(inu + il)); i__1 = il; for(i__ = 1; i__ <= i__1; ++i__) { c2r = s2r; c2i = s2i; s2r = s1r + (fn + fnf) * (rzr * c2r - rzi * c2i); s2i = s1i + (fn + fnf) * (rzr * c2i + rzi * c2r); s1r = c2r; s1i = c2i; fn += -1.; c2r = s2r * csr; c2i = s2i * csr; ckr = c2r; cki = c2i; c1r = yr[kk]; c1i = yi[kk]; if(*kode == 1) { goto L300; } zs1s2_(&zrr, &zri, &c1r, &c1i, &c2r, &c2i, &nw, &asc, alim, &iuf); *nz += nw; L300: yr[kk] = c1r * cspnr - c1i * cspni + c2r; yi[kk] = c1r * cspni + c1i * cspnr + c2i; --kk; cspnr = -cspnr; cspni = -cspni; if(iflag >= 3) { goto L310; } c2r = abs(ckr); c2i = abs(cki); c2m = max(c2r, c2i); if(c2m <= ascle) { goto L310; } ++iflag; ascle = bry[iflag - 1]; s1r *= csr; s1i *= csr; s2r = ckr; s2i = cki; s1r *= cssr[iflag - 1]; s1i *= cssr[iflag - 1]; s2r *= cssr[iflag - 1]; s2i *= cssr[iflag - 1]; csr = csrr[iflag - 1]; L310:; } return 0; L320: *nz = -1; return 0; } /* zunk2_ */ int zuoik_(double* zr, double* zi, double* fnu, int32* kode, int32* ikflg, int32* n, double* yr, double* yi, int32* nuf, double* tol, double* elim, double* alim) { /* Initialized data */ static double zeror = 0.; static double zeroi = 0.; static double aic = 1.265512123484645396; /* System generated locals */ int32 i__1; int32 i__; double ax, ay; int32 nn, nw; double fnn, gnn, zbi, czi, gnu, zbr, czr, rcz, sti, zni, zri, str, znr, zrr, aarg, aphi, argi, phii, argr; int32 idum; double phir; int32 init; double sumi, sumr, ascle; int32 iform; double asumi, bsumi, cwrki[16]; double asumr, bsumr, cwrkr[16]; double zeta1i, zeta2i, zeta1r, zeta2r; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE ZUOIK */ /* ***REFER TO ZBESI,ZBESK,ZBESH */ /* ZUOIK COMPUTES THE LEADING TERMS OF THE UNIFORM ASYMPTOTIC */ /* EXPANSIONS FOR THE I AND K FUNCTIONS AND COMPARES THEM */ /* (IN LOGARITHMIC FORM) TO ALIM AND ELIM FOR OVER AND UNDERFLOW */ /* WHERE ALIM.LT.ELIM. IF THE MAGNITUDE, BASED ON THE LEADING */ /* EXPONENTIAL, IS LESS THAN ALIM OR GREATER THAN -ALIM, THEN */ /* THE RESULT IS ON SCALE. IF NOT, THEN A REFINED TEST USING OTHER */ /* MULTIPLIERS (IN LOGARITHMIC FORM) IS MADE BASED ON ELIM. HERE */ /* EXP(-ELIM)=SMALLEST MACHINE NUMBER*1.0E+3 AND EXP(-ALIM)= */ /* EXP(-ELIM)/TOL */ /* IKFLG=1 MEANS THE I SEQUENCE IS TESTED */ /* =2 MEANS THE K SEQUENCE IS TESTED */ /* NUF = 0 MEANS THE LAST MEMBER OF THE SEQUENCE IS ON SCALE */ /* =-1 MEANS AN OVERFLOW WOULD OCCUR */ /* IKFLG=1 AND NUF.GT.0 MEANS THE LAST NUF Y VALUES WERE SET TO ZERO */ /* THE FIRST N-NUF VALUES MUST BE SET BY ANOTHER ROUTINE */ /* IKFLG=2 AND NUF.EQ.N MEANS ALL Y VALUES WERE SET TO ZERO */ /* IKFLG=2 AND 0.LT.NUF.LT.N NOT CONSIDERED. Y MUST BE SET BY */ /* ANOTHER ROUTINE */ /* ***ROUTINES CALLED ZUCHK,ZUNHJ,ZUNIK,D1MACH,ZABS,ZLOG */ /* ***END PROLOGUE ZUOIK */ /* COMPLEX ARG,ASUM,BSUM,CWRK,CZ,CZERO,PHI,SUM,Y,Z,ZB,ZETA1,ZETA2,ZN, */ /* *ZR */ /* Parameter adjustments */ --yi; --yr; /* Function Body */ *nuf = 0; nn = *n; zrr = *zr; zri = *zi; if(*zr >= 0.) { goto L10; } zrr = -(*zr); zri = -(*zi); L10: zbr = zrr; zbi = zri; ax = abs(*zr) * 1.7321; ay = abs(*zi); iform = 1; if(ay > ax) { iform = 2; } gnu = max(*fnu, 1.); if(*ikflg == 1) { goto L20; } fnn = (double)((float)nn); gnn = *fnu + fnn - 1.; gnu = max(gnn, fnn); L20: /* ----------------------------------------------------------------------- */ /* ONLY THE MAGNITUDE OF ARG AND PHI ARE NEEDED ALONG WITH THE */ /* REAL PARTS OF ZETA1, ZETA2 AND ZB. NO ATTEMPT IS MADE TO GET */ /* THE SIGN OF THE IMAGINARY PART CORRECT. */ /* ----------------------------------------------------------------------- */ if(iform == 2) { goto L30; } init = 0; zunik_(&zrr, &zri, &gnu, ikflg, &c__1, tol, &init, &phir, &phii, &zeta1r, &zeta1i, &zeta2r, &zeta2i, &sumr, &sumi, cwrkr, cwrki); czr = -zeta1r + zeta2r; czi = -zeta1i + zeta2i; goto L50; L30: znr = zri; zni = -zrr; if(*zi > 0.) { goto L40; } znr = -znr; L40: zunhj_(&znr, &zni, &gnu, &c__1, tol, &phir, &phii, &argr, &argi, &zeta1r, &zeta1i, &zeta2r, &zeta2i, &asumr, &asumi, &bsumr, &bsumi); czr = -zeta1r + zeta2r; czi = -zeta1i + zeta2i; aarg = zabs_(&argr, &argi); L50: if(*kode == 1) { goto L60; } czr -= zbr; czi -= zbi; L60: if(*ikflg == 1) { goto L70; } czr = -czr; czi = -czi; L70: aphi = zabs_(&phir, &phii); rcz = czr; /* ----------------------------------------------------------------------- */ /* OVERFLOW TEST */ /* ----------------------------------------------------------------------- */ if(rcz > *elim) { goto L210; } if(rcz < *alim) { goto L80; } rcz += log(aphi); if(iform == 2) { rcz = rcz - log(aarg) * .25 - aic; } if(rcz > *elim) { goto L210; } goto L130; L80: /* ----------------------------------------------------------------------- */ /* UNDERFLOW TEST */ /* ----------------------------------------------------------------------- */ if(rcz < -(*elim)) { goto L90; } if(rcz > -(*alim)) { goto L130; } rcz += log(aphi); if(iform == 2) { rcz = rcz - log(aarg) * .25 - aic; } if(rcz > -(*elim)) { goto L110; } L90: i__1 = nn; for(i__ = 1; i__ <= i__1; ++i__) { yr[i__] = zeror; yi[i__] = zeroi; /* L100: */ } *nuf = nn; return 0; L110: ascle = d1mach_(&c__1) * 1e3 / *tol; zlog_(&phir, &phii, &str, &sti, &idum); czr += str; czi += sti; if(iform == 1) { goto L120; } zlog_(&argr, &argi, &str, &sti, &idum); czr = czr - str * .25 - aic; czi -= sti * .25; L120: ax = exp(rcz) / *tol; ay = czi; czr = ax * cos(ay); czi = ax * sin(ay); zuchk_(&czr, &czi, &nw, &ascle, tol); if(nw != 0) { goto L90; } L130: if(*ikflg == 2) { return 0; } if(*n == 1) { return 0; } /* ----------------------------------------------------------------------- */ /* SET UNDERFLOWS ON I SEQUENCE */ /* ----------------------------------------------------------------------- */ L140: gnu = *fnu + (double)((float)(nn - 1)); if(iform == 2) { goto L150; } init = 0; zunik_(&zrr, &zri, &gnu, ikflg, &c__1, tol, &init, &phir, &phii, &zeta1r, &zeta1i, &zeta2r, &zeta2i, &sumr, &sumi, cwrkr, cwrki); czr = -zeta1r + zeta2r; czi = -zeta1i + zeta2i; goto L160; L150: zunhj_(&znr, &zni, &gnu, &c__1, tol, &phir, &phii, &argr, &argi, &zeta1r, &zeta1i, &zeta2r, &zeta2i, &asumr, &asumi, &bsumr, &bsumi); czr = -zeta1r + zeta2r; czi = -zeta1i + zeta2i; aarg = zabs_(&argr, &argi); L160: if(*kode == 1) { goto L170; } czr -= zbr; czi -= zbi; L170: aphi = zabs_(&phir, &phii); rcz = czr; if(rcz < -(*elim)) { goto L180; } if(rcz > -(*alim)) { return 0; } rcz += log(aphi); if(iform == 2) { rcz = rcz - log(aarg) * .25 - aic; } if(rcz > -(*elim)) { goto L190; } L180: yr[nn] = zeror; yi[nn] = zeroi; --nn; ++(*nuf); if(nn == 0) { return 0; } goto L140; L190: ascle = d1mach_(&c__1) * 1e3 / *tol; zlog_(&phir, &phii, &str, &sti, &idum); czr += str; czi += sti; if(iform == 1) { goto L200; } zlog_(&argr, &argi, &str, &sti, &idum); czr = czr - str * .25 - aic; czi -= sti * .25; L200: ax = exp(rcz) / *tol; ay = czi; czr = ax * cos(ay); czi = ax * sin(ay); zuchk_(&czr, &czi, &nw, &ascle, tol); if(nw != 0) { goto L180; } return 0; L210: *nuf = -1; return 0; } /* zuoik_ */ int zwrsk_(double* zrr, double* zri, double* fnu, int32* kode, int32* n, double* yr, double* yi, int32* nz, double* cwr, double* cwi, double* tol, double* elim, double* alim) { /* System generated locals */ int32 i__1; int32 i__, nw; double c1i, c2i, c1r, c2r, act, acw, cti, ctr, pti, sti, ptr, str, ract; double ascle, csclr, cinui, cinur; /* *********************************************************************72 */ /* ***BEGIN PROLOGUE ZWRSK */ /* ***REFER TO ZBESI,ZBESK */ /* ZWRSK COMPUTES THE I BESSEL FUNCTION FOR RE(Z).GE.0.0 BY */ /* NORMALIZING THE I FUNCTION RATIOS FROM ZRATI BY THE WRONSKIAN */ /* ***ROUTINES CALLED D1MACH,ZBKNU,ZRATI,ZABS */ /* ***END PROLOGUE ZWRSK */ /* COMPLEX CINU,CSCL,CT,CW,C1,C2,RCT,ST,Y,ZR */ /* ----------------------------------------------------------------------- */ /* I(FNU+I-1,Z) BY BACKWARD RECURRENCE FOR RATIOS */ /* Y(I)=I(FNU+I,Z)/I(FNU+I-1,Z) FROM CRATI NORMALIZED BY THE */ /* WRONSKIAN WITH K(FNU,Z) AND K(FNU+1,Z) FROM CBKNU. */ /* ----------------------------------------------------------------------- */ /* Parameter adjustments */ --yi; --yr; --cwr; --cwi; /* Function Body */ *nz = 0; zbknu_(zrr, zri, fnu, kode, &c__2, &cwr[1], &cwi[1], &nw, tol, elim, alim); if(nw != 0) { goto L50; } zrati_(zrr, zri, fnu, n, &yr[1], &yi[1], tol); /* ----------------------------------------------------------------------- */ /* RECUR FORWARD ON I(FNU+1,Z) = R(FNU,Z)*I(FNU,Z), */ /* R(FNU+J-1,Z)=Y(J), J=1,...,N */ /* ----------------------------------------------------------------------- */ cinur = 1.; cinui = 0.; if(*kode == 1) { goto L10; } cinur = cos(*zri); cinui = sin(*zri); L10: /* ----------------------------------------------------------------------- */ /* ON LOW EXPONENT MACHINES THE K FUNCTIONS CAN BE CLOSE TO BOTH */ /* THE UNDER AND OVERFLOW LIMITS AND THE NORMALIZATION MUST BE */ /* SCALED TO PREVENT OVER OR UNDERFLOW. CUOIK HAS DETERMINED THAT */ /* THE RESULT IS ON SCALE. */ /* ----------------------------------------------------------------------- */ acw = zabs_(&cwr[2], &cwi[2]); ascle = d1mach_(&c__1) * 1e3 / *tol; csclr = 1.; if(acw > ascle) { goto L20; } csclr = 1. / *tol; goto L30; L20: ascle = 1. / ascle; if(acw < ascle) { goto L30; } csclr = *tol; L30: c1r = cwr[1] * csclr; c1i = cwi[1] * csclr; c2r = cwr[2] * csclr; c2i = cwi[2] * csclr; str = yr[1]; sti = yi[1]; /* ----------------------------------------------------------------------- */ /* CINU=CINU*(CONJG(CT)/CABS(CT))*(1.0D0/CABS(CT) PREVENTS */ /* UNDER- OR OVERFLOW PREMATURELY BY SQUARING CABS(CT) */ /* ----------------------------------------------------------------------- */ ptr = str * c1r - sti * c1i; pti = str * c1i + sti * c1r; ptr += c2r; pti += c2i; ctr = *zrr * ptr - *zri * pti; cti = *zrr * pti + *zri * ptr; act = zabs_(&ctr, &cti); ract = 1. / act; ctr *= ract; cti = -cti * ract; ptr = cinur * ract; pti = cinui * ract; cinur = ptr * ctr - pti * cti; cinui = ptr * cti + pti * ctr; yr[1] = cinur * csclr; yi[1] = cinui * csclr; if(*n == 1) { return 0; } i__1 = *n; for(i__ = 2; i__ <= i__1; ++i__) { ptr = str * cinur - sti * cinui; cinui = str * cinui + sti * cinur; cinur = ptr; str = yr[i__]; sti = yi[i__]; yr[i__] = cinur * csclr; yi[i__] = cinui * csclr; /* L40: */ } return 0; L50: *nz = -1; if(nw == -2) { *nz = -2; } return 0; } /* zwrsk_ */
36.627257
258
0.427556
trmcnealy
4f9559843067ede1a3b32ca819d485ada6c6a072
184
cpp
C++
Chapter12/Source/Chapter12/Chapter12.cpp
xiaomozi/Unreal-Engine-4-Scripting-with-CPlusPlus-Cookbook
b17ea5de947f018b5c34f1621ce2785d6236c3a4
[ "MIT" ]
115
2016-10-27T15:46:35.000Z
2022-03-28T02:00:31.000Z
Chapter12/Source/Chapter12/Chapter12.cpp
xiaomozi/Unreal-Engine-4-Scripting-with-CPlusPlus-Cookbook
b17ea5de947f018b5c34f1621ce2785d6236c3a4
[ "MIT" ]
3
2016-11-06T06:45:42.000Z
2021-03-20T01:06:39.000Z
Chapter12/Source/Chapter12/Chapter12.cpp
xiaomozi/Unreal-Engine-4-Scripting-with-CPlusPlus-Cookbook
b17ea5de947f018b5c34f1621ce2785d6236c3a4
[ "MIT" ]
60
2016-12-08T18:16:43.000Z
2022-02-26T05:44:57.000Z
// Fill out your copyright notice in the Description page of Project Settings. #include "Chapter12.h" IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, Chapter12, "Chapter12" );
36.8
80
0.809783
xiaomozi
4f95a67664a448eb0cd5a40c135cae3369e203bc
5,009
inl
C++
src/core/CPU.inl
Senryoku/NESen
7573eddc55da0e140cf01e609b1041b2c6e4e853
[ "MIT" ]
1
2015-10-16T09:15:37.000Z
2015-10-16T09:15:37.000Z
src/core/CPU.inl
Senryoku/NESen
7573eddc55da0e140cf01e609b1041b2c6e4e853
[ "MIT" ]
null
null
null
src/core/CPU.inl
Senryoku/NESen
7573eddc55da0e140cf01e609b1041b2c6e4e853
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////////////////////// // CPU Inline functions word_t CPU::read(addr_t addr) { if(addr < RAMSize) return _ram[addr]; else if(addr < 0x2000) // RAM mirrors return _ram[addr % RAMSize]; else if(addr < 0x2008) // PPU registers return ppu->read(addr); else if(addr < 0x4000) // PPU registers mirrors return ppu->read(addr); else if(addr < 0x4016) // pAPU return apu->read(addr); else if(addr == 0x4016) // Controllers registers return read_controller_state(); else if(addr == 0x4017) // Controllers registers return read_controller2_state(); else if(addr < 0x5000) // Unused return 0; else if(addr < 0x6000) // Expansion return cartridge->read(addr); else if(addr < 0x8000) // SRAM return cartridge->read(addr); else if(addr <= 0xFFFF) // Cartridge return cartridge->read(addr); else { Log::error("Error: Read addr ", Hexa(addr), " out of bounds."); exit(1); } } addr_t CPU::read16(addr_t addr) { return read(addr) | (read(addr + 1) << 8); } void CPU::write(addr_t addr, word_t value) { if(addr < RAMSize) _ram[addr] = value; else if(addr < 0x2000) // RAM mirrors _ram[addr % RAMSize] = value; else if(addr < 0x2008) // PPU registers ppu->write(addr, value); else if(addr == 0x4014) // OAMDMA oam_dma(value); else if(addr < 0x4000) // PPU registers mirrors ppu->write(addr, value); else if(addr == 0x4016) // Controllers registers _refresh_controller = value & 1; else if(addr < 0x4018) // APU registers apu->write(addr - 0x4000, value); else cartridge->write(addr, value); } void CPU::oam_dma(word_t value) { /// @todo Timing: Takes 513 or 514 (if on an odd cycle) Cycles ppu->write(0x2003, 0x00); // Reset OAMADDR addr_t start = (value << 8); for(addr_t a = 0; a < 256; ++a) ppu->write(0x2004, _ram[start + a]); } //////////////////////////////////////////////////////////////////////////////////////////////// // Stack inline void CPU::push(word_t value) { _ram[0x100 + _reg_sp--] = value; } inline void CPU::push16(addr_t value) { push((value & 0xFF00) >> 8); push(value & 0xFF); } inline word_t CPU::pop() { return _ram[0x100 + ++_reg_sp]; } inline addr_t CPU::pop16() { addr_t l = pop(); addr_t h = pop(); return (h << 8) | l; } //////////////////////////////////////////////////////////////////////////////////////////////// // Processor Status Flags // @todo Use an other form of storage until status is queried ? enum StateMask : uint8_t { Carry = 0b00000001, Zero = 0b00000010, Interrupt = 0b00000100, ///< Interrupt Disable (NMI) Decimal = 0b00001000, ///< Decimal Mode (Unused) Break = 0b00010000, ///< Break Command Overflow = 0b01000000, Negative = 0b10000000 }; inline bool CPU::check(StateMask mask) { return (_reg_ps & mask); } inline void CPU::set(StateMask mask) { _reg_ps |= mask; } inline void CPU::clear(StateMask mask) { _reg_ps &= ~mask; } inline void CPU::set(StateMask mask, bool b) { b ? set(mask) : clear(mask); } /// Clears the Negative Flag if the operand is $#00-7F, otherwise sets it. inline void CPU::set_neg(word_t operand) { set(StateMask::Negative, operand & 0b10000000); } /// Sets the Zero Flag if the operand is $#00, otherwise clears it. inline void CPU::set_zero(word_t operand) { set(StateMask::Zero, operand == 0); } inline void CPU::set_neg_zero(word_t operand) { set_neg(operand); set_zero(operand); } //////////////////////////////////////////////////////////////////////////////////////////////// // Addressing modes inline addr_t CPU::addr_immediate() { auto r = _reg_pc; ++_reg_pc; return r; } inline addr_t CPU::addr_abs() { addr_t r = read16(_reg_pc); _reg_pc += 2; return r; } inline addr_t CPU::addr_absX() { addr_t r = read16(_reg_pc) + _reg_x; _reg_pc += 2; return r; } inline addr_t CPU::addr_absY() { addr_t r = read16(_reg_pc) + _reg_y; _reg_pc += 2; return r; } inline addr_t CPU::addr_zero() { addr_t r = read(_reg_pc); ++_reg_pc; return r & 0xFF; } inline addr_t CPU::addr_zeroX() { addr_t r = (read(_reg_pc) + _reg_x) & 0xFF; ++_reg_pc; return r; } inline addr_t CPU::addr_zeroY() { addr_t r = (read(_reg_pc) + _reg_y) & 0xFF; ++_reg_pc; return r; } inline addr_t CPU::addr_indirect() { addr_t l = read(_reg_pc); addr_t h = read((_reg_pc + 1) & 0xFFFF); ++_reg_pc; ++_reg_pc; addr_t tmp = (l | (h << 8)); // This addressing mode is bugged on the actual hardware! // Here! \/ return read(tmp) + ((read((((l + 1) & 0xFF) | (h << 8))) & 0xFF) << 8); // 'Correct' version: // return read(tmp) + ((read(tmp + 1) & 0xFF) << 8); } inline addr_t CPU::addr_indirectX() { addr_t tmp = read(_reg_pc); addr_t l = read((_reg_x + tmp) & 0xFF); addr_t h = read((_reg_x + tmp + 1) & 0xFF); ++_reg_pc; return (l | (h << 8)); } inline addr_t CPU::addr_indirectY() { addr_t tmp = read(_reg_pc); addr_t l = read(tmp); addr_t h = read((tmp + 1) & 0xFF); ++_reg_pc; return ((l | (h << 8)) + _reg_y) & 0xFFFF; }
21.778261
96
0.597924
Senryoku
4f96e70aa9041c16e9de823d8fa07141e39b3023
26,870
cpp
C++
interface/src/ui/overlays/Web3DOverlay.cpp
cain-kilgore/hifi
51bf3c1466f4e7fe783a81baae4dd96912560c92
[ "Apache-2.0" ]
null
null
null
interface/src/ui/overlays/Web3DOverlay.cpp
cain-kilgore/hifi
51bf3c1466f4e7fe783a81baae4dd96912560c92
[ "Apache-2.0" ]
null
null
null
interface/src/ui/overlays/Web3DOverlay.cpp
cain-kilgore/hifi
51bf3c1466f4e7fe783a81baae4dd96912560c92
[ "Apache-2.0" ]
null
null
null
// // Web3DOverlay.cpp // // Created by Clement on 7/1/14. // Modified and renamed by Zander Otavka on 8/4/15 // Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "Web3DOverlay.h" #include <Application.h> #include <QQuickWindow> #include <QtGui/QOpenGLContext> #include <QtQuick/QQuickItem> #include <QtQml/QQmlContext> #include <QtQml/QQmlEngine> #include <AbstractViewStateInterface.h> #include <gpu/Batch.h> #include <DependencyManager.h> #include <GeometryCache.h> #include <GeometryUtil.h> #include <gl/GLHelpers.h> #include <scripting/HMDScriptingInterface.h> #include <ui/OffscreenQmlSurface.h> #include <ui/OffscreenQmlSurfaceCache.h> #include <ui/TabletScriptingInterface.h> #include <PathUtils.h> #include <RegisteredMetaTypes.h> #include <TextureCache.h> #include <UsersScriptingInterface.h> #include <UserActivityLoggerScriptingInterface.h> #include <AbstractViewStateInterface.h> #include <AddressManager.h> #include "scripting/HMDScriptingInterface.h" #include "scripting/AssetMappingsScriptingInterface.h" #include "scripting/MenuScriptingInterface.h" #include "scripting/SettingsScriptingInterface.h" #include <Preferences.h> #include <ScriptEngines.h> #include "FileDialogHelper.h" #include "avatar/AvatarManager.h" #include "AudioClient.h" #include "LODManager.h" #include "ui/OctreeStatsProvider.h" #include "ui/DomainConnectionModel.h" #include "ui/AvatarInputs.h" #include "avatar/AvatarManager.h" #include "scripting/AccountServicesScriptingInterface.h" #include <plugins/InputConfiguration.h> #include "ui/Snapshot.h" #include "SoundCache.h" #include "raypick/PointerScriptingInterface.h" static int MAX_WINDOW_SIZE = 4096; static const float METERS_TO_INCHES = 39.3701f; static const float OPAQUE_ALPHA_THRESHOLD = 0.99f; const QString Web3DOverlay::TYPE = "web3d"; const QString Web3DOverlay::QML = "Web3DOverlay.qml"; Web3DOverlay::Web3DOverlay() { _touchDevice.setCapabilities(QTouchDevice::Position); _touchDevice.setType(QTouchDevice::TouchScreen); _touchDevice.setName("Web3DOverlayTouchDevice"); _touchDevice.setMaximumTouchPoints(4); _geometryId = DependencyManager::get<GeometryCache>()->allocateID(); connect(this, &Web3DOverlay::requestWebSurface, this, &Web3DOverlay::buildWebSurface); connect(this, &Web3DOverlay::releaseWebSurface, this, &Web3DOverlay::destroyWebSurface); connect(this, &Web3DOverlay::resizeWebSurface, this, &Web3DOverlay::onResizeWebSurface); //need to be intialized before Tablet 1st open _webSurface = DependencyManager::get<OffscreenQmlSurfaceCache>()->acquire(_url); _webSurface->getSurfaceContext()->setContextProperty("HMD", DependencyManager::get<HMDScriptingInterface>().data()); _webSurface->getSurfaceContext()->setContextProperty("Account", AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED _webSurface->getSurfaceContext()->setContextProperty("GlobalServices", AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED _webSurface->getSurfaceContext()->setContextProperty("AccountServices", AccountServicesScriptingInterface::getInstance()); _webSurface->getSurfaceContext()->setContextProperty("AddressManager", DependencyManager::get<AddressManager>().data()); } Web3DOverlay::Web3DOverlay(const Web3DOverlay* Web3DOverlay) : Billboard3DOverlay(Web3DOverlay), _url(Web3DOverlay->_url), _scriptURL(Web3DOverlay->_scriptURL), _dpi(Web3DOverlay->_dpi), _showKeyboardFocusHighlight(Web3DOverlay->_showKeyboardFocusHighlight) { _geometryId = DependencyManager::get<GeometryCache>()->allocateID(); } Web3DOverlay::~Web3DOverlay() { disconnect(this, &Web3DOverlay::requestWebSurface, this, nullptr); disconnect(this, &Web3DOverlay::releaseWebSurface, this, nullptr); disconnect(this, &Web3DOverlay::resizeWebSurface, this, nullptr); destroyWebSurface(); auto geometryCache = DependencyManager::get<GeometryCache>(); if (geometryCache) { geometryCache->releaseID(_geometryId); } } void Web3DOverlay::rebuildWebSurface() { destroyWebSurface(); buildWebSurface(); } void Web3DOverlay::destroyWebSurface() { if (!_webSurface) { return; } QQuickItem* rootItem = _webSurface->getRootItem(); if (rootItem && rootItem->objectName() == "tabletRoot") { auto tabletScriptingInterface = DependencyManager::get<TabletScriptingInterface>(); tabletScriptingInterface->setQmlTabletRoot("com.highfidelity.interface.tablet.system", nullptr); } // Fix for crash in QtWebEngineCore when rapidly switching domains // Call stop on the QWebEngineView before destroying OffscreenQMLSurface. if (rootItem) { QObject* obj = rootItem->findChild<QObject*>("webEngineView"); if (obj) { // stop loading QMetaObject::invokeMethod(obj, "stop"); } } _webSurface->pause(); QObject::disconnect(this, &Web3DOverlay::scriptEventReceived, _webSurface.data(), &OffscreenQmlSurface::emitScriptEvent); QObject::disconnect(_webSurface.data(), &OffscreenQmlSurface::webEventReceived, this, &Web3DOverlay::webEventReceived); DependencyManager::get<OffscreenQmlSurfaceCache>()->release(QML, _webSurface); _webSurface.reset(); } void Web3DOverlay::buildWebSurface() { if (_webSurface) { return; } gl::withSavedContext([&] { // FIXME, the max FPS could be better managed by being dynamic (based on the number of current surfaces // and the current rendering load) if (_currentMaxFPS != _desiredMaxFPS) { setMaxFPS(_desiredMaxFPS); } if (isWebContent()) { _webSurface = DependencyManager::get<OffscreenQmlSurfaceCache>()->acquire(QML); _webSurface->getRootItem()->setProperty("url", _url); _webSurface->getRootItem()->setProperty("scriptURL", _scriptURL); } else { _webSurface = DependencyManager::get<OffscreenQmlSurfaceCache>()->acquire(_url); setupQmlSurface(); } _webSurface->getSurfaceContext()->setContextProperty("globalPosition", vec3toVariant(getWorldPosition())); onResizeWebSurface(); _webSurface->resume(); }); QObject::connect(this, &Web3DOverlay::scriptEventReceived, _webSurface.data(), &OffscreenQmlSurface::emitScriptEvent); QObject::connect(_webSurface.data(), &OffscreenQmlSurface::webEventReceived, this, &Web3DOverlay::webEventReceived); } void Web3DOverlay::update(float deltatime) { if (_webSurface) { // update globalPosition _webSurface->getSurfaceContext()->setContextProperty("globalPosition", vec3toVariant(getWorldPosition())); } Parent::update(deltatime); } bool Web3DOverlay::isWebContent() const { QUrl sourceUrl(_url); if (sourceUrl.scheme() == "http" || sourceUrl.scheme() == "https" || _url.toLower().endsWith(".htm") || _url.toLower().endsWith(".html")) { return true; } return false; } void Web3DOverlay::setupQmlSurface() { _webSurface->getSurfaceContext()->setContextProperty("Users", DependencyManager::get<UsersScriptingInterface>().data()); _webSurface->getSurfaceContext()->setContextProperty("HMD", DependencyManager::get<HMDScriptingInterface>().data()); _webSurface->getSurfaceContext()->setContextProperty("UserActivityLogger", DependencyManager::get<UserActivityLoggerScriptingInterface>().data()); _webSurface->getSurfaceContext()->setContextProperty("Preferences", DependencyManager::get<Preferences>().data()); _webSurface->getSurfaceContext()->setContextProperty("Vec3", new Vec3()); _webSurface->getSurfaceContext()->setContextProperty("Quat", new Quat()); _webSurface->getSurfaceContext()->setContextProperty("MyAvatar", DependencyManager::get<AvatarManager>()->getMyAvatar().get()); _webSurface->getSurfaceContext()->setContextProperty("Entities", DependencyManager::get<EntityScriptingInterface>().data()); _webSurface->getSurfaceContext()->setContextProperty("Snapshot", DependencyManager::get<Snapshot>().data()); if (_webSurface->getRootItem() && _webSurface->getRootItem()->objectName() == "tabletRoot") { auto tabletScriptingInterface = DependencyManager::get<TabletScriptingInterface>(); auto flags = tabletScriptingInterface->getFlags(); _webSurface->getSurfaceContext()->setContextProperty("offscreenFlags", flags); _webSurface->getSurfaceContext()->setContextProperty("AddressManager", DependencyManager::get<AddressManager>().data()); _webSurface->getSurfaceContext()->setContextProperty("Account", AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED _webSurface->getSurfaceContext()->setContextProperty("GlobalServices", AccountServicesScriptingInterface::getInstance()); // DEPRECATED - TO BE REMOVED _webSurface->getSurfaceContext()->setContextProperty("AccountServices", AccountServicesScriptingInterface::getInstance()); // in Qt 5.10.0 there is already an "Audio" object in the QML context // though I failed to find it (from QtMultimedia??). So.. let it be "AudioScriptingInterface" _webSurface->getSurfaceContext()->setContextProperty("AudioScriptingInterface", DependencyManager::get<AudioScriptingInterface>().data()); _webSurface->getSurfaceContext()->setContextProperty("AudioStats", DependencyManager::get<AudioClient>()->getStats().data()); _webSurface->getSurfaceContext()->setContextProperty("HMD", DependencyManager::get<HMDScriptingInterface>().data()); _webSurface->getSurfaceContext()->setContextProperty("fileDialogHelper", new FileDialogHelper()); _webSurface->getSurfaceContext()->setContextProperty("MyAvatar", DependencyManager::get<AvatarManager>()->getMyAvatar().get()); _webSurface->getSurfaceContext()->setContextProperty("ScriptDiscoveryService", DependencyManager::get<ScriptEngines>().data()); _webSurface->getSurfaceContext()->setContextProperty("Assets", DependencyManager::get<AssetMappingsScriptingInterface>().data()); _webSurface->getSurfaceContext()->setContextProperty("LODManager", DependencyManager::get<LODManager>().data()); _webSurface->getSurfaceContext()->setContextProperty("OctreeStats", DependencyManager::get<OctreeStatsProvider>().data()); _webSurface->getSurfaceContext()->setContextProperty("DCModel", DependencyManager::get<DomainConnectionModel>().data()); _webSurface->getSurfaceContext()->setContextProperty("AvatarInputs", AvatarInputs::getInstance()); _webSurface->getSurfaceContext()->setContextProperty("AvatarList", DependencyManager::get<AvatarManager>().data()); _webSurface->getSurfaceContext()->setContextProperty("DialogsManager", DialogsManagerScriptingInterface::getInstance()); _webSurface->getSurfaceContext()->setContextProperty("InputConfiguration", DependencyManager::get<InputConfiguration>().data()); _webSurface->getSurfaceContext()->setContextProperty("SoundCache", DependencyManager::get<SoundCache>().data()); _webSurface->getSurfaceContext()->setContextProperty("MenuInterface", MenuScriptingInterface::getInstance()); _webSurface->getSurfaceContext()->setContextProperty("Settings", SettingsScriptingInterface::getInstance()); _webSurface->getSurfaceContext()->setContextProperty("Render", AbstractViewStateInterface::instance()->getRenderEngine()->getConfiguration().get()); _webSurface->getSurfaceContext()->setContextProperty("Controller", DependencyManager::get<controller::ScriptingInterface>().data()); _webSurface->getSurfaceContext()->setContextProperty("Pointers", DependencyManager::get<PointerScriptingInterface>().data()); _webSurface->getSurfaceContext()->setContextProperty("Web3DOverlay", this); _webSurface->getSurfaceContext()->setContextProperty("pathToFonts", "../../"); // Override min fps for tablet UI, for silky smooth scrolling setMaxFPS(90); } } void Web3DOverlay::setMaxFPS(uint8_t maxFPS) { _desiredMaxFPS = maxFPS; if (_webSurface) { _webSurface->setMaxFps(_desiredMaxFPS); _currentMaxFPS = _desiredMaxFPS; } } void Web3DOverlay::onResizeWebSurface() { glm::vec2 dims = glm::vec2(getDimensions()); dims *= METERS_TO_INCHES * _dpi; // ensure no side is never larger then MAX_WINDOW_SIZE float max = (dims.x > dims.y) ? dims.x : dims.y; if (max > MAX_WINDOW_SIZE) { dims *= MAX_WINDOW_SIZE / max; } _webSurface->resize(QSize(dims.x, dims.y)); } unsigned int Web3DOverlay::deviceIdByTouchPoint(qreal x, qreal y) { if (_webSurface) { return _webSurface->deviceIdByTouchPoint(x, y); } else { return PointerEvent::INVALID_POINTER_ID; } } void Web3DOverlay::render(RenderArgs* args) { if (!_renderVisible || !getParentVisible()) { return; } if (!_webSurface) { emit requestWebSurface(); return; } if (_mayNeedResize) { emit resizeWebSurface(); } if (_currentMaxFPS != _desiredMaxFPS) { setMaxFPS(_desiredMaxFPS); } vec4 color(toGlm(getColor()), getAlpha()); if (!_texture) { _texture = gpu::Texture::createExternal(OffscreenQmlSurface::getDiscardLambda()); _texture->setSource(__FUNCTION__); } OffscreenQmlSurface::TextureAndFence newTextureAndFence; bool newTextureAvailable = _webSurface->fetchTexture(newTextureAndFence); if (newTextureAvailable) { _texture->setExternalTexture(newTextureAndFence.first, newTextureAndFence.second); } Q_ASSERT(args->_batch); gpu::Batch& batch = *args->_batch; batch.setResourceTexture(0, _texture); auto renderTransform = getRenderTransform(); auto size = renderTransform.getScale(); renderTransform.setScale(1.0f); batch.setModelTransform(renderTransform); auto geometryCache = DependencyManager::get<GeometryCache>(); if (color.a < OPAQUE_ALPHA_THRESHOLD) { geometryCache->bindWebBrowserProgram(batch, true); } else { geometryCache->bindWebBrowserProgram(batch); } vec2 halfSize = vec2(size.x, size.y) / 2.0f; geometryCache->renderQuad(batch, halfSize * -1.0f, halfSize, vec2(0), vec2(1), color, _geometryId); batch.setResourceTexture(0, nullptr); // restore default white color after me } Transform Web3DOverlay::evalRenderTransform() { Transform transform = Parent::evalRenderTransform(); transform.setScale(1.0f); transform.postScale(glm::vec3(getDimensions(), 1.0f)); return transform; } const render::ShapeKey Web3DOverlay::getShapeKey() { auto builder = render::ShapeKey::Builder().withoutCullFace().withDepthBias().withOwnPipeline(); if (isTransparent()) { builder.withTranslucent(); } return builder.build(); } QObject* Web3DOverlay::getEventHandler() { if (!_webSurface) { return nullptr; } return _webSurface->getEventHandler(); } void Web3DOverlay::setProxyWindow(QWindow* proxyWindow) { if (!_webSurface) { return; } _webSurface->setProxyWindow(proxyWindow); } void Web3DOverlay::hoverEnterOverlay(const PointerEvent& event) { if (_inputMode == Mouse) { handlePointerEvent(event); } else if (_webSurface) { PointerEvent webEvent = event; webEvent.setPos2D(event.getPos2D() * (METERS_TO_INCHES * _dpi)); _webSurface->hoverBeginEvent(webEvent, _touchDevice); } } void Web3DOverlay::hoverLeaveOverlay(const PointerEvent& event) { if (_inputMode == Mouse) { PointerEvent endEvent(PointerEvent::Release, event.getID(), event.getPos2D(), event.getPos3D(), event.getNormal(), event.getDirection(), event.getButton(), event.getButtons(), event.getKeyboardModifiers()); handlePointerEvent(endEvent); // QML onReleased is only triggered if a click has happened first. We need to send this "fake" mouse move event to properly trigger an onExited. PointerEvent endMoveEvent(PointerEvent::Move, event.getID()); handlePointerEvent(endMoveEvent); } else if (_webSurface) { PointerEvent webEvent = event; webEvent.setPos2D(event.getPos2D() * (METERS_TO_INCHES * _dpi)); _webSurface->hoverEndEvent(webEvent, _touchDevice); } } void Web3DOverlay::handlePointerEvent(const PointerEvent& event) { if (_inputMode == Touch) { handlePointerEventAsTouch(event); } else { handlePointerEventAsMouse(event); } } void Web3DOverlay::handlePointerEventAsTouch(const PointerEvent& event) { if (_webSurface) { PointerEvent webEvent = event; webEvent.setPos2D(event.getPos2D() * (METERS_TO_INCHES * _dpi)); _webSurface->handlePointerEvent(webEvent, _touchDevice); } } void Web3DOverlay::handlePointerEventAsMouse(const PointerEvent& event) { if (!_webSurface) { return; } glm::vec2 windowPos = event.getPos2D() * (METERS_TO_INCHES * _dpi); QPointF windowPoint(windowPos.x, windowPos.y); Qt::MouseButtons buttons = Qt::NoButton; if (event.getButtons() & PointerEvent::PrimaryButton) { buttons |= Qt::LeftButton; } Qt::MouseButton button = Qt::NoButton; if (event.getButton() == PointerEvent::PrimaryButton) { button = Qt::LeftButton; } QEvent::Type type; switch (event.getType()) { case PointerEvent::Press: type = QEvent::MouseButtonPress; break; case PointerEvent::Release: type = QEvent::MouseButtonRelease; break; case PointerEvent::Move: type = QEvent::MouseMove; break; default: return; } QMouseEvent mouseEvent(type, windowPoint, windowPoint, windowPoint, button, buttons, event.getKeyboardModifiers()); QCoreApplication::sendEvent(_webSurface->getWindow(), &mouseEvent); } void Web3DOverlay::setProperties(const QVariantMap& properties) { Billboard3DOverlay::setProperties(properties); auto urlValue = properties["url"]; if (urlValue.isValid()) { QString newURL = urlValue.toString(); if (newURL != _url) { setURL(newURL); } } auto scriptURLValue = properties["scriptURL"]; if (scriptURLValue.isValid()) { QString newScriptURL = scriptURLValue.toString(); if (newScriptURL != _scriptURL) { setScriptURL(newScriptURL); } } auto dpi = properties["dpi"]; if (dpi.isValid()) { _dpi = dpi.toFloat(); _mayNeedResize = true; } auto maxFPS = properties["maxFPS"]; if (maxFPS.isValid()) { _desiredMaxFPS = maxFPS.toInt(); } auto showKeyboardFocusHighlight = properties["showKeyboardFocusHighlight"]; if (showKeyboardFocusHighlight.isValid()) { _showKeyboardFocusHighlight = showKeyboardFocusHighlight.toBool(); } auto inputModeValue = properties["inputMode"]; if (inputModeValue.isValid()) { QString inputModeStr = inputModeValue.toString(); if (inputModeStr == "Mouse") { _inputMode = Mouse; } else { _inputMode = Touch; } } } // Web3DOverlay overrides the meaning of Planar3DOverlay's dimensions property. /**jsdoc * These are the properties of a <code>web3d</code> {@link Overlays.OverlayType|OverlayType}. * @typedef {object} Overlays.Web3DProperties * * @property {string} type=web3d - Has the value <code>"web3d"</code>. <em>Read-only.</em> * @property {Color} color=255,255,255 - The color of the overlay. * @property {number} alpha=0.7 - The opacity of the overlay, <code>0.0</code> - <code>1.0</code>. * @property {number} pulseMax=0 - The maximum value of the pulse multiplier. * @property {number} pulseMin=0 - The minimum value of the pulse multiplier. * @property {number} pulsePeriod=1 - The duration of the color and alpha pulse, in seconds. A pulse multiplier value goes from * <code>pulseMin</code> to <code>pulseMax</code>, then <code>pulseMax</code> to <code>pulseMin</code> in one period. * @property {number} alphaPulse=0 - If non-zero, the alpha of the overlay is pulsed: the alpha value is multiplied by the * current pulse multiplier value each frame. If > 0 the pulse multiplier is applied in phase with the pulse period; if < 0 * the pulse multiplier is applied out of phase with the pulse period. (The magnitude of the property isn't otherwise * used.) * @property {number} colorPulse=0 - If non-zero, the color of the overlay is pulsed: the color value is multiplied by the * current pulse multiplier value each frame. If > 0 the pulse multiplier is applied in phase with the pulse period; if < 0 * the pulse multiplier is applied out of phase with the pulse period. (The magnitude of the property isn't otherwise * used.) * @property {boolean} visible=true - If <code>true</code>, the overlay is rendered, otherwise it is not rendered. * * @property {string} name="" - A friendly name for the overlay. * @property {Vec3} position - The position of the overlay center. Synonyms: <code>p1</code>, <code>point</code>, and * <code>start</code>. * @property {Vec3} localPosition - The local position of the overlay relative to its parent if the overlay has a * <code>parentID</code> set, otherwise the same value as <code>position</code>. * @property {Quat} rotation - The orientation of the overlay. Synonym: <code>orientation</code>. * @property {Quat} localRotation - The orientation of the overlay relative to its parent if the overlay has a * <code>parentID</code> set, otherwise the same value as <code>rotation</code>. * @property {boolean} isSolid=false - Synonyms: <ode>solid</code>, <code>isFilled</code>, and <code>filled</code>. * Antonyms: <code>isWire</code> and <code>wire</code>. * @property {boolean} isDashedLine=false - If <code>true</code>, a dashed line is drawn on the overlay's edges. Synonym: * <code>dashed</code>. * @property {boolean} ignoreRayIntersection=false - If <code>true</code>, * {@link Overlays.findRayIntersection|findRayIntersection} ignores the overlay. * @property {boolean} drawInFront=false - If <code>true</code>, the overlay is rendered in front of other overlays that don't * have <code>drawInFront</code> set to <code>true</code>, and in front of entities. * @property {boolean} grabbable=false - Signal to grabbing scripts whether or not this overlay can be grabbed. * @property {Uuid} parentID=null - The avatar, entity, or overlay that the overlay is parented to. * @property {number} parentJointIndex=65535 - Integer value specifying the skeleton joint that the overlay is attached to if * <code>parentID</code> is an avatar skeleton. A value of <code>65535</code> means "no joint". * * @property {boolean} isFacingAvatar - If <code>true</code>, the overlay is rotated to face the user's camera about an axis * parallel to the user's avatar's "up" direction. * * @property {string} url - The URL of the Web page to display. * @property {string} scriptURL="" - The URL of a JavaScript file to inject into the Web page. * @property {number} dpi=30 - The dots per inch to display the Web page at, on the overlay. * @property {Vec2} dimensions=1,1 - The size of the overlay to display the Web page on, in meters. Synonyms: * <code>scale</code>, <code>size</code>. * @property {number} maxFPS=10 - The maximum update rate for the Web overlay content, in frames/second. * @property {boolean} showKeyboardFocusHighlight=true - If <code>true</code>, the Web overlay is highlighted when it has * keyboard focus. * @property {string} inputMode=Touch - The user input mode to use - either <code>"Touch"</code> or <code>"Mouse"</code>. */ QVariant Web3DOverlay::getProperty(const QString& property) { if (property == "url") { return _url; } if (property == "scriptURL") { return _scriptURL; } if (property == "dpi") { return _dpi; } if (property == "maxFPS") { return _desiredMaxFPS; } if (property == "showKeyboardFocusHighlight") { return _showKeyboardFocusHighlight; } if (property == "inputMode") { if (_inputMode == Mouse) { return QVariant("Mouse"); } else { return QVariant("Touch"); } } return Billboard3DOverlay::getProperty(property); } void Web3DOverlay::setURL(const QString& url) { if (url != _url) { bool wasWebContent = isWebContent(); _url = url; if (_webSurface) { if (wasWebContent && isWebContent()) { // If we're just targeting a new web URL, then switch to that without messing around // with the underlying QML AbstractViewStateInterface::instance()->postLambdaEvent([this, url] { _webSurface->getRootItem()->setProperty("url", _url); _webSurface->getRootItem()->setProperty("scriptURL", _scriptURL); }); } else { // If we're switching to or from web content, or between different QML content // we need to destroy and rebuild the entire QML surface AbstractViewStateInterface::instance()->postLambdaEvent([this, url] { rebuildWebSurface(); }); } } } } void Web3DOverlay::setScriptURL(const QString& scriptURL) { _scriptURL = scriptURL; if (_webSurface) { AbstractViewStateInterface::instance()->postLambdaEvent([this, scriptURL] { if (!_webSurface) { return; } _webSurface->getRootItem()->setProperty("scriptURL", scriptURL); }); } } bool Web3DOverlay::findRayIntersection(const glm::vec3& origin, const glm::vec3& direction, float& distance, BoxFace& face, glm::vec3& surfaceNormal) { glm::vec2 dimensions = getDimensions(); glm::quat rotation = getWorldOrientation(); glm::vec3 position = getWorldPosition(); if (findRayRectangleIntersection(origin, direction, rotation, position, dimensions, distance)) { surfaceNormal = rotation * Vectors::UNIT_Z; face = glm::dot(surfaceNormal, direction) > 0 ? MIN_Z_FACE : MAX_Z_FACE; return true; } else { return false; } } Web3DOverlay* Web3DOverlay::createClone() const { return new Web3DOverlay(this); } void Web3DOverlay::emitScriptEvent(const QVariant& message) { QMetaObject::invokeMethod(this, "scriptEventReceived", Q_ARG(QVariant, message)); }
43.833605
159
0.700595
cain-kilgore
4f99e8788a3aeb592ed260fa26f02b977127bc88
619
cpp
C++
prova tema3.cpp
RafelNunes/ifsc-programacao
40622fb1a5496e09f4800220e293385468fef323
[ "MIT" ]
null
null
null
prova tema3.cpp
RafelNunes/ifsc-programacao
40622fb1a5496e09f4800220e293385468fef323
[ "MIT" ]
null
null
null
prova tema3.cpp
RafelNunes/ifsc-programacao
40622fb1a5496e09f4800220e293385468fef323
[ "MIT" ]
null
null
null
#include<stdio.h> #include<math.h> main() { float peso=0, altura=0, IMC=0, soma=0, soma2; printf("Digite seu peso[em kg]: "); scanf("%f", &peso); while(peso>0){ soma = peso; printf("Digite sua altura: "); scanf("%f", &altura); soma = pow(altura,2); IMC = peso/soma; if(IMC<18.5){ printf("\nAbaixo do peso.\n"); }else if(IMC>18.5 && IMC<25){ printf("\nPeso normal.\n"); }else if(IMC>25 && IMC<30){ printf("\nSobrepeso.\n"); }else if(IMC>30){ printf("\nObesidade.\n"); } printf("Digite seu peso[em kg]: "); scanf("%f", &peso); peso = peso + peso; } }
16.289474
46
0.546042
RafelNunes
4f9b64c95a7ad0282b731837dcb0f65f699b4ef2
8,308
hpp
C++
build-time-parser/core_tree.hpp
daher-alfawares/build-time-parser
eaf8c8a446a7a91380a5fce4b006a2addd43d974
[ "Apache-2.0" ]
null
null
null
build-time-parser/core_tree.hpp
daher-alfawares/build-time-parser
eaf8c8a446a7a91380a5fce4b006a2addd43d974
[ "Apache-2.0" ]
null
null
null
build-time-parser/core_tree.hpp
daher-alfawares/build-time-parser
eaf8c8a446a7a91380a5fce4b006a2addd43d974
[ "Apache-2.0" ]
null
null
null
//C++ ////////////////////////////////////////////////////////////////////////////// // // // Filename : ASCII_Table.hpp // // Created by : Daher Alfawares // // Created Date : 06/20/2009 // // License : Apache License 2.0 // // // // Copyright 2009 Daher Alfawares // // // // 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. // // // ////////////////////////////////////////////////////////////////////////////// /* ASCII Table is a C++ class that allows you to format your data in an ASCII dynamic table structure. Example: ascii::table myTable("Table Title"); myTable ("header 1")("header 2")++; myTable ("value 11")("value 12")++; myTable ("value 21")("value 22")++; std::cout << myTable; Output: +---------------------+ |Table Title | +----------+----------+ | header 1 | header 2 | +----------+----------+ | value 11 | value 12 | | value 21 | value 22 | +----------+----------+ */ #ifndef _DA_ASCII_Table__0a61eabe_d038_4d30_a6fb_e202b2dfd6a9 #define _DA_ASCII_Table__0a61eabe_d038_4d30_a6fb_e202b2dfd6a9 #include <iostream> #include <vector> #include <string> #include <iomanip> #include <numeric> namespace ascii { // forward: // the following allows adding a C style string to an std::string and returns an std::string. // example: // std::string a = "abc"; // std::string b = "123" + a; // inline std::string operator + ( const char*a, const std::string& b ); inline std::string itoa( const int &i ); inline int atoi( const std::string&s ); // lexical cast. template<typename _To, typename _From> class lexical_cast; struct scoped_mute_s; // formats the output. std::string format( std::string _Name, int _Code ); class table { public: std::string title; size_t column; std::vector<std::string> columns; std::vector<std::size_t> column_widths; bool column_complete; std::string comment; std::string Prefix; // line prefix. table( std::string t ):title(t),column(0),column_complete(false){} std::vector< std::vector<std::string> > rows; table & operator()(std::string t) { if( column >= columns.size() ) { columns.push_back(""); column_widths.push_back(0); } columns[column] = t; if( column_widths[column] < t.size() ) column_widths[column] = t.size(); ++column; return *this; } table & operator()(int i) { return (*this)(itoa(i)); } void operator ++(int) { column = 0; column_complete = true; rows.push_back( columns ); } std::string prefix(){ return Prefix; } void prefix( std::string _P ){ Prefix=_P; } std::string endl(){ return "\r\n" + format("",1) + prefix() + " "; } }; inline std::ostream& operator << ( std::ostream& _Str, table& T ) { int width = std::accumulate( T.column_widths.begin(), T.column_widths.end(), 0 ); width += 3*T.columns.size(); _Str << std::setiosflags(std::ios::left); _Str << format("",1) << T.endl(); // top border. _Str << '+'; for( int b=0; b< width-1; b++ ) _Str << '-'; _Str << '+' << T.endl(); // title. _Str << "|" << std::setw(width-1) << T.title << "|" << T.endl(); // middle border for( size_t i=0; i< T.columns.size(); i++ ) _Str << "+-" << std::setw( T.column_widths[i] ) << std::setfill('-') << "" << std::setfill(' ') << "-"; _Str << "+" << T.endl(); if( !T.rows.empty() || !T.rows[0].empty() ) { size_t i=0,j=0; // first row as header. for( i=0; i< T.columns.size(); i++ ) { _Str << "| " << std::setw( T.column_widths[i] ) << T.rows[j][i] << " "; } _Str << "|" << T.endl(); // middle border for( size_t i=0; i< T.columns.size(); i++ ) { _Str << "+-" << std::setw( T.column_widths[i] ) << std::setfill('-') << "" << std::setfill(' ') << "-"; } _Str << "+" << T.endl(); // comment if available. if( !T.comment.empty() ) _Str << "|" << std::setw(width-1) << T.comment << "|" << T.endl(); // full table. for( size_t j=1; j< T.rows.size(); j++ ) { for( size_t i=0; i< T.columns.size(); i++ ) { _Str << "| " << std::setw( T.column_widths[i] ) << T.rows[j][i] << " "; } _Str << "|" << T.endl(); } } // bottom border. for( size_t i=0; i< T.columns.size(); i++ ) { _Str << "+-" << std::setw( T.column_widths[i] ) << std::setfill('-') << "" << std::setfill(' ') << "-"; } _Str << std::resetiosflags(std::ios::left); _Str << "+" << std::endl; return _Str; } inline std::string operator + ( const char*a, const std::string& b ) { std::string c; c += a; c += b; return c; } inline std::string itoa( const int &i ) { std::stringstream Str; Str << i; return Str.str(); } inline int atoi( const std::string&s ) { int i; std::istringstream Str(s); Str >> i; return i; } // lexical cast. template<typename _To, typename _From> class lexical_cast { _From * from; public: lexical_cast<_To, _From>( _From From ) { this->from = & From; } operator _To() { throw( "Bad lexical cast: " ); } }; struct scoped_mute_s { scoped_mute_s(); ~scoped_mute_s(); }; #define scoped_mute() ascii::scoped_mute_s _6BBBC7E7_B5DB_41a0_9BE9_61BA1AFF2183_ #define once(a) {static bool F399DD2E_11AA_4d81_90AD_A4130C8D96A8;if(!F399DD2E_11AA_4d81_90AD_A4130C8D96A8)(a),F399DD2E_11AA_4d81_90AD_A4130C8D96A8=true;} // formats the output. inline std::string format( std::string _Name, int _Code ) { return ""; #ifndef _DEBUG if( _Name.length() > 10 ) _Name.erase(10); // if( _Description.length() > 255 ) _Description.erase(254); #endif char datetime[20]; std::time_t Time_t = std::time(0); std::tm *Time; #if defined (_MSC_VER) && (_MSC_VER >= 1300) // secure version. std::tm TimeS; Time = &TimeS; localtime_s( Time, &Time_t ); #else // insecure portable version Time = std::localtime( &Time_t ); #endif strftime( datetime, 20, "%Y-%m-%d %H:%M:%S", Time ); std::stringstream _Str; _Str << std::setw(10) << _Name << " " << datetime << " " << std::setfill('0') << std::setw(3) << _Code << " "; return _Str.str(); } } /* ascii */ #endif
29.884892
176
0.455344
daher-alfawares
4f9ebfd2a7c62b1714faf78d1eef9f22d7e4549f
414
cpp
C++
AndGate.cpp
sgeisler/LogSim
c2120430117a569a1d108f99ad57422bb949d6d2
[ "MIT" ]
null
null
null
AndGate.cpp
sgeisler/LogSim
c2120430117a569a1d108f99ad57422bb949d6d2
[ "MIT" ]
null
null
null
AndGate.cpp
sgeisler/LogSim
c2120430117a569a1d108f99ad57422bb949d6d2
[ "MIT" ]
null
null
null
#include "AndGate.h" AndGate::AndGate() { //ctor } AndGate::~AndGate() { //dtor } string AndGate::getName() { return "AND"; } size_t AndGate::getInputCount() { return 2; } bool AndGate::getOutput(size_t pin) { switch(pin) { case 0: return inputs[0] && inputs[1]; break; default: return false; } } size_t AndGate::getOutputCount() { return 1; }
10.615385
38
0.562802
sgeisler
4fa0d2e502a73eb6acb82ef6cf154c64fe234bf7
7,055
hh
C++
app/demo-loop/LDemoRun.i.hh
tmdelellis/celeritas
5252bcb0659892ae9082ca2b6716e3c84e18004b
[ "Apache-2.0", "MIT" ]
null
null
null
app/demo-loop/LDemoRun.i.hh
tmdelellis/celeritas
5252bcb0659892ae9082ca2b6716e3c84e18004b
[ "Apache-2.0", "MIT" ]
null
null
null
app/demo-loop/LDemoRun.i.hh
tmdelellis/celeritas
5252bcb0659892ae9082ca2b6716e3c84e18004b
[ "Apache-2.0", "MIT" ]
null
null
null
//----------------------------------*-C++-*----------------------------------// // Copyright 2021 UT-Battelle, LLC, and other Celeritas developers. // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: (Apache-2.0 OR MIT) //---------------------------------------------------------------------------// //! \file LDemoRun.i.hh //---------------------------------------------------------------------------// #include "base/CollectionStateStore.hh" #include "base/VectorUtils.hh" #include "comm/Logger.hh" #include "physics/base/ModelData.hh" #include "sim/TrackInitUtils.hh" #include "sim/TrackData.hh" #include "LDemoParams.hh" #include "LDemoKernel.hh" #include "diagnostic/EnergyDiagnostic.hh" #include "diagnostic/ParticleProcessDiagnostic.hh" #include "diagnostic/StepDiagnostic.hh" #include "diagnostic/TrackDiagnostic.hh" using namespace celeritas; namespace demo_loop { namespace { //---------------------------------------------------------------------------// template<class P, MemSpace M> struct ParamsGetter; template<class P> struct ParamsGetter<P, MemSpace::host> { const P& params_; auto operator()() const -> decltype(auto) { return params_.host_ref(); } }; template<class P> struct ParamsGetter<P, MemSpace::device> { const P& params_; auto operator()() const -> decltype(auto) { return params_.device_ref(); } }; template<MemSpace M, class P> decltype(auto) get_ref(const P& params) { return ParamsGetter<P, M>{params}(); } //---------------------------------------------------------------------------// template<MemSpace M> ParamsData<Ownership::const_reference, M> build_params_refs(const LDemoParams& p) { ParamsData<Ownership::const_reference, M> ref; ref.geometry = get_ref<M>(*p.geometry); ref.materials = get_ref<M>(*p.materials); ref.geo_mats = get_ref<M>(*p.geo_mats); ref.cutoffs = get_ref<M>(*p.cutoffs); ref.particles = get_ref<M>(*p.particles); ref.physics = get_ref<M>(*p.physics); ref.rng = get_ref<M>(*p.rng); ref.track_inits = get_ref<M>(*p.track_inits); CELER_ENSURE(ref); return ref; } //---------------------------------------------------------------------------// /*! * Launch interaction kernels for all applicable models. * * For now, just launch *all* the models. */ template<MemSpace M> void launch_models(LDemoParams const& host_params, ParamsData<Ownership::const_reference, M> const& params, StateData<Ownership::reference, M> const& states) { // TODO: these *should* be able to be persistent across steps, rather than // recreated at every step. ModelInteractRef<M> refs; refs.params.particle = params.particles; refs.params.material = params.materials; refs.params.physics = params.physics; refs.params.cutoffs = params.cutoffs; refs.states.particle = states.particles; refs.states.material = states.materials; refs.states.physics = states.physics; refs.states.rng = states.rng; refs.states.sim = states.sim; refs.states.direction = states.geometry.dir; refs.states.secondaries = states.secondaries; refs.states.interactions = states.interactions; CELER_ASSERT(refs); // Loop over physics models IDs and invoke `interact` for (auto model_id : range(ModelId{host_params.physics->num_models()})) { const Model& model = host_params.physics->model(model_id); model.interact(refs); } } //---------------------------------------------------------------------------// } // namespace //---------------------------------------------------------------------------// template<MemSpace M> LDemoResult run_demo(LDemoArgs args) { CELER_EXPECT(args); // Load all the problem data LDemoParams params = load_params(args); // Create param interfaces auto params_ref = build_params_refs<M>(params); // Diagnostics // TODO: Create a vector of these objects. TrackDiagnostic<M> track_diagnostic; StepDiagnostic<M> step_diagnostic( params_ref, params.particles, args.max_num_tracks, 200); ParticleProcessDiagnostic<M> process_diagnostic( params_ref, params.particles, params.physics); EnergyDiagnostic<M> energy_diagnostic(linspace(-700.0, 700.0, 1024 + 1)); // Create states (TODO state store?) StateData<Ownership::value, M> state_storage; resize(&state_storage, build_params_refs<MemSpace::host>(params), args.max_num_tracks); StateData<Ownership::reference, M> states_ref = make_ref(state_storage); // Copy primaries to device and create track initializers CELER_ASSERT(params.track_inits->host_ref().primaries.size() <= state_storage.track_inits.initializers.capacity()); extend_from_primaries(params.track_inits->host_ref(), &state_storage.track_inits); size_type num_alive = 0; size_type num_inits = state_storage.track_inits.initializers.size(); size_type remaining_steps = args.max_steps; while (num_alive > 0 || num_inits > 0) { // Create new tracks from primaries or secondaries initialize_tracks(params_ref, states_ref, &state_storage.track_inits); demo_loop::pre_step(params_ref, states_ref); demo_loop::along_and_post_step(params_ref, states_ref); // Launch the interaction kernels for all applicable models launch_models(params, params_ref, states_ref); // Mid-step diagnostics process_diagnostic.mid_step(states_ref); step_diagnostic.mid_step(states_ref); // Postprocess secondaries and interaction results demo_loop::process_interactions(params_ref, states_ref); // Create track initializers from surviving secondaries extend_from_secondaries( params_ref, states_ref, &state_storage.track_inits); // Clear secondaries demo_loop::cleanup(params_ref, states_ref); // Get the number of track initializers and active tracks num_alive = args.max_num_tracks - state_storage.track_inits.vacancies.size(); num_inits = state_storage.track_inits.initializers.size(); // End-of-step diagnostic(s) track_diagnostic.end_step(states_ref); energy_diagnostic.end_step(states_ref); if (--remaining_steps == 0) { // Exceeded step count break; } } // Collect results from diagnostics LDemoResult result; result.time = {0}; result.alive = track_diagnostic.num_alive_per_step(); result.edep = energy_diagnostic.energy_deposition(); result.process = process_diagnostic.particle_processes(); result.steps = step_diagnostic.steps(); result.total_time = 0; return result; } //---------------------------------------------------------------------------// } // namespace demo_loop
34.925743
79
0.610489
tmdelellis
4fa0f6f65d05fef23d30d652a335ec60e0206b99
2,948
cpp
C++
liupeng/src/main/java/liupeng/Ch2_HDFS/liveMedia/BasicUDPSource.cpp
jayfans3/example
6982e33d760dd8e4d94de40c81ae733434bf3f1b
[ "BSD-2-Clause" ]
null
null
null
liupeng/src/main/java/liupeng/Ch2_HDFS/liveMedia/BasicUDPSource.cpp
jayfans3/example
6982e33d760dd8e4d94de40c81ae733434bf3f1b
[ "BSD-2-Clause" ]
null
null
null
liupeng/src/main/java/liupeng/Ch2_HDFS/liveMedia/BasicUDPSource.cpp
jayfans3/example
6982e33d760dd8e4d94de40c81ae733434bf3f1b
[ "BSD-2-Clause" ]
null
null
null
/********** This library 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. (See <http://www.gnu.org/copyleft/lesser.html>.) This library 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 this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********/ // "liveMedia" // Copyright (c) 1996-2011 Live Networks, Inc. All rights reserved. // A simple UDP source, where every UDP payload is a complete frame // Implementation #include "BasicUDPSource.hh" #include <GroupsockHelper.hh> BasicUDPSource* BasicUDPSource::createNew(UsageEnvironment& env, Groupsock* inputGS) { return new BasicUDPSource(env, inputGS); } BasicUDPSource::BasicUDPSource(UsageEnvironment& env, Groupsock* inputGS) : FramedSource(env), fInputGS(inputGS), fHaveStartedReading(False) { // Try to use a large receive buffer (in the OS): increaseReceiveBufferTo(env, inputGS->socketNum(), 50*1024); // Make the socket non-blocking, even though it will be read from only asynchronously, when packets arrive. // The reason for this is that, in some OSs, reads on a blocking socket can (allegedly) sometimes block, // even if the socket was previously reported (e.g., by "select()") as having data available. // (This can supposedly happen if the UDP checksum fails, for example.) makeSocketNonBlocking(fInputGS->socketNum()); } BasicUDPSource::~BasicUDPSource(){ envir().taskScheduler().turnOffBackgroundReadHandling(fInputGS->socketNum()); } void BasicUDPSource::doGetNextFrame() { if (!fHaveStartedReading) { // Await incoming packets: envir().taskScheduler().turnOnBackgroundReadHandling(fInputGS->socketNum(), (TaskScheduler::BackgroundHandlerProc*)&incomingPacketHandler, this); fHaveStartedReading = True; } } void BasicUDPSource::doStopGettingFrames() { envir().taskScheduler().turnOffBackgroundReadHandling(fInputGS->socketNum()); fHaveStartedReading = False; } void BasicUDPSource::incomingPacketHandler(BasicUDPSource* source, int /*mask*/){ source->incomingPacketHandler1(); } void BasicUDPSource::incomingPacketHandler1() { if (!isCurrentlyAwaitingData()) return; // we're not ready for the data yet // Read the packet into our desired destination: struct sockaddr_in fromAddress; if (!fInputGS->handleRead(fTo, fMaxSize, fFrameSize, fromAddress)) return; // Tell our client that we have new data: afterGetting(this); // we're preceded by a net read; no infinite recursion }
39.837838
109
0.756784
jayfans3
4fa234e07691200e669d988a3d9d903daea69479
8,624
cpp
C++
tests/pso_test.cpp
walragatver/ensmallen
7c37b614e35bd1e8f2131d5ee631013493be53bf
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
tests/pso_test.cpp
walragatver/ensmallen
7c37b614e35bd1e8f2131d5ee631013493be53bf
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
tests/pso_test.cpp
walragatver/ensmallen
7c37b614e35bd1e8f2131d5ee631013493be53bf
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
/** * @file pso_test.cpp * @author Suryoday Basak * @author Chintan Soni * * Test file for PSO optimizer. * * mlpack is free software; you may redistribute it and/or modify it under the * terms of the 3-clause BSD license. You should have received a copy of the * 3-clause BSD license along with mlpack. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #include <ensmallen.hpp> #include "catch.hpp" using namespace ens; using namespace ens::test; /** * Test the PSO optimizer on the Sphere Function. Use arma::mat. */ TEST_CASE("LBestPSOSphereFunctionTest", "[PSOTest]") { SphereFunction f(4); LBestPSO s; arma::mat coords = f.GetInitialPoint<arma::mat>(); if (!s.Optimize(f, coords)) FAIL("LBest PSO optimization reported failure for Sphere Function."); double finalValue = f.Evaluate(coords); REQUIRE(finalValue <= 1e-5); for (size_t j = 0; j < 4; ++j) REQUIRE(coords(j) <= 1e-3); } /** * Test the PSO optimizer on the Sphere Function. Use arma::fmat. */ TEST_CASE("LBestPSOSphereFunctionFMatTest", "[PSOTest]") { SphereFunction f(4); LBestPSO s; arma::fmat coords = f.GetInitialPoint<arma::fmat>(); if (!s.Optimize(f, coords)) FAIL("LBest PSO optimization reported failure for Sphere Function."); double finalValue = f.Evaluate(coords); REQUIRE(finalValue <= 1e-5); for (size_t j = 0; j < 4; ++j) REQUIRE(coords(j) <= 1e-3); } /** * Test the PSO optimizer on the Rosenbrock Function. Use arma::mat. */ TEST_CASE("LBestPSORosenbrockTest","[PSOTest]") { RosenbrockFunction f; // Setting bounds for the initial swarm population. arma::vec lowerBound(2); arma::vec upperBound(2); lowerBound.fill(50); upperBound.fill(60); LBestPSO s(250, lowerBound, upperBound, 3000, 600, 1e-30, 2.05, 2.05); arma::vec coordinates = f.GetInitialPoint(); const double result = s.Optimize(f, coordinates); REQUIRE(result == Approx(0.0).margin(1e-3)); REQUIRE(coordinates(0) == Approx(1.0).epsilon(1e-2)); REQUIRE(coordinates(1) == Approx(1.0).epsilon(1e-2)); } /** * Test the PSO optimizer on the Rosenbrock Function. Use arma::fmat. */ TEST_CASE("LBestPSORosenbrockFMatTest","[PSOTest]") { RosenbrockFunction f; // Setting bounds for the initial swarm population. arma::vec lowerBound(2); arma::vec upperBound(2); lowerBound.fill(50); upperBound.fill(60); LBestPSO s(250, lowerBound, upperBound, 5000, 600, 1e-30, 2.05, 2.05); arma::fmat coordinates = f.GetInitialPoint<arma::fmat>(); const double result = s.Optimize(f, coordinates); REQUIRE(result == Approx(0.0).margin(1e-3)); REQUIRE(coordinates(0) == Approx(1.0).epsilon(1e-2)); REQUIRE(coordinates(1) == Approx(1.0).epsilon(1e-2)); } /** * Test the PSO optimizer on the Rosenbrock function with lowerBound and * upperbound of type double. */ TEST_CASE("LBestPSORosenbrockDoubleTest","[PSOTest]") { RosenbrockFunction f; // Setting bounds for the initial swarm population. double lowerBound = 50; double upperBound = 60; LBestPSO s(250, lowerBound, upperBound, 5000, 400, 1e-30, 2.05, 2.05); arma::vec coordinates = f.GetInitialPoint(); const double result = s.Optimize(f, coordinates); REQUIRE(result == Approx(0.0).margin(1e-3)); REQUIRE(coordinates(0) == Approx(1.0).epsilon(1e-3)); REQUIRE(coordinates(1) == Approx(1.0).epsilon(1e-3)); } /** * Test the PSO optimizer on Cross-in-Tray Function. */ TEST_CASE("LBestPSOCrossInTrayFunctionTest", "[PSOTest]") { CrossInTrayFunction f; // Setting bounds for the initial swarm population. arma::vec lowerBound(2); arma::vec upperBound(2); lowerBound.fill(-1); upperBound.fill(1); LBestPSO s(500, lowerBound, upperBound, 6000, 400, 1e-30, 2.05, 2.05); arma::mat coordinates = arma::mat("10; 10"); const double result = s.Optimize(f, coordinates); REQUIRE(result == Approx(-2.06261).margin(0.01)); REQUIRE(abs(coordinates(0)) == Approx(1.34941).margin(0.01)); REQUIRE(abs(coordinates(1)) == Approx(1.34941).margin(0.01)); } /** * Test the PSO optimizer on the Ackley Function. */ TEST_CASE("LBestPSOAckleyFunctionTest", "[PSOTest]") { AckleyFunction f; // Setting bounds for the initial swarm population. arma::vec lowerBound(2); arma::vec upperBound(2); lowerBound.fill(4); upperBound.fill(5); LBestPSO s(64, lowerBound, upperBound); arma::mat coordinates = arma::mat("5; 5"); const double result = s.Optimize(f, coordinates); REQUIRE(result == Approx(0).margin(0.01)); REQUIRE(coordinates(0) == Approx(0).margin(0.01)); REQUIRE(coordinates(1) == Approx(0).margin(0.01)); } /** * Test the PSO optimizer on the Beale Function. */ TEST_CASE("LBestPSOBealeFunctionTest", "[PSOTest]") { BealeFunction f; // Setting bounds for the initial swarm population. arma::vec lowerBound(2); arma::vec upperBound(2); lowerBound.fill(3); upperBound.fill(4); LBestPSO s(64, lowerBound, upperBound); arma::mat coordinates = arma::mat("4.5; 4.5"); const double result = s.Optimize(f, coordinates); REQUIRE(result == Approx(0).margin(0.01)); REQUIRE(coordinates(0) == Approx(3).margin(0.01)); REQUIRE(coordinates(1) == Approx(0.5).margin(0.01)); } /** * Test the PSO optimizer on the Goldstein-Price Function. */ TEST_CASE("LBestPSOGoldsteinPriceFunctionTest", "[PSOTest]") { GoldsteinPriceFunction f; // Setting bounds for the initial swarm population. arma::vec lowerBound(2); arma::vec upperBound(2); lowerBound.fill(1.6); upperBound.fill(2); LBestPSO s(64, lowerBound, upperBound); arma::mat coordinates = arma::mat("1; 0"); s.Optimize(f, coordinates); REQUIRE(coordinates(0) == Approx(0).margin(0.01)); REQUIRE(coordinates(1) == Approx(-1).margin(0.01)); } /** * Test the PSO optimizer on the Levi Function. */ TEST_CASE("LBestPSOLevyFunctionN13Test", "[PSOTest]") { LevyFunctionN13 f; // Setting bounds for the initial swarm population. arma::vec lowerBound(2); arma::vec upperBound(2); lowerBound.fill(-10); upperBound.fill(-9); LBestPSO s(64, lowerBound, upperBound); arma::mat coordinates = arma::mat("3; 3"); s.Optimize(f, coordinates); REQUIRE(coordinates(0) == Approx(1).margin(0.01)); REQUIRE(coordinates(1) == Approx(1).margin(0.01)); } /** * Test the PSO optimizer on the Himmelblau Function. */ TEST_CASE("LBestPSOHimmelblauFunctionTest", "[PSOTest]") { HimmelblauFunction f; // Setting bounds for the initial swarm population. arma::vec lowerBound(2); arma::vec upperBound(2); lowerBound.fill(0); upperBound.fill(1); LBestPSO s(64, lowerBound, upperBound); arma::mat coordinates = arma::mat("2; 1"); s.Optimize(f, coordinates); REQUIRE(coordinates(0) == Approx(3.0).margin(0.01)); REQUIRE(coordinates(1) == Approx(2.0).margin(0.01)); } /** * Test the PSO optimizer on the Three-hump Camel Function. */ TEST_CASE("LBestPSOThreeHumpCamelFunctionTest", "[PSOTest]") { ThreeHumpCamelFunction f; // Setting bounds for the initial swarm population. arma::vec lowerBound(2); arma::vec upperBound(2); lowerBound.fill(-5); upperBound.fill(-4); LBestPSO s(64, lowerBound, upperBound); arma::mat coordinates = arma::mat("2; 2"); s.Optimize(f, coordinates); REQUIRE(coordinates(0) == Approx(0).margin(0.01)); REQUIRE(coordinates(1) == Approx(0).margin(0.01)); } /** * Test the PSO optimizer on Schaffer Function N.2. */ TEST_CASE("LBestPSOSchafferFunctionN2Test", "[PSOTest]") { SchafferFunctionN2 f; // Setting bounds for the initial swarm population. arma::vec lowerBound(2); arma::vec upperBound(2); lowerBound.fill(40); upperBound.fill(50); LBestPSO s(500, lowerBound, upperBound); arma::mat coordinates = arma::mat("10; 10"); s.Optimize(f, coordinates); REQUIRE(coordinates(0) == Approx(0).margin(0.01)); REQUIRE(coordinates(1) == Approx(0).margin(0.01)); } // TODO: With future improvements in metaheuristic optimisers in ensmallen, // try to optimize this function. /** * Test the PSO optimizer on Schaffer function N.4. */ /* TEST_CASE("LBestPSOScafferFunctionN4Test", "[PSOTest]") { SchafferFunctionN4 f; // Setting bounds for the initial swarm population. arma::vec lowerBound(2); arma::vec upperBound(2); lowerBound.fill(-0.01); upperBound.fill(1.5); LBestPSO s(25000, lowerBound, upperBound, 4000, 40, 1e-40, 1.5, 1.0); arma::mat coordinates = arma::mat("0; 10"); const double result = s.Optimize(f, coordinates); REQUIRE(result == Approx(0.292579).margin(0.1)); REQUIRE(coordinates(0) == Approx(0).margin(0.1)); REQUIRE(abs(coordinates(1)) == Approx(1.25313).margin(0.1)); } */
26.617284
78
0.6875
walragatver
4fa461fad38e54f11567bd1adeb0c54ff6e448bf
1,187
cpp
C++
code/framework/src/integrations/server/networking/engine.cpp
MafiaHub/Framework
9514ef2a9ae8e95e100e415568b683d46e1ba709
[ "OpenSSL" ]
18
2021-09-17T16:41:14.000Z
2022-02-01T15:22:20.000Z
code/framework/src/integrations/server/networking/engine.cpp
MafiaHub/Framework
9514ef2a9ae8e95e100e415568b683d46e1ba709
[ "OpenSSL" ]
36
2021-09-21T10:22:16.000Z
2022-01-22T10:25:11.000Z
code/framework/src/integrations/server/networking/engine.cpp
MafiaHub/Framework
9514ef2a9ae8e95e100e415568b683d46e1ba709
[ "OpenSSL" ]
6
2021-09-26T11:06:32.000Z
2022-01-21T15:07:05.000Z
/* * MafiaHub OSS license * Copyright (c) 2022, MafiaHub. All rights reserved. * * This file comes from MafiaHub, hosted at https://github.com/MafiaHub/Framework. * See LICENSE file in the source repository for information regarding licensing. */ #include "engine.h" #include <logging/logger.h> namespace Framework::Integrations::Server::Networking { Engine::Engine() { _networkServer = std::make_unique<Framework::Networking::NetworkServer>(); } bool Engine::Init(int32_t port, std::string &host, int32_t maxPlayers, std::string &password) { if (_networkServer->Init(port, host, maxPlayers, password) != Framework::Networking::SERVER_NONE) { Framework::Logging::GetInstance()->Get(FRAMEWORK_INNER_SERVER)->critical("Failed to init the inner networking engine"); return false; } return true; } bool Engine::Shutdown() { if (_networkServer) { _networkServer->Shutdown(); } return true; } void Engine::Update() { if (_networkServer) { _networkServer->Update(); } } } // namespace Framework::Integrations::Server::Networking
29.675
131
0.648694
MafiaHub
4fa685fd477cf664517c5d8408e0281b0357f454
1,029
cpp
C++
BusinessCardVCard/BusinessCardVCard.cpp
jgamez118/SPRING2019-ITSE1307
63cb213e2ebd2888fc4f5e53b2037966fb55137a
[ "MIT" ]
null
null
null
BusinessCardVCard/BusinessCardVCard.cpp
jgamez118/SPRING2019-ITSE1307
63cb213e2ebd2888fc4f5e53b2037966fb55137a
[ "MIT" ]
null
null
null
BusinessCardVCard/BusinessCardVCard.cpp
jgamez118/SPRING2019-ITSE1307
63cb213e2ebd2888fc4f5e53b2037966fb55137a
[ "MIT" ]
null
null
null
// BusinessCardVCard.cpp : This file contains the 'main' function. Program execution begins and ends there. /* Jonathan Gamez ITSE-1307-002 2/20/19 */ // We have to include fstream #include "pch.h" #include <iostream> #include <fstream> using namespace std; int main() { // Use ofstream to output files. Used to create files and write information to files ofstream fileVCard; // Here we select the name and type of file then begin to send information to it for the bussiness card fileVCard.open("name.vcf"); fileVCard << "BEGIN:VCARD" << endl; fileVCard << "N:Business Card:JAG::" << endl; fileVCard << "FN:JAG Business Card" << endl; fileVCard << "TEL:CELL;VOICE:(210)-073-1985" << endl; fileVCard << "TEL:WORK;VOICE:(210)-214-2016" << endl; fileVCard << "ADR:TYPE;HOME;LABEL = 1010 King Court, TX 72345" << endl; fileVCard << "EMAIL:JohnG@gmail.com" << endl; fileVCard << "END:VCARD" << endl; // Here we end the file and then close it fileVCard.close(); return 0; }
27.078947
108
0.669582
jgamez118
4facb4c7facdf15d2433eccdbde2a34dc067f52f
18,874
cpp
C++
toonz/sources/toonz/matchlinecommand.cpp
areckx/opentoonz
a86fd8f80a1a07f97a8d230fda44fd1d6a7de576
[ "BSD-3-Clause" ]
1
2021-08-07T00:16:54.000Z
2021-08-07T00:16:54.000Z
toonz/sources/toonz/matchlinecommand.cpp
LibrePhone/opentoonz
cb95a29db4c47ab1f36a6e85a039c4c9c901f88a
[ "BSD-3-Clause" ]
null
null
null
toonz/sources/toonz/matchlinecommand.cpp
LibrePhone/opentoonz
cb95a29db4c47ab1f36a6e85a039c4c9c901f88a
[ "BSD-3-Clause" ]
1
2021-08-07T00:16:58.000Z
2021-08-07T00:16:58.000Z
// TnzCore includes #include "tsystem.h" #include "tundo.h" #include "tpalette.h" // TnzLib includes #include "toonz/toonzscene.h" #include "toonz/txshcell.h" #include "toonz/txshsimplelevel.h" #include "toonz/levelset.h" #include "toonz/hook.h" #include "toonz/levelproperties.h" #include "toonz/txshlevelhandle.h" #include "toonz/txsheethandle.h" #include "toonz/tscenehandle.h" // TnzQt includes #include "toonzqt/menubarcommand.h" // Tnz6 includes #include "tapp.h" #include "cellselection.h" #include "columnselection.h" #include "keyframeselection.h" #include "filmstripselection.h" #include "menubarcommandids.h" #include "columncommand.h" // Qt includes #include <QCoreApplication> #include <QPushButton> #include <QMainWindow> #include "matchline.h" //***************************************************************************** // MergeCmappedDialog implementation //***************************************************************************** void MergeCmappedDialog::accept() { m_levelPath = TFilePath(QString(m_saveInFileFld->getPath() + "\\" + m_fileNameFld->text() + ".tlv") .toStdString()); TFilePath fp = TApp::instance()->getCurrentScene()->getScene()->decodeFilePath( m_levelPath); if (TSystem::doesExistFileOrLevel(fp)) { if (DVGui::MsgBox( QObject::tr("Level ") + QString::fromStdWString(m_levelPath.getWideString()) + QObject::tr( " already exists! Are you sure you want to overwrite it?"), tr("Ok"), tr("Cancel")) != 1) return; else { TSystem::removeFileOrLevel(fp); TSystem::removeFileOrLevel(fp.withType("tpl")); } } Dialog::accept(); } //------------------------------------------------------------------------------ MergeCmappedDialog::MergeCmappedDialog(TFilePath &levelPath) : Dialog(TApp::instance()->getMainWindow(), true, true, "Merge Tlv") , m_levelPath(levelPath) { bool ret = true; QString path = QString::fromStdWString(m_levelPath.getParentDir().getWideString()); QString name = QString::fromStdString(m_levelPath.getName()); setWindowTitle(tr(" Merge Tlv Levels")); m_saveInFileFld = new DVGui::FileField(0, path); ret = ret && connect(m_saveInFileFld, SIGNAL(pathChanged()), this, SLOT(onPathChanged())); addWidget(tr("Save in:"), m_saveInFileFld); m_fileNameFld = new DVGui::LineEdit(name + "_merged"); m_fileNameFld->setMaximumHeight(DVGui::WidgetHeight); ret = ret && connect(m_fileNameFld, SIGNAL(editingFinished()), SLOT(onNameChanged())); addWidget(tr("File Name:"), m_fileNameFld); QPushButton *okBtn = new QPushButton(tr("Apply"), this); okBtn->setDefault(true); QPushButton *cancelBtn = new QPushButton(tr("Cancel"), this); connect(okBtn, SIGNAL(clicked()), this, SLOT(accept())); connect(cancelBtn, SIGNAL(clicked()), this, SLOT(reject())); addButtonBarWidget(okBtn, cancelBtn); } //***************************************************************************** // MergeColumns command //***************************************************************************** class MergeColumnsCommand final : public MenuItemHandler { public: MergeColumnsCommand() : MenuItemHandler(MI_MergeColumns) {} void execute() override { TColumnSelection *selection = dynamic_cast<TColumnSelection *>(TSelection::getCurrent()); std::set<int> indices = selection ? selection->getIndices() : std::set<int>(); if (indices.empty()) { DVGui::warning( tr("It is not possible to execute the merge column command because " "no column was selected.")); return; } if (indices.size() == 1) { DVGui::warning( tr("It is not possible to execute the merge column command because " "only one columns is selected.")); return; } mergeColumns(indices); TApp::instance()->getCurrentXsheet()->notifyXsheetChanged(); } } MergeColumnsCommand; //***************************************************************************** // ApplyMatchlines command //***************************************************************************** class ApplyMatchlinesCommand final : public MenuItemHandler { public: ApplyMatchlinesCommand() : MenuItemHandler(MI_ApplyMatchLines) {} void execute() override { TColumnSelection *selection = dynamic_cast<TColumnSelection *>(TSelection::getCurrent()); if (!selection) { DVGui::warning( tr("It is not possible to apply the match lines because no column " "was selected.")); return; } std::set<int> indices = selection->getIndices(); if (indices.size() != 2) { DVGui::warning( tr("It is not possible to apply the match lines because two columns " "have to be selected.")); return; } std::set<int>::iterator it = indices.begin(); int i = *it++, j = *it; doMatchlines(i, j, -1, -1); TApp::instance()->getCurrentXsheet()->notifyXsheetChanged(); } } ApplyMatchlinesCommand; //-------------------------------------------- namespace { bool checkColumnValidity(int column) { TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet(); int start, end; xsh->getCellRange(column, start, end); if (start > end) return false; std::vector<TXshCell> cell(end - start + 1); xsh->getCells(start, column, cell.size(), &(cell[0])); TXshSimpleLevel *level = 0; for (int i = 0; i < (int)cell.size(); i++) { if (cell[i].isEmpty()) continue; if (!level) level = cell[i].getSimpleLevel(); if (cell[i].getSimpleLevel()->getType() != TZP_XSHLEVEL) { DVGui::warning(QObject::tr( "Match lines can be applied to Toonz raster levels only.")); return false; } if (level != cell[i].getSimpleLevel()) { DVGui::warning( QObject::tr("It is not possible to merge tlv columns containing more " "than one level")); return false; } } if (!level) return false; if (!level->getPalette()) { DVGui::warning( QObject::tr("The level you are using has not a valid palette.")); return false; } return true; } //--------------------------------------------------------------------------------------------------------- void doCloneLevelNoSave(const TCellSelection::Range &range, const QString &newLevelName, bool withUndo); //----------------------------------------------------------------------------- namespace { //----------------------------------------------------------------------------- class CloneLevelNoSaveUndo final : public TUndo { std::map<TXshSimpleLevel *, TXshLevelP> m_createdLevels; std::set<int> m_insertedColumnIndices; TCellSelection::Range m_range; QString m_levelname; public: CloneLevelNoSaveUndo( const TCellSelection::Range &range, const std::map<TXshSimpleLevel *, TXshLevelP> &createdLevels, const std::set<int> &insertedColumnIndices, const QString &levelname) : m_createdLevels(createdLevels) , m_range(range) , m_insertedColumnIndices(insertedColumnIndices) , m_levelname(levelname) {} void undo() const override { TApp *app = TApp::instance(); ToonzScene *scene = app->getCurrentScene()->getScene(); TXsheet *xsh = scene->getXsheet(); int i; for (i = m_range.getColCount(); i > 0; i--) { int index = m_range.m_c1 + i; std::set<int>::const_iterator it = m_insertedColumnIndices.find(index); xsh->removeColumn(index); if (it == m_insertedColumnIndices.end()) xsh->insertColumn(index); } std::map<TXshSimpleLevel *, TXshLevelP>::const_iterator it = m_createdLevels.begin(); for (; it != m_createdLevels.end(); ++it) { it->second->addRef(); scene->getLevelSet()->removeLevel(it->second.getPointer()); } app->getCurrentXsheet()->notifyXsheetChanged(); } void redo() const override { doCloneLevelNoSave(m_range, m_levelname, false); } int getSize() const override { return sizeof *this + (sizeof(TXshLevelP) + sizeof(TXshSimpleLevel *)) * m_createdLevels.size(); } }; //----------------------------------------------------------------------------- } // namespace //----------------------------------------------------------------------------- void doCloneLevelNoSave(const TCellSelection::Range &range, const QString &newLevelName = QString(), bool withUndo = true) { std::map<TXshSimpleLevel *, TXshLevelP> createdLevels; TApp *app = TApp::instance(); TXsheet *xsh = app->getCurrentXsheet()->getXsheet(); ToonzScene *scene = app->getCurrentScene()->getScene(); // Build indices of inserted columns std::set<int> insertedColumnIndices; int c; for (c = 1; c <= range.getColCount(); ++c) { int colIndex = range.m_c1 + c; if (xsh->isColumnEmpty(colIndex)) continue; xsh->insertColumn(colIndex); insertedColumnIndices.insert(colIndex); } bool isOneCellCloned = false; for (c = range.m_c0; c <= range.m_c1; ++c) { TXshLevelP xl; TXshSimpleLevel *sl = 0; TFrameId fid(1); bool keepOldLevel = false; // OverwriteDialog* dialog = new OverwriteDialog(); for (int r = range.m_r0; r <= range.m_r1; ++r) { TXshCell cell = xsh->getCell(r, c); TImageP img = cell.getImage(true); if (!img) continue; fid = cell.getFrameId(); if (cell.getSimpleLevel() == 0 || cell.getSimpleLevel()->getPath().getType() == "psd") continue; std::map<TXshSimpleLevel *, TXshLevelP>::iterator it = createdLevels.find(cell.getSimpleLevel()); if (it == createdLevels.end()) { // Create a new level if not already done TXshSimpleLevel *oldSl = cell.getSimpleLevel(); { int levelType = oldSl->getType(); assert(levelType > 0); xl = scene->createNewLevel(levelType, newLevelName.toStdWString()); sl = xl->getSimpleLevel(); // if(levelType == OVL_XSHLEVEL) // dstPath = dstPath.withType(oldSl->getPath().getType()); assert(sl); // sl->setPath(scene->codeFilePath(dstPath)); // sl->setName(newName); sl->clonePropertiesFrom(oldSl); *sl->getHookSet() = *oldSl->getHookSet(); if (levelType == TZP_XSHLEVEL || levelType == PLI_XSHLEVEL) { TPalette *palette = oldSl->getPalette(); assert(palette); sl->setPalette(palette->clone()); } } createdLevels[cell.getSimpleLevel()] = xl; } else { xl = it->second; sl = xl->getSimpleLevel(); } TXshCell oldCell(cell); cell.m_level = xl; int k; for (k = range.m_r0; k < r; k++) { if (xsh->getCell(k, c).getImage(true).getPointer() == img.getPointer()) { TFrameId oldFid = xsh->getCell(k, c).getFrameId(); assert(fid == oldFid); sl->setFrame(fid, xsh->getCell(k, c + range.getColCount()).getImage(true)); break; } } if (!keepOldLevel && k >= r) { TImageP newImg(img->cloneImage()); assert(newImg); sl->setFrame(fid, newImg); } cell.m_frameId = fid; xsh->setCell(r, c + range.getColCount(), cell); isOneCellCloned = true; } if (sl) sl->getProperties()->setDirtyFlag(true); } // Se non e' stata inserita nessuna cella rimuovo le colonne aggiunte e // ritorno. if (!isOneCellCloned) { if (!insertedColumnIndices.empty()) { int i; for (i = range.getColCount(); i > 0; i--) { int index = range.m_c1 + i; std::set<int>::const_iterator it = insertedColumnIndices.find(index); xsh->removeColumn(index); } } return; } if (withUndo) TUndoManager::manager()->add(new CloneLevelNoSaveUndo( range, createdLevels, insertedColumnIndices, newLevelName)); app->getCurrentXsheet()->notifyXsheetChanged(); app->getCurrentScene()->setDirtyFlag(true); app->getCurrentScene()->notifyCastChange(); } void cloneColumn(const TCellSelection::Range &cells, const TFilePath &newLevelPath) { std::set<std::pair<int, int>> positions; for (int i = cells.m_r0; i <= cells.m_r1; i++) positions.insert(std::pair<int, int>(i, cells.m_c0)); TKeyframeSelection ks(positions); ks.copyKeyframes(); doCloneLevelNoSave(cells, QString::fromStdString(newLevelPath.getName() + "_")); ColumnCmd::deleteColumn(cells.m_c0); ks.pasteKeyframes(); } } // namespace class MergeCmappedCommand final : public MenuItemHandler { public: MergeCmappedCommand() : MenuItemHandler(MI_MergeCmapped) {} void execute() override { TColumnSelection *selection = dynamic_cast<TColumnSelection *>(TSelection::getCurrent()); if (!selection) { DVGui::warning( tr("It is not possible to merge tlv columns because no column was " "selected.")); return; } std::set<int> indices = selection->getIndices(); if (indices.size() < 2) { DVGui::warning( tr("It is not possible to merge tlv columns because at least two " "columns have to be selected.")); return; } std::set<int>::iterator it = indices.begin(); int destColumn = *it; TCellSelection::Range cells; cells.m_c0 = cells.m_c1 = destColumn; TXshColumn *column = TApp::instance()->getCurrentXsheet()->getXsheet()->getColumn( destColumn); column->getRange(cells.m_r0, cells.m_r1); // column->getLevelColumn() TFilePath newLevelPath; TXshCell c = TApp::instance()->getCurrentXsheet()->getXsheet()->getCell( cells.m_r0, destColumn); if (!c.isEmpty() && c.getSimpleLevel()) newLevelPath = c.getSimpleLevel()->getPath(); if (MergeCmappedDialog(newLevelPath).exec() != QDialog::Accepted) return; it = indices.begin(); for (; it != indices.end(); ++it) if (!checkColumnValidity(*it)) return; DVGui::ProgressDialog progress(tr("Merging Tlv Levels..."), QString(), 0, indices.size() - 1, TApp::instance()->getMainWindow()); progress.setWindowModality(Qt::WindowModal); progress.setWindowTitle(tr("Merging Tlv Levels...")); progress.setValue(0); progress.show(); QCoreApplication::instance()->processEvents(); TUndoManager::manager()->beginBlock(); cloneColumn(cells, newLevelPath); TFilePath tmpPath = newLevelPath.withName( QString::fromStdString(newLevelPath.getName() + "_tmp").toStdWString()); it = indices.begin(); ++it; for (int count = 0; it != indices.end();) { int index = *it; it++; mergeCmapped(destColumn, index - count, it == indices.end() ? newLevelPath.getQString() : tmpPath.getQString(), false); ColumnCmd::deleteColumn(index - count); progress.setValue(++count); QCoreApplication::instance()->processEvents(); } TUndoManager::manager()->endBlock(); TApp::instance()->getCurrentXsheet()->notifyXsheetChanged(); } } MergeCmappedCommand; //----------------------------------------------------------------------------- namespace { void doDeleteCommand(bool isMatchline) { TRect r; TCellSelection *sel = dynamic_cast<TCellSelection *>(TSelection::getCurrent()); if (!sel) { TFilmstripSelection *filmstripSelection = dynamic_cast<TFilmstripSelection *>(TSelection::getCurrent()); TColumnSelection *columnSelection = dynamic_cast<TColumnSelection *>(TSelection::getCurrent()); std::set<int> indices; std::set<TFrameId> fids; if (filmstripSelection && (fids = filmstripSelection->getSelectedFids()).size() > 0) { TXshSimpleLevel *sl = TApp::instance()->getCurrentLevel()->getSimpleLevel(); if (isMatchline) deleteMatchlines(sl, fids); else deleteInk(sl, fids); TApp::instance()->getCurrentXsheet()->notifyXsheetChanged(); return; } else if (!columnSelection || (indices = columnSelection->getIndices()).size() != 1) { DVGui::warning( QObject::tr("It is not possible to delete lines because no column, " "cell or level strip frame was selected.")); return; } int from, to; int columnIndex = *indices.begin(); TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet(); if (!xsh->getCellRange(*indices.begin(), from, to)) { DVGui::warning(QObject::tr("The selected column is empty.")); return; } r.y0 = from; r.y1 = to; r.x0 = r.x1 = columnIndex; } else sel->getSelectedCells(r.y0, r.x0, r.y1, r.x1); if (r.x0 != r.x1) { DVGui::warning(QObject::tr("Selected cells must be in the same column.")); return; } TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet(); int i; for (i = r.y0; i <= r.y1; i++) { TXshCell cell = xsh->getCell(i, r.x0); if (cell.isEmpty()) { DVGui::warning( QObject::tr("It is not possible to delete lines because no column, " "cell or level strip frame was selected.")); return; } if (cell.m_level->getType() != TZP_XSHLEVEL) { DVGui::warning(QObject::tr( "Match lines can be deleted from Toonz raster levels only")); return; } } std::set<TFrameId> fids; for (i = r.y0; i <= r.y1; i++) { const TXshCell &cell = xsh->getCell(i, r.x0); fids.insert(cell.getFrameId()); } TXshSimpleLevel *sl = xsh->getCell(r.y0, r.x0).getSimpleLevel(); assert(sl); if (isMatchline) deleteMatchlines(sl, fids); else deleteInk(sl, fids); TApp::instance()->getCurrentXsheet()->notifyXsheetChanged(); } } // namespace //----------------------------------------------------------------------------- class DeleteInkCommand final : public MenuItemHandler { public: DeleteInkCommand() : MenuItemHandler(MI_DeleteInk) {} void execute() override { doDeleteCommand(false); } } DeleteInkCommand; //----------------------------------------------------------------------------- class DeleteMatchlinesCommand final : public MenuItemHandler { public: DeleteMatchlinesCommand() : MenuItemHandler(MI_DeleteMatchLines) {} void execute() override { doDeleteCommand(true); } } DeleteMatchlinesCommand;
31.352159
107
0.576984
areckx
4fb15d392e82d584e89c654f2a962027b6d76402
7,272
cc
C++
src/developer/forensics/last_reboot/tests/main_service_unittest.cc
csrpi/fuchsia
2f015594dcb4c13aa51eee305ad561078f1f9b7f
[ "BSD-2-Clause" ]
3
2021-09-02T07:21:06.000Z
2022-03-12T03:20:10.000Z
src/developer/forensics/last_reboot/tests/main_service_unittest.cc
csrpi/fuchsia
2f015594dcb4c13aa51eee305ad561078f1f9b7f
[ "BSD-2-Clause" ]
null
null
null
src/developer/forensics/last_reboot/tests/main_service_unittest.cc
csrpi/fuchsia
2f015594dcb4c13aa51eee305ad561078f1f9b7f
[ "BSD-2-Clause" ]
2
2022-02-25T12:22:49.000Z
2022-03-12T03:20:10.000Z
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/developer/forensics/last_reboot/main_service.h" #include <lib/syslog/cpp/macros.h> #include <memory> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "src/developer/forensics/testing/stubs/cobalt_logger.h" #include "src/developer/forensics/testing/stubs/cobalt_logger_factory.h" #include "src/developer/forensics/testing/stubs/reboot_methods_watcher_register.h" #include "src/developer/forensics/testing/unit_test_fixture.h" #include "src/lib/files/file.h" #include "src/lib/files/path.h" #include "src/lib/files/scoped_temp_dir.h" namespace forensics { namespace last_reboot { namespace { using fuchsia::feedback::LastRebootInfoProviderSyncPtr; using inspect::testing::ChildrenMatch; using inspect::testing::NameMatches; using inspect::testing::NodeMatches; using inspect::testing::PropertyList; using inspect::testing::StringIs; using inspect::testing::UintIs; using testing::Contains; using testing::UnorderedElementsAreArray; class MainServiceTest : public UnitTestFixture { public: MainServiceTest() : main_service_(MainService::Config{ .dispatcher = dispatcher(), .services = services(), .root_node = &InspectRoot(), .reboot_log = RebootLog(RebootReason::kNotParseable, "", std::nullopt), .graceful_reboot_reason_write_path = Path(), }) {} protected: void SetUpRebootMethodsWatcherRegisterServer( std::unique_ptr<stubs::RebootMethodsWatcherRegisterBase> server) { reboot_watcher_register_server_ = std::move(server); if (reboot_watcher_register_server_) { InjectServiceProvider(reboot_watcher_register_server_.get()); } } std::string Path() { return files::JoinPath(tmp_dir_.path(), "graceful_reboot_reason.txt"); } private: files::ScopedTempDir tmp_dir_; std::unique_ptr<stubs::RebootMethodsWatcherRegisterBase> reboot_watcher_register_server_; protected: MainService main_service_; }; TEST_F(MainServiceTest, Check_RegistersRebootWatcher) { SetUpCobaltServer(std::make_unique<stubs::CobaltLoggerFactory>()); SetUpRebootMethodsWatcherRegisterServer(std::make_unique<stubs::RebootMethodsWatcherRegister>( fuchsia::hardware::power::statecontrol::RebootReason::USER_REQUEST)); RunLoopUntilIdle(); main_service_.WatchForImminentGracefulReboot(); RunLoopUntilIdle(); EXPECT_TRUE(files::IsFile(Path())); std::string reboot_reason_str; ASSERT_TRUE(files::ReadFileToString(Path(), &reboot_reason_str)); EXPECT_EQ(reboot_reason_str, "USER REQUEST"); } TEST_F(MainServiceTest, CheckInspect) { SetUpCobaltServer(std::make_unique<stubs::CobaltLoggerFactory>()); EXPECT_THAT( InspectTree(), ChildrenMatch(UnorderedElementsAreArray({ AllOf(NodeMatches(NameMatches("fidl")), ChildrenMatch(UnorderedElementsAreArray({ NodeMatches(AllOf(NameMatches("fuchsia.feedback.LastRebootInfoProvider"), PropertyList(UnorderedElementsAreArray({ UintIs("total_num_connections", 0u), UintIs("current_num_connections", 0u), })))), }))), }))); } TEST_F(MainServiceTest, LastRebootInfoProvider_CheckInspect) { SetUpCobaltServer(std::make_unique<stubs::CobaltLoggerFactory>()); LastRebootInfoProviderSyncPtr last_reboot_info_provider_1; main_service_.HandleLastRebootInfoProviderRequest(last_reboot_info_provider_1.NewRequest()); EXPECT_THAT( InspectTree(), ChildrenMatch(UnorderedElementsAreArray({ AllOf(NodeMatches(NameMatches("fidl")), ChildrenMatch(UnorderedElementsAreArray({ NodeMatches(AllOf(NameMatches("fuchsia.feedback.LastRebootInfoProvider"), PropertyList(UnorderedElementsAreArray({ UintIs("total_num_connections", 1u), UintIs("current_num_connections", 1u), })))), }))), }))); LastRebootInfoProviderSyncPtr last_reboot_info_provider_2; main_service_.HandleLastRebootInfoProviderRequest(last_reboot_info_provider_2.NewRequest()); EXPECT_THAT( InspectTree(), ChildrenMatch(UnorderedElementsAreArray({ AllOf(NodeMatches(NameMatches("fidl")), ChildrenMatch(UnorderedElementsAreArray({ NodeMatches(AllOf(NameMatches("fuchsia.feedback.LastRebootInfoProvider"), PropertyList(UnorderedElementsAreArray({ UintIs("total_num_connections", 2u), UintIs("current_num_connections", 2u), })))), }))), }))); last_reboot_info_provider_1.Unbind(); RunLoopUntilIdle(); EXPECT_THAT( InspectTree(), ChildrenMatch(UnorderedElementsAreArray({ AllOf(NodeMatches(NameMatches("fidl")), ChildrenMatch(UnorderedElementsAreArray({ NodeMatches(AllOf(NameMatches("fuchsia.feedback.LastRebootInfoProvider"), PropertyList(UnorderedElementsAreArray({ UintIs("total_num_connections", 2u), UintIs("current_num_connections", 1u), })))), }))), }))); LastRebootInfoProviderSyncPtr last_reboot_info_provider_3; main_service_.HandleLastRebootInfoProviderRequest(last_reboot_info_provider_3.NewRequest()); EXPECT_THAT( InspectTree(), ChildrenMatch(UnorderedElementsAreArray({ AllOf(NodeMatches(NameMatches("fidl")), ChildrenMatch(UnorderedElementsAreArray({ NodeMatches(AllOf(NameMatches("fuchsia.feedback.LastRebootInfoProvider"), PropertyList(UnorderedElementsAreArray({ UintIs("total_num_connections", 3u), UintIs("current_num_connections", 2u), })))), }))), }))); last_reboot_info_provider_2.Unbind(); last_reboot_info_provider_3.Unbind(); RunLoopUntilIdle(); EXPECT_THAT( InspectTree(), ChildrenMatch(UnorderedElementsAreArray({ AllOf(NodeMatches(NameMatches("fidl")), ChildrenMatch(UnorderedElementsAreArray({ NodeMatches(AllOf(NameMatches("fuchsia.feedback.LastRebootInfoProvider"), PropertyList(UnorderedElementsAreArray({ UintIs("total_num_connections", 3u), UintIs("current_num_connections", 0u), })))), }))), }))); } } // namespace } // namespace last_reboot } // namespace forensics
40.4
96
0.632288
csrpi
4fb32df1a76ee57e5e0db852d707791dc9015c47
10,496
cpp
C++
Chapter16-Policy-Based-Design/11_pack.cpp
shekerkamma/Hands-On-Design-Patterns-with-CPP
5f6aa05ac44491a92fef6e38179d1bd3c8e39347
[ "MIT" ]
1
2020-11-23T21:57:24.000Z
2020-11-23T21:57:24.000Z
Chapter16-Policy-Based-Design/11_pack.cpp
shekerkamma/Hands-On-Design-Patterns-with-CPP
5f6aa05ac44491a92fef6e38179d1bd3c8e39347
[ "MIT" ]
null
null
null
Chapter16-Policy-Based-Design/11_pack.cpp
shekerkamma/Hands-On-Design-Patterns-with-CPP
5f6aa05ac44491a92fef6e38179d1bd3c8e39347
[ "MIT" ]
1
2022-01-21T23:14:24.000Z
2022-01-21T23:14:24.000Z
// Variadic template policies #include <cstdlib> #include <iostream> using std::cin; using std::cout; using std::endl; template <typename T, typename V> struct ComparableSelf { friend bool operator==(V lhs, V rhs) { return lhs.get() == rhs.get(); } friend bool operator!=(V lhs, V rhs) { return lhs.get() != rhs.get(); } }; template <typename T, typename V> struct ComparableValue { friend bool operator==(V lhs, T rhs) { return lhs.get() == rhs; } friend bool operator==(T lhs, V rhs) { return lhs == rhs.get(); } friend bool operator!=(V lhs, T rhs) { return lhs.get() != rhs; } friend bool operator!=(T lhs, V rhs) { return lhs != rhs.get(); } }; template <typename T, typename V> struct Comparable : public ComparableSelf<T, V>, public ComparableValue<T, V> { }; template <typename T, typename V> struct AddSub { friend V operator+(V lhs, V rhs) { return V(lhs.get() + rhs.get()); } friend V operator+(V lhs, T rhs) { return V(lhs.get() + rhs); } friend V operator+(T lhs, V rhs) { return V(lhs + rhs.get()); } friend V operator-(V lhs, V rhs) { return V(lhs.get() - rhs.get()); } friend V operator-(V lhs, T rhs) { return V(lhs.get() - rhs); } friend V operator-(T lhs, V rhs) { return V(lhs - rhs.get()); } }; template <typename T, typename V> struct MulDiv { friend V operator*(V lhs, V rhs) { return V(lhs.get() * rhs.get()); } friend V operator*(V lhs, T rhs) { return V(lhs.get() * rhs); } friend V operator*(T lhs, V rhs) { return V(lhs * rhs.get()); } friend V operator/(V lhs, V rhs) { return V(lhs.get() / rhs.get()); } friend V operator/(V lhs, T rhs) { return V(lhs.get() / rhs); } friend V operator/(T lhs, V rhs) { return V(lhs / rhs.get()); } }; template <typename T, typename V> struct Incrementable { V operator++() { V& v = static_cast<V&>(*this); ++(v.get()); return v; } V operator++(int) { V& v = static_cast<V&>(*this); return V(v.get()++); } V operator--() { V& v = static_cast<V&>(*this); --(v.get()); return v; } V operator--(int) { V& v = static_cast<V&>(*this); return V(v.get()--); } V& operator+=(V val) { V& v = static_cast<V&>(*this); v.get() += val.get(); return v; } V& operator+=(T val) { V& v = static_cast<V&>(*this); v.get() += val; return v; } V& operator-=(V val) { V& v = static_cast<V&>(*this); v.get() -= val.get(); return v; } V& operator-=(T val) { V& v = static_cast<V&>(*this); v.get() -= val; return v; } }; template <typename T, typename V> struct ExplicitConvertible { explicit operator T() { return static_cast<V*>(this)->get(); } explicit operator const T() const { return static_cast<const V*>(this)->get(); } }; template <typename T, typename V> struct ImplicitConvertible { //typedef V::value_type value_type; // Does not work: Value is an incomplete type when its base class is instantiated operator T() { return static_cast<V*>(this)->get(); } operator const T() const { return static_cast<const V*>(this)->get(); } }; template <typename T, template <typename, typename> class... Policies> // "class" -> "typename" in C++17 class Value : public Policies<T, Value<T, Policies...>>... { public: typedef T value_type; explicit Value() : val_(T()) { } explicit Value(T v) : val_(v) { } Value(const Value& rhs) : val_(rhs.val_) { } Value& operator=(Value rhs) { val_ = rhs.val_; return *this; } Value& operator=(T rhs) { val_ = rhs; return *this; } friend std::ostream& operator<<(std::ostream& out, Value x) { out << x.val_; return out; } friend std::istream& operator>>(std::istream& in, Value& x) { in >> x.val_; return in; } T get() const { return val_; } T& get() { return val_; } template <typename U> using rebind_type = Value<U, Policies...>; private: // ??? friend class Policies<T, Value<T, Policies...>>...; T val_; }; #define ERROR12 int main() { if (1) { using V = Value<int>; V i; V j(5); V k(j); k = j; i = 3; cout << "i=" << i << endl; cin >> i; cout << "i=" << i << endl; #ifdef ERROR1 if (i == j) cout << "i==j" << endl; #endif #ifdef ERROR8 int x = i; #endif #ifdef ERROR9 int x(i); #endif } if (1) { using V = Value<int, ComparableSelf>; V i; V j(5); V k(j); if (i == j) cout << "i==j" << endl; if (i != j) cout << "i!=j" << endl; if (k == j) cout << "k==j" << endl; #ifdef ERROR2 if (k == 5) cout << "k==5" << endl; #endif } if (1) { using V = Value<int, ComparableValue>; V i; V j(5); V k(j); if (k == 5) cout << "k==5" << endl; if (5 == k) cout << "5==k" << endl; #ifdef ERROR3 if (i == j) cout << "i==j" << endl; #endif } if (1) { using V = Value<int, Comparable>; V i; V j(5); V k(j); if (i == j) cout << "i==j" << endl; if (i != j) cout << "i!=j" << endl; if (k == j) cout << "k==j" << endl; if (k == 5) cout << "k==5" << endl; if (5 == k) cout << "5==k" << endl; } if (1) { using V = Value<int, AddSub>; V i(3); V j(5); V k(i - j); k = i + j; cout << "k=" << k << endl; cout << "i + j - k=" << i + j - k << endl; #ifdef ERROR4 if (k == 5) cout << "k==5" << endl; #endif } if (1) { using V = Value<int, AddSub, Comparable>; V i(3); V j(5); V k(i - j); k = i + j; cout << "k=" << k << endl; cout << "i + j - k=" << i + j - k << endl; if (k == 5) cout << "k==5" << endl; if (i != j) cout << "i!=j" << endl; if (i - j != k) cout << "i - j != k" << endl; if (i - j != k + j) cout << "i - j != k + j" << endl; } if (1) { using V = Value<int, Comparable, AddSub>; V i(3); V j(5); V k(i - j); k = i + j; cout << "k=" << k << endl; cout << "i + j - k=" << i + j - k << endl; if (k == 5) cout << "k==5" << endl; if (i != j) cout << "i!=j" << endl; if (i - j != k) cout << "i - j != k" << endl; if (i - j != k + j) cout << "i - j != k + j" << endl; } if (1) { using V = Value<int, MulDiv>; V i(3); V j(5); V k(i / j); k = i * j; cout << "k=" << k << endl; cout << "i * j / k=" << i * j / k << endl; #ifdef ERROR5 if (k == 5) cout << "k==5" << endl; k = i + j; #endif } if (1) { using V = Value<int, MulDiv, AddSub>; V i(3); V j(5); V k(i / j); k = i * j; cout << "k=" << k << endl; cout << "i * j / k=" << i * j / k << endl; k = i + j; cout << "k=" << k << endl; cout << "i + j - k=" << i + j - k << endl; cout << "(i + j) * (k - i)" << (i + j) * (k - i) << endl; cout << "(i * j) + (k / i)" << (i * j) + (k / i) << endl; #ifdef ERROR6 if (k == 5) cout << "k==5" << endl; #endif } if (1) { using V = Value<int, AddSub, MulDiv>; V i(3); V j(5); V k(i / j); k = i * j; cout << "k=" << k << endl; cout << "i * j / k=" << i * j / k << endl; k = i + j; cout << "k=" << k << endl; cout << "i + j - k=" << i + j - k << endl; cout << "(i + j) * (k - i)" << (i + j) * (k - i) << endl; cout << "(i * j) + (k / i)" << (i * j) + (k / i) << endl; #ifdef ERROR7 if (k == 5) cout << "k==5" << endl; #endif } if (1) { using V = Value<int, Comparable, AddSub, MulDiv>; V i(3); V j(5); V k(i / j); k = i * j; cout << "k=" << k << endl; cout << "i * j / k=" << i * j / k << endl; k = i + j; cout << "k=" << k << endl; cout << "i + j - k=" << i + j - k << endl; if (k == 5) cout << "k==5" << endl; if (i != j) cout << "i!=j" << endl; if (i - j != k) cout << "i - j != k" << endl; if (i - j != k * j) cout << "i - j != k * j" << endl; } if (1) { using V = Value<int, Incrementable>; V i(3); V j(5); V k(i++); cout << "++i=" << ++i << endl; cout << "i=" << i << endl; cout << "k=" << k << endl; j += i; cout << "j=" << j << endl; j += 3; cout << "j=" << j << endl; k -= 4; cout << "k=" << k << endl; k -= j; cout << "k=" << k << endl; j--; cout << "j=" << k << endl; } if (1) { using V = Value<int, ExplicitConvertible>; V i(3); int j(i); cout << "i=" << i << " j=" << j << endl; #ifdef ERROR10 int x = i; #endif } if (1) { using V = Value<int, ImplicitConvertible>; V i(3); int j(i); int k = i; cout << "i=" << i << " j=" << j << " k=" << k << endl; } if (1) { using V0 = Value<int, Comparable, AddSub, MulDiv>; using V = V0::rebind_type<double>; V i(3); V j(5); V k(i / j); cout << "k=" << k << endl; k = i * j; cout << "k=" << k << endl; cout << "i * j / k=" << i * j / k << endl; k = i + j; cout << "k=" << k << endl; cout << "i + j - k=" << i + j - k << endl; if (k == 5) cout << "k==5" << endl; if (i != j) cout << "i!=j" << endl; if (i - j != k) cout << "i - j != k" << endl; if (i - j != k * j) cout << "i - j != k * j" << endl; #ifdef ERROR11 ++i; #endif } }
25.050119
121
0.403106
shekerkamma
4fba518be24ecce0257377d7484b45362b517e9a
2,547
cc
C++
io/example/zero-source1/zero-source1.cc
diegows/wanproxy
c0ad933f7ca5ba44bafb7f44f25c4e720375ff14
[ "BSD-2-Clause" ]
3
2015-04-27T06:20:12.000Z
2019-03-08T11:41:39.000Z
io/example/zero-source1/zero-source1.cc
diegows/wanproxy
c0ad933f7ca5ba44bafb7f44f25c4e720375ff14
[ "BSD-2-Clause" ]
1
2015-02-13T22:00:57.000Z
2015-02-13T22:00:57.000Z
io/example/zero-source1/zero-source1.cc
diegows/wanproxy
c0ad933f7ca5ba44bafb7f44f25c4e720375ff14
[ "BSD-2-Clause" ]
4
2015-08-31T09:50:58.000Z
2019-06-11T08:21:28.000Z
/* * Copyright (c) 2010-2011 Juli Mallett. 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. * * THIS SOFTWARE IS PROVIDED BY AUTHOR 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 AUTHOR 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 <unistd.h> #include <event/event_callback.h> #include <event/event_main.h> #include <io/stream_handle.h> static Buffer zero_buffer; class Source { LogHandle log_; StreamHandle fd_; Action *action_; public: Source(int fd) : log_("/source"), fd_(fd), action_(NULL) { Buffer tmp(zero_buffer); EventCallback *cb = callback(this, &Source::write_complete); action_ = fd_.write(&tmp, cb); } ~Source() { ASSERT(log_, action_ == NULL); } void write_complete(Event e) { action_->cancel(); action_ = NULL; switch (e.type_) { case Event::Done: case Event::Error: break; default: HALT(log_) << "Unexpected event: " << e; return; } if (e.type_ == Event::Error) { SimpleCallback *cb = callback(this, &Source::close_complete); action_ = fd_.close(cb); return; } Buffer tmp(zero_buffer); EventCallback *cb = callback(this, &Source::write_complete); action_ = fd_.write(&tmp, cb); } void close_complete(void) { action_->cancel(); action_ = NULL; } }; int main(void) { static uint8_t zbuf[65536]; memset(zbuf, 0, sizeof zbuf); zero_buffer.append(zbuf, sizeof zbuf); Source source(STDOUT_FILENO); event_main(); }
25.47
77
0.715744
diegows
4fbb558aeeb0ff9ff132bfcd7bb1b996954ca55d
24,513
cpp
C++
src/caffe/test/test_math_functions.cpp
alemagnani/caffe
9dfd7e44a452800566260d8b6f9bc27a29a34d76
[ "BSD-2-Clause" ]
2
2015-12-02T09:51:57.000Z
2016-05-03T09:34:30.000Z
src/caffe/test/test_math_functions.cpp
alemagnani/caffe
9dfd7e44a452800566260d8b6f9bc27a29a34d76
[ "BSD-2-Clause" ]
null
null
null
src/caffe/test/test_math_functions.cpp
alemagnani/caffe
9dfd7e44a452800566260d8b6f9bc27a29a34d76
[ "BSD-2-Clause" ]
null
null
null
#include <stdint.h> // for uint32_t & uint64_t #include <time.h> #include <climits> #include <cmath> // for std::fabs #include <cstdlib> // for rand_r #include <vector> #include "gtest/gtest.h" #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/filler.hpp" #include "caffe/util/benchmark.hpp" #include "caffe/util/math_functions.hpp" #include "caffe/test/test_caffe_main.hpp" namespace caffe { template<typename Dtype> class MathFunctionsTest : public ::testing::Test { protected: MathFunctionsTest() : blob_bottom_(new Blob<Dtype>()), blob_top_(new Blob<Dtype>()) { } virtual void SetUp() { Caffe::set_random_seed(1701); this->blob_bottom_->Reshape(11, 17, 19, 23); this->blob_top_->Reshape(11, 17, 19, 23); // fill the values FillerParameter filler_param; GaussianFiller<Dtype> filler(filler_param); filler.Fill(this->blob_bottom_); filler.Fill(this->blob_top_); } virtual ~MathFunctionsTest() { delete blob_bottom_; delete blob_top_; } // http://en.wikipedia.org/wiki/Hamming_distance int ReferenceHammingDistance(const int n, const Dtype* x, const Dtype* y) { int dist = 0; uint64_t val; for (int i = 0; i < n; ++i) { if (sizeof(Dtype) == 8) { val = static_cast<uint64_t>(x[i]) ^ static_cast<uint64_t>(y[i]); } else if (sizeof(Dtype) == 4) { val = static_cast<uint32_t>(x[i]) ^ static_cast<uint32_t>(y[i]); } else { LOG(FATAL) << "Unrecognized Dtype size: " << sizeof(Dtype); } // Count the number of set bits while (val) { ++dist; val &= val - 1; } } return dist; } Blob<Dtype>* const blob_bottom_; Blob<Dtype>* const blob_top_; }; TYPED_TEST_CASE(MathFunctionsTest, TestDtypes); TYPED_TEST(MathFunctionsTest, TestNothing) { // The first test case of a test suite takes the longest time // due to the set up overhead. } TYPED_TEST(MathFunctionsTest, TestHammingDistanceCPU) { int n = this->blob_bottom_->count(); const TypeParam* x = this->blob_bottom_->cpu_data(); const TypeParam* y = this->blob_top_->cpu_data(); EXPECT_EQ(this->ReferenceHammingDistance(n, x, y), caffe_cpu_hamming_distance<TypeParam>(n, x, y)); } TYPED_TEST(MathFunctionsTest, TestAsumCPU) { int n = this->blob_bottom_->count(); const TypeParam* x = this->blob_bottom_->cpu_data(); TypeParam std_asum = 0; for (int i = 0; i < n; ++i) { std_asum += std::fabs(x[i]); } TypeParam cpu_asum = caffe_cpu_asum<TypeParam>(n, x); EXPECT_LT((cpu_asum - std_asum) / std_asum, 1e-2); } TYPED_TEST(MathFunctionsTest, TestSignCPU) { int n = this->blob_bottom_->count(); const TypeParam* x = this->blob_bottom_->cpu_data(); caffe_cpu_sign<TypeParam>(n, x, this->blob_bottom_->mutable_cpu_diff()); const TypeParam* signs = this->blob_bottom_->cpu_diff(); for (int i = 0; i < n; ++i) { EXPECT_EQ(signs[i], x[i] > 0 ? 1 : (x[i] < 0 ? -1 : 0)); } } TYPED_TEST(MathFunctionsTest, TestSgnbitCPU) { int n = this->blob_bottom_->count(); const TypeParam* x = this->blob_bottom_->cpu_data(); caffe_cpu_sgnbit<TypeParam>(n, x, this->blob_bottom_->mutable_cpu_diff()); const TypeParam* signbits = this->blob_bottom_->cpu_diff(); for (int i = 0; i < n; ++i) { EXPECT_EQ(signbits[i], x[i] < 0 ? 1 : 0); } } TYPED_TEST(MathFunctionsTest, TestFabsCPU) { int n = this->blob_bottom_->count(); const TypeParam* x = this->blob_bottom_->cpu_data(); caffe_abs<TypeParam>(n, x, this->blob_bottom_->mutable_cpu_diff()); const TypeParam* abs_val = this->blob_bottom_->cpu_diff(); for (int i = 0; i < n; ++i) { EXPECT_EQ(abs_val[i], x[i] > 0 ? x[i] : -x[i]); } } TYPED_TEST(MathFunctionsTest, TestScaleCPU) { int n = this->blob_bottom_->count(); TypeParam alpha = this->blob_bottom_->cpu_diff()[caffe_rng_rand() % this->blob_bottom_->count()]; caffe_cpu_scale<TypeParam>(n, alpha, this->blob_bottom_->cpu_data(), this->blob_bottom_->mutable_cpu_diff()); const TypeParam* scaled = this->blob_bottom_->cpu_diff(); const TypeParam* x = this->blob_bottom_->cpu_data(); for (int i = 0; i < n; ++i) { EXPECT_EQ(scaled[i], x[i] * alpha); } } TYPED_TEST(MathFunctionsTest, TestCopyCPU) { const int n = this->blob_bottom_->count(); const TypeParam* bottom_data = this->blob_bottom_->cpu_data(); TypeParam* top_data = this->blob_top_->mutable_cpu_data(); Caffe::set_mode(Caffe::CPU); caffe_copy(n, bottom_data, top_data); for (int i = 0; i < n; ++i) { EXPECT_EQ(bottom_data[i], top_data[i]); } } #ifndef CPU_ONLY // TODO: Fix caffe_gpu_hamming_distance and re-enable this test. TYPED_TEST(MathFunctionsTest, DISABLED_TestHammingDistanceGPU) { int n = this->blob_bottom_->count(); const TypeParam* x = this->blob_bottom_->cpu_data(); const TypeParam* y = this->blob_top_->cpu_data(); int reference_distance = this->ReferenceHammingDistance(n, x, y); x = this->blob_bottom_->gpu_data(); y = this->blob_top_->gpu_data(); int computed_distance = caffe_gpu_hamming_distance<TypeParam>(n, x, y); EXPECT_EQ(reference_distance, computed_distance); } TYPED_TEST(MathFunctionsTest, TestAsumGPU) { int n = this->blob_bottom_->count(); const TypeParam* x = this->blob_bottom_->cpu_data(); TypeParam std_asum = 0; for (int i = 0; i < n; ++i) { std_asum += std::fabs(x[i]); } TypeParam gpu_asum; caffe_gpu_asum<TypeParam>(n, this->blob_bottom_->gpu_data(), &gpu_asum); EXPECT_LT((gpu_asum - std_asum) / std_asum, 1e-2); } TYPED_TEST(MathFunctionsTest, TestSignGPU) { int n = this->blob_bottom_->count(); caffe_gpu_sign<TypeParam>(n, this->blob_bottom_->gpu_data(), this->blob_bottom_->mutable_gpu_diff()); const TypeParam* signs = this->blob_bottom_->cpu_diff(); const TypeParam* x = this->blob_bottom_->cpu_data(); for (int i = 0; i < n; ++i) { EXPECT_EQ(signs[i], x[i] > 0 ? 1 : (x[i] < 0 ? -1 : 0)); } } TYPED_TEST(MathFunctionsTest, TestSgnbitGPU) { int n = this->blob_bottom_->count(); caffe_gpu_sgnbit<TypeParam>(n, this->blob_bottom_->gpu_data(), this->blob_bottom_->mutable_gpu_diff()); const TypeParam* signbits = this->blob_bottom_->cpu_diff(); const TypeParam* x = this->blob_bottom_->cpu_data(); for (int i = 0; i < n; ++i) { EXPECT_EQ(signbits[i], x[i] < 0 ? 1 : 0); } } TYPED_TEST(MathFunctionsTest, TestFabsGPU) { int n = this->blob_bottom_->count(); caffe_gpu_abs<TypeParam>(n, this->blob_bottom_->gpu_data(), this->blob_bottom_->mutable_gpu_diff()); const TypeParam* abs_val = this->blob_bottom_->cpu_diff(); const TypeParam* x = this->blob_bottom_->cpu_data(); for (int i = 0; i < n; ++i) { EXPECT_EQ(abs_val[i], x[i] > 0 ? x[i] : -x[i]); } } TYPED_TEST(MathFunctionsTest, TestScaleGPU) { int n = this->blob_bottom_->count(); TypeParam alpha = this->blob_bottom_->cpu_diff()[caffe_rng_rand() % this->blob_bottom_->count()]; caffe_gpu_scale<TypeParam>(n, alpha, this->blob_bottom_->gpu_data(), this->blob_bottom_->mutable_gpu_diff()); const TypeParam* scaled = this->blob_bottom_->cpu_diff(); const TypeParam* x = this->blob_bottom_->cpu_data(); for (int i = 0; i < n; ++i) { EXPECT_EQ(scaled[i], x[i] * alpha); } } TYPED_TEST(MathFunctionsTest, TestCopyGPU) { const int n = this->blob_bottom_->count(); const TypeParam* bottom_data = this->blob_bottom_->gpu_data(); TypeParam* top_data = this->blob_top_->mutable_gpu_data(); Caffe::set_mode(Caffe::GPU); caffe_copy(n, bottom_data, top_data); bottom_data = this->blob_bottom_->cpu_data(); top_data = this->blob_top_->mutable_cpu_data(); for (int i = 0; i < n; ++i) { EXPECT_EQ(bottom_data[i], top_data[i]); } } #endif template<typename Dtype> class CsrFunctionsGenTest : public ::testing::Test { protected: CsrFunctionsGenTest() : A_(), indices_(), ptr_(), B_(), C_(), M(0), N(0), K(0), NZZ(0), PTR_SIZE(0), TransA(CblasNoTrans), TransB(CblasNoTrans), alpha(1.0), beta(0.0), orderC(CblasRowMajor) { } virtual void SetUp(int m, int n, int k, int nzz, int ptr_size) { M = m; N = n; K = k; NZZ = nzz; PTR_SIZE = ptr_size; A_.reset(new SyncedMemory(nzz * sizeof(Dtype))); indices_.reset(new SyncedMemory(nzz * sizeof(int))); ptr_.reset(new SyncedMemory(ptr_size * sizeof(int))); B_.reset(new SyncedMemory(K * N * sizeof(Dtype))); C_.reset(new SyncedMemory(M * N * sizeof(Dtype))); } virtual void run(bool isCpu, int times = 1) { if (isCpu) { Timer timer; timer.Start(); for (int t = 0; t < times; t++) { caffe_cpu_csr_gemm(TransA, TransB, M, N, K, alpha, NZZ, cpu_A(), cpu_indices(), cpu_ptr(), cpu_B(), beta, cpu_C(), orderC); } std::cout << "Total Time for CSR CPU gemm M:" << M << " N: " << N << " K: " << K << " transA: " << TransA << " transB: " << TransB << " orderC: " << orderC << " equal to " << (timer.MilliSeconds() / times) << " milli seconds.. Time per M ops: " << timer.MilliSeconds() / (times * NZZ * N / 1e6) << " milli seconds\n"; } else { #ifndef CPU_ONLY Dtype* agpu = gpu_A(); int* indicesgpu = gpu_indices(); int* ptrgpu = gpu_ptr(); Dtype* bgpu = gpu_B(); Dtype* cgpu = gpu_C(); Timer timer; timer.Start(); for (int t = 0; t < times; t++) { caffe_gpu_csr_gemm(TransA, TransB, M, N, K, alpha, NZZ, agpu, indicesgpu, ptrgpu, bgpu, beta, cgpu, orderC); } cudaDeviceSynchronize(); std::cout << "Total Time for CSR GPU gemm M:" << M << " N: " << N << " K: " << K << " transA: " << TransA << " transB: " << TransB << " orderC: " << orderC << " equal to " << (timer.MilliSeconds() / times) << " milli seconds. Time per M ops: " << timer.MilliSeconds() / (times * NZZ * N / 1e6) << " milli seconds\n"; #else #endif } } void setA(Dtype A_data[], int A_indices[], int A_ptr[]) { Dtype* am = cpu_A(); int* aindices = cpu_indices(); int* aptr = cpu_ptr(); for (int i = 0; i < NZZ; i++) { am[i] = A_data[i]; aindices[i] = A_indices[i]; } for (int i = 0; i < PTR_SIZE; i++) { aptr[i] = A_ptr[i]; } } void setB(Dtype B_data[]) { Dtype* bm = cpu_B(); for (int i = 0; i < (K * N); i++) { bm[i] = B_data[i]; } } void setC(Dtype C_data[]) { Dtype* cm = cpu_C(); for (int i = 0; i < (M * N); i++) { cm[i] = C_data[i]; } } void checkC(Dtype C_check[]) { Dtype* cm = cpu_C(); for (int i = 0; i < (M * N); i++) { EXPECT_EQ(cm[i], C_check[i]); } } Dtype* cpu_A() { CHECK(A_); return reinterpret_cast<Dtype*>(A_->mutable_cpu_data()); } Dtype* gpu_A() { CHECK(A_); return reinterpret_cast<Dtype*>(A_->mutable_gpu_data()); } Dtype* cpu_B() { CHECK(B_); return reinterpret_cast<Dtype*>(B_->mutable_cpu_data()); } Dtype* gpu_B() { CHECK(B_); return reinterpret_cast<Dtype*>(B_->mutable_gpu_data()); } Dtype* cpu_C() { CHECK(C_); return reinterpret_cast<Dtype*>(C_->mutable_cpu_data()); } Dtype* gpu_C() { CHECK(C_); return reinterpret_cast<Dtype*>(C_->mutable_gpu_data()); } int* cpu_indices() { CHECK(indices_); return reinterpret_cast<int*>(indices_->mutable_cpu_data()); } int* gpu_indices() { CHECK(indices_); return reinterpret_cast<int*>(indices_->mutable_gpu_data()); } int* cpu_ptr() { CHECK(ptr_); return reinterpret_cast<int*>(ptr_->mutable_cpu_data()); } int* gpu_ptr() { CHECK(ptr_); return reinterpret_cast<int*>(ptr_->mutable_gpu_data()); } void random_csr(int M, int N, int nzz_per_row, Dtype* A, int* indices, int* ptr) { srand(0); ptr[0] = 0; for (int row = 0; row < M; row++) { ptr[row+1] = nzz_per_row * (row+1); for (int pos = 0; pos < nzz_per_row; pos++) { int col = caffe_rng_rand() % N; indices[row * nzz_per_row + pos] = col; A[row * nzz_per_row + pos] = static_cast <Dtype> (caffe_rng_rand()) / static_cast <Dtype> (RAND_MAX); } } } void random_fill(int size, Dtype* X) { srand(0); for (int pos = 0; pos < size; pos++) { X[pos] = static_cast<Dtype>(caffe_rng_rand()) / static_cast<Dtype>(RAND_MAX); } } void test_speed_forward(int batch_size, int features, int nzz_per_row, int classes) { Dtype* A = new Dtype[batch_size * nzz_per_row]; int* indices = new int[batch_size * nzz_per_row]; int* ptr = new int[batch_size + 1]; Dtype* B = new Dtype[features * classes]; Dtype* C = new Dtype[batch_size * classes]; this->random_csr(batch_size, features, nzz_per_row, A, indices, ptr); this->random_fill(features * classes, B); this->random_fill(batch_size * classes, C); this->alpha = 1.0; this->beta = 1.0; this->SetUp(batch_size, classes, features, batch_size * nzz_per_row, batch_size + 1); this->TransA = CblasNoTrans; this->TransB = CblasTrans; this->orderC = CblasRowMajor; this->setA(A, indices, ptr); this->setB(B); this->setC(C); this->run(true, 100); this->setC(C); #ifndef CPU_ONLY this->run(false, 100); #else #endif delete A; delete indices; delete ptr; delete B; delete C; } void test_speed_backward(int batch_size, int features, int nzz_per_row, int classes) { Dtype* A = new Dtype[batch_size * nzz_per_row]; int* indices = new int[batch_size * nzz_per_row]; int* ptr = new int[batch_size + 1]; Dtype* B = new Dtype[batch_size * classes]; Dtype* C = new Dtype[features * classes]; this->random_csr(batch_size, features, nzz_per_row, A, indices, ptr); this->random_fill(batch_size * classes, B); this->random_fill(features * classes, C); this->alpha = 1.0; this->beta = 1.0; this->SetUp(features, classes, batch_size, batch_size * nzz_per_row, batch_size + 1); this->TransA = CblasTrans; this->TransB = CblasNoTrans; this->orderC = CblasColMajor; this->setA(A, indices, ptr); this->setB(B); this->setC(C); this->run(true, 100); this->setC(C); #ifndef CPU_ONLY this->run(false, 100); #else #endif delete A; delete indices; delete ptr; delete B; delete C; } shared_ptr<SyncedMemory> A_; shared_ptr<SyncedMemory> indices_; shared_ptr<SyncedMemory> ptr_; shared_ptr<SyncedMemory> B_; shared_ptr<SyncedMemory> C_; int M; int N; int K; int NZZ; int PTR_SIZE; CBLAS_TRANSPOSE TransA; CBLAS_TRANSPOSE TransB; Dtype alpha; Dtype beta; CBLAS_ORDER orderC; }; typedef ::testing::Types<float, double> Dtypes; TYPED_TEST_CASE(CsrFunctionsGenTest, Dtypes); TYPED_TEST(CsrFunctionsGenTest, TestCsrGemm1) { TypeParam A[] = {1.0, 2.0, 3.0}; int indices[] = {0, 2, 1}; int ptr[] = {0, 2, 3}; TypeParam B[] = {4.0, 7.0, 5.0, 8.0, 6.0, 9.0}; TypeParam C[] = {0.0, 0.0, 0.0, 0.0}; TypeParam CCheck[] = {16.0, 25.0, 15.0, 24.0}; this->alpha = 1.0; this->beta = 1.0; this->SetUp(2, 2, 3, 3, 3); this->setA(A, indices, ptr); this->setB(B); this->setC(C); this->run(true); this->checkC(CCheck); this->setC(C); #ifndef CPU_ONLY this->run(false); this->checkC(CCheck); #else #endif } TYPED_TEST(CsrFunctionsGenTest, TestCsrGemm2) { TypeParam A[] = {1.0, 2.0, 3.0}; int indices[] = {0, 2, 1}; int ptr[] = {0, 2, 3}; TypeParam B[] = {4.0, 7.0, 5.0, 8.0, 6.0, 9.0}; TypeParam C[] = {1.0, 2.0, 3.0, 4.0}; TypeParam CCheck[] = {17.0, 27.0, 18.0, 28.0}; this->alpha = 1.0; this->beta = 1.0; this->SetUp(2, 2, 3, 3, 3); this->TransA = CblasNoTrans; this->TransB = CblasNoTrans; this->orderC = CblasRowMajor; this->setA(A, indices, ptr); this->setB(B); this->setC(C); this->run(true); this->checkC(CCheck); this->setC(C); #ifndef CPU_ONLY this->run(false); this->checkC(CCheck); #else #endif } TYPED_TEST(CsrFunctionsGenTest, TestCsrGemm3) { TypeParam A[] = {1.0, 2.0, 3.0}; int indices[] = {0, 2, 1}; int ptr[] = {0, 2, 3}; TypeParam B[] = {4.0, 7.0, 5.0, 8.0, 6.0, 9.0}; TypeParam C[] = {1.0, 2.3, 3.0, 4.0}; TypeParam CCheck[] = {16.0, 25.0, 15.0, 24.0}; this->alpha = 1.0; this->beta = 0.0; this->SetUp(2, 2, 3, 3, 3); this->setA(A, indices, ptr); this->setB(B); this->setC(C); this->run(true); this->checkC(CCheck); this->setC(C); #ifndef CPU_ONLY this->run(false); this->checkC(CCheck); #else #endif } TYPED_TEST(CsrFunctionsGenTest, TestCsrGemm4) { TypeParam A[] = {1.0, 2.0, 3.0}; int indices[] = {0, 2, 1}; int ptr[] = {0, 2, 3}; TypeParam B[] = {4.0, 7.0, 5.0, 8.0, 6.0, 9.0}; TypeParam C[] = {0.0, 0.0, 0.0, 0.0}; TypeParam CCheck[] = {16.0, 15.0, 25.0, 24.0}; this->alpha = 1.0; this->beta = 1.0; this->SetUp(2, 2, 3, 3, 3); this->TransA = CblasNoTrans; this->TransB = CblasNoTrans; this->orderC = CblasColMajor; this->setA(A, indices, ptr); this->setB(B); this->setC(C); this->run(true); this->checkC(CCheck); this->setC(C); #ifndef CPU_ONLY this->run(false); this->checkC(CCheck); #else #endif } TYPED_TEST(CsrFunctionsGenTest, TestCsrGemm5) { TypeParam A[] = {1.0, 2.0, 3.0}; int indices[] = {0, 2, 1}; int ptr[] = {0, 2, 3}; TypeParam B[] = {4.0, 7.0, 5.0, 8.0, 6.0, 9.0}; TypeParam C[] = {1.0, 2.0, 0.0, 0.0}; TypeParam CCheck[] = {17.0, 17.0, 25.0, 24.0}; this->alpha = 1.0; this->beta = 1.0; this->SetUp(2, 2, 3, 3, 3); this->TransA = CblasNoTrans; this->TransB = CblasNoTrans; this->orderC = CblasColMajor; this->setA(A, indices, ptr); this->setB(B); this->setC(C); this->run(true); this->checkC(CCheck); this->setC(C); #ifndef CPU_ONLY this->run(false); this->checkC(CCheck); #else #endif } TYPED_TEST(CsrFunctionsGenTest, TestCsrGemm6) { TypeParam A[] = {1.0, 2.0, 3.0}; int indices[] = {0, 2, 1}; int ptr[] = {0, 2, 3}; TypeParam B[] = {4.0, 7.0, 5.0, 8.0, 6.0, 9.0}; TypeParam C[] = {1.0, 2.0, 3.0, 0.0}; TypeParam CCheck[] = {16.0, 15.0, 25.0, 24.0}; this->alpha = 1.0; this->beta = 0.0; this->SetUp(2, 2, 3, 3, 3); this->TransA = CblasNoTrans; this->TransB = CblasNoTrans; this->orderC = CblasColMajor; this->setA(A, indices, ptr); this->setB(B); this->setC(C); this->run(true); this->checkC(CCheck); this->setC(C); #ifndef CPU_ONLY this->run(false); this->checkC(CCheck); #else #endif } TYPED_TEST(CsrFunctionsGenTest, TestCsrGemm7) { TypeParam A[] = {1.0, 2.0, 3.0}; int indices[] = {0, 2, 1}; int ptr[] = {0, 2, 3}; TypeParam B[] = {4.0, 7.0, 5.0, 8.0, 6.0, 9.0}; TypeParam C[] = {0.0, 0.0, 0.0, 0.0}; TypeParam CCheck[] = {32.0, 50.0, 30.0, 48.0}; this->alpha = 2.0; this->beta = 1.0; this->SetUp(2, 2, 3, 3, 3); this->setA(A, indices, ptr); this->setB(B); this->setC(C); this->run(true); this->checkC(CCheck); this->setC(C); #ifndef CPU_ONLY this->run(false); this->checkC(CCheck); #else #endif } TYPED_TEST(CsrFunctionsGenTest, TestCsrGemm8) { TypeParam A[] = {1.0, 2.0, 3.0}; int indices[] = {0, 2, 1}; int ptr[] = {0, 2, 3}; TypeParam B[] = {4.0, 7.0, 5.0, 8.0, 6.0, 9.0}; TypeParam C[] = {1.0, 2.0, 3.0, 0.0}; TypeParam CCheck[] = {31.0, 58.0, 51.0, 36.0}; this->alpha = 2.0; this->beta = 3.0; this->SetUp(2, 2, 3, 3, 3); this->TransA = CblasNoTrans; this->TransB = CblasTrans; this->orderC = CblasRowMajor; this->setA(A, indices, ptr); this->setB(B); this->setC(C); this->run(true); this->checkC(CCheck); this->setC(C); #ifndef CPU_ONLY this->run(false); this->checkC(CCheck); #else #endif } TYPED_TEST(CsrFunctionsGenTest, TestCsrGemm9) { TypeParam A[] = {1.0, 2.0, 3.0}; int indices[] = {0, 2, 1}; int ptr[] = {0, 2, 3}; TypeParam B[] = {4.0, 7.0, 5.0, 8.0, 6.0, 9.0}; TypeParam C[] = {1.0, 2.0, 3.0, 0.0}; TypeParam CCheck[] = {31.0, 48.0, 61.0, 36.0}; this->alpha = 2.0; this->beta = 3.0; this->SetUp(2, 2, 3, 3, 3); this->TransA = CblasNoTrans; this->TransB = CblasTrans; this->orderC = CblasColMajor; this->setA(A, indices, ptr); this->setB(B); this->setC(C); this->run(true); this->checkC(CCheck); this->setC(C); #ifndef CPU_ONLY this->run(false); this->checkC(CCheck); #else #endif } TYPED_TEST(CsrFunctionsGenTest, TestCsrGemm10) { TypeParam A[] = {1.0, 2.0, 3.0}; int indices[] = {0, 2, 1}; int ptr[] = {0, 2, 3}; TypeParam B[] = {4.0, 7.0, 5.0, 8.0, 6.0, 9.0}; TypeParam C[] = {1.0, 2.0, 3.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; TypeParam CCheck[] = {11.0, 20.0, 19.0, 48.0, 36.0, 54.0, 16.0, 28.0, 20.0}; this->alpha = 2.0; this->beta = 3.0; this->SetUp(3, 3, 2, 3, 3); this->TransA = CblasTrans; this->TransB = CblasNoTrans; this->orderC = CblasRowMajor; this->setA(A, indices, ptr); this->setB(B); this->setC(C); this->run(true); this->checkC(CCheck); this->setC(C); #ifndef CPU_ONLY this->run(false); this->checkC(CCheck); #else #endif } TYPED_TEST(CsrFunctionsGenTest, TestCsrGemm11) { TypeParam A[] = {1.0, 2.0, 3.0}; int indices[] = {0, 2, 1}; int ptr[] = {0, 2, 3}; TypeParam B[] = {4.0, 7.0, 5.0, 8.0, 6.0, 9.0}; TypeParam C[] = {1.0, 2.0, 3.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; TypeParam CCheck[] = {11.0, 54.0, 25.0, 14.0, 36.0, 28.0, 10.0, 54.0, 20.0}; this->alpha = 2.0; this->beta = 3.0; this->SetUp(3, 3, 2, 3, 3); this->TransA = CblasTrans; this->TransB = CblasNoTrans; this->orderC = CblasColMajor; this->setA(A, indices, ptr); this->setB(B); this->setC(C); this->run(true); this->checkC(CCheck); this->setC(C); #ifndef CPU_ONLY this->run(false); this->checkC(CCheck); #else #endif } TYPED_TEST(CsrFunctionsGenTest, TestCsrGemm12) { TypeParam A[] = {1.0, 2.0, 3.0}; int indices[] = {0, 2, 1}; int ptr[] = {0, 2, 3}; TypeParam B[] = {4.0, 7.0, 5.0, 8.0, 6.0, 9.0}; TypeParam C[] = {1.0, 2.0, 3.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; TypeParam CCheck[] = {11.0, 16.0, 21.0, 42.0, 48.0, 54.0, 16.0, 20.0, 24.0}; this->alpha = 2.0; this->beta = 3.0; this->SetUp(3, 3, 2, 3, 3); this->TransA = CblasTrans; this->TransB = CblasTrans; this->orderC = CblasRowMajor; this->setA(A, indices, ptr); this->setB(B); this->setC(C); this->run(true); this->checkC(CCheck); this->setC(C); #ifndef CPU_ONLY this->run(false); this->checkC(CCheck); #else #endif } TYPED_TEST(CsrFunctionsGenTest, TestCsrGemm13) { TypeParam A[] = {1.0, 2.0, 3.0}; int indices[] = {0, 2, 1}; int ptr[] = {0, 2, 3}; TypeParam B[] = {4.0, 7.0, 5.0, 8.0, 6.0, 9.0}; TypeParam C[] = {1.0, 2.0, 3.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; TypeParam CCheck[] = {11.0, 48.0, 25.0, 10.0, 48.0, 20.0, 12.0, 54.0, 24.0}; this->alpha = 2.0; this->beta = 3.0; this->SetUp(3, 3, 2, 3, 3); this->TransA = CblasTrans; this->TransB = CblasTrans; this->orderC = CblasColMajor; this->setA(A, indices, ptr); this->setB(B); this->setC(C); this->run(true); this->checkC(CCheck); this->setC(C); #ifndef CPU_ONLY this->run(false); this->checkC(CCheck); #else #endif } TYPED_TEST(CsrFunctionsGenTest, TestCsrGemmSpeedForward) { std::vector<int> batch_size; std::vector<int> features; std::vector<int> nzz_per_row; std::vector<int> classes; batch_size.push_back(64); batch_size.push_back(128); features.push_back(10000); nzz_per_row.push_back(200); classes.push_back(2); classes.push_back(10); classes.push_back(100); for (int ba = 0; ba < batch_size.size(); ba++) { for (int f = 0; f < features.size(); f++) { for (int nr = 0; nr < nzz_per_row.size(); nr++) { for (int c = 0; c < classes.size(); c++) { this->test_speed_forward(batch_size[ba], features[f], nzz_per_row[nr], classes[c]); } } } } } TYPED_TEST(CsrFunctionsGenTest, TestCsrGemmSpeedBackward) { std::vector<int> batch_size; std::vector<int> features; std::vector<int> nzz_per_row; std::vector<int> classes; batch_size.push_back(64); batch_size.push_back(128); features.push_back(10000); nzz_per_row.push_back(200); classes.push_back(2); classes.push_back(10); classes.push_back(100); for (int ba = 0; ba < batch_size.size(); ba++) { for (int f = 0; f < features.size(); f++) { for (int nr = 0; nr < nzz_per_row.size(); nr++) { for (int c = 0; c < classes.size(); c++) { this->test_speed_backward(batch_size[ba], features[f], nzz_per_row[nr], classes[c]); } } } } } } // namespace caffe
26.673558
80
0.607882
alemagnani
4fbc03e946878551b5e3438b518cf8f3461219b7
12,666
hpp
C++
external/windows/boost/include/boost/xpressive/detail/static/grammar.hpp
foxostro/CheeseTesseract
737ebbd19cee8f5a196bf39a11ca793c561e56cb
[ "MIT" ]
1
2016-05-17T03:36:52.000Z
2016-05-17T03:36:52.000Z
external/windows/boost/include/boost/xpressive/detail/static/grammar.hpp
foxostro/CheeseTesseract
737ebbd19cee8f5a196bf39a11ca793c561e56cb
[ "MIT" ]
null
null
null
external/windows/boost/include/boost/xpressive/detail/static/grammar.hpp
foxostro/CheeseTesseract
737ebbd19cee8f5a196bf39a11ca793c561e56cb
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // grammar.hpp // // Copyright 2007 Eric Niebler. 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) #ifndef BOOST_XPRESSIVE_DETAIL_STATIC_GRAMMAR_HPP_EAN_11_12_2006 #define BOOST_XPRESSIVE_DETAIL_STATIC_GRAMMAR_HPP_EAN_11_12_2006 // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once #endif #include <boost/mpl/if.hpp> #include <boost/mpl/bool.hpp> #include <boost/mpl/assert.hpp> #include <boost/xpressive/detail/static/is_pure.hpp> #include <boost/xpressive/proto/proto.hpp> #include <boost/xpressive/proto/transform/arg.hpp> #include <boost/xpressive/proto/transform/fold.hpp> #include <boost/xpressive/proto/transform/compose.hpp> #include <boost/xpressive/detail/static/transforms/as_matcher.hpp> #include <boost/xpressive/detail/static/transforms/as_alternate.hpp> #include <boost/xpressive/detail/static/transforms/as_sequence.hpp> #include <boost/xpressive/detail/static/transforms/as_quantifier.hpp> #include <boost/xpressive/detail/static/transforms/as_marker.hpp> #include <boost/xpressive/detail/static/transforms/as_set.hpp> #include <boost/xpressive/detail/static/transforms/as_independent.hpp> #include <boost/xpressive/detail/static/transforms/as_modifier.hpp> #include <boost/xpressive/detail/static/transforms/as_inverse.hpp> #include <boost/xpressive/detail/static/transforms/as_action.hpp> #include <boost/xpressive/detail/detail_fwd.hpp> #define BOOST_XPRESSIVE_CHECK_REGEX(Expr, Char)\ BOOST_MPL_ASSERT\ ((\ typename boost::mpl::if_<\ boost::xpressive::is_valid_regex<Expr, Char>\ , boost::mpl::true_\ , boost::xpressive::INVALID_REGULAR_EXPRESSION\ >::type\ )); ////////////////////////////////////////////////////////////////////////// //**********************************************************************// //* << NOTE! >> *// //* *// //* Whenever you change this grammar, you MUST also make corresponding *// //* changes to width_of.hpp and is_pure.hpp. *// //* *// //**********************************************************************// ////////////////////////////////////////////////////////////////////////// namespace boost { namespace xpressive { template<typename Char> struct Grammar; template<typename Char> struct ActionableGrammar; namespace detail { /////////////////////////////////////////////////////////////////////////// // CharLiteral template<typename Char> struct CharLiteral; /////////////////////////////////////////////////////////////////////////// // ListSet template<typename Char> struct ListSet; /////////////////////////////////////////////////////////////////////////// // as_repeat template<typename Char, typename Gram, typename Tag, bool Greedy> struct as_repeat : proto::if_< use_simple_repeat<proto::result_of::arg<mpl::_>, Char> , as_simple_quantifier<proto::unary_expr<Tag, Gram>, Greedy> , as_default_quantifier<proto::unary_expr<Tag, Gram>, Greedy> > {}; /////////////////////////////////////////////////////////////////////////// // NonGreedyRepeatCases template<typename Char, typename Gram> struct NonGreedyRepeatCases { template<typename Tag, typename Dummy = void> struct case_ : proto::not_<proto::_> {}; template<typename Dummy> struct case_<proto::tag::dereference, Dummy> : as_repeat<Char, Gram, proto::tag::dereference, false> {}; template<typename Dummy> struct case_<proto::tag::posit, Dummy> : as_repeat<Char, Gram, proto::tag::posit, false> {}; template<typename Dummy> struct case_<proto::tag::logical_not, Dummy> : as_repeat<Char, Gram, proto::tag::logical_not, false> {}; template<uint_t Min, uint_t Max, typename Dummy> struct case_<generic_quant_tag<Min, Max>, Dummy> : as_repeat<Char, Gram, generic_quant_tag<Min, Max>, false> {}; }; /////////////////////////////////////////////////////////////////////////// // InvertibleCases template<typename Char, typename Gram> struct InvertibleCases { template<typename Tag, typename Dummy = void> struct case_ : proto::not_<proto::_> {}; template<typename Dummy> struct case_<proto::tag::comma, Dummy> : as_list_set<ListSet<Char> > {}; template<typename Dummy> struct case_<proto::tag::assign, Dummy> : as_list_set<ListSet<Char> > {}; template<typename Dummy> struct case_<proto::tag::subscript, Dummy> : proto::transform::right<proto::subscript<set_initializer_type, as_set<Gram> > > {}; template<typename Dummy> struct case_<lookahead_tag, Dummy> : proto::transform::arg<proto::unary_expr<lookahead_tag, as_lookahead<Gram> > > {}; template<typename Dummy> struct case_<lookbehind_tag, Dummy> : proto::transform::arg<proto::unary_expr<lookbehind_tag, as_lookbehind<Gram> > > {}; template<typename Dummy> struct case_<proto::tag::terminal, Dummy> : proto::or_< as_matcher<CharLiteral<Char> > , as_matcher<proto::terminal<posix_charset_placeholder> > , as_matcher<proto::terminal<range_placeholder<proto::_> > > , as_matcher<proto::terminal<logical_newline_placeholder> > , as_matcher<proto::terminal<assert_word_placeholder<word_boundary<true> > > > > {}; }; /////////////////////////////////////////////////////////////////////////// // Cases template<typename Char, typename Gram> struct Cases { template<typename Tag, typename Dummy = void> struct case_ : proto::not_<proto::_> {}; template<typename Dummy> struct case_<proto::tag::shift_right, Dummy> : proto::transform::reverse_fold<proto::shift_right<Gram, Gram> > {}; template<typename Dummy> struct case_<proto::tag::terminal, Dummy> : in_sequence<as_matcher<proto::terminal<proto::_> > > {}; template<typename Dummy> struct case_<proto::tag::bitwise_or, Dummy> : in_sequence<as_alternate<proto::bitwise_or<Gram, Gram> > > {}; template<typename Dummy, bool Greedy> struct case_<optional_tag<Greedy> , Dummy> : in_sequence<proto::transform::arg<proto::unary_expr<optional_tag<Greedy>, as_optional<Gram, Greedy> > > > {}; template<typename Dummy> struct case_<proto::tag::dereference, Dummy> : proto::transform::compose<as_repeat<Char, Gram, proto::tag::dereference, true>, Gram> {}; template<typename Dummy> struct case_<proto::tag::posit, Dummy> : proto::transform::compose<as_repeat<Char, Gram, proto::tag::posit, true>, Gram> {}; template<typename Dummy> struct case_<proto::tag::logical_not, Dummy> : proto::transform::compose<as_repeat<Char, Gram, proto::tag::logical_not, true>, Gram> {}; template<uint_t Min, uint_t Max, typename Dummy> struct case_<generic_quant_tag<Min, Max> , Dummy> : proto::transform::compose<as_repeat<Char, Gram, generic_quant_tag<Min, Max>, true>, Gram> {}; template<typename Dummy> struct case_<proto::tag::negate, Dummy> : proto::transform::compose< proto::transform::arg<proto::negate<proto::switch_<NonGreedyRepeatCases<Char, Gram> > > > , Gram > {}; template<typename Dummy> struct case_<proto::tag::complement, Dummy> : in_sequence<as_inverse< proto::transform::arg<proto::complement<proto::switch_<InvertibleCases<Char, Gram> > > > > > {}; template<typename Dummy> struct case_<modifier_tag, Dummy> : as_modifier<proto::binary_expr<modifier_tag, proto::_, Gram> > {}; template<typename Dummy> struct case_<lookahead_tag, Dummy> : in_sequence<proto::transform::arg<proto::unary_expr<lookahead_tag, as_lookahead<Gram> > > > {}; template<typename Dummy> struct case_<lookbehind_tag, Dummy> : in_sequence<proto::transform::arg<proto::unary_expr<lookbehind_tag, as_lookbehind<Gram> > > > {}; template<typename Dummy> struct case_<keeper_tag, Dummy> : in_sequence<proto::transform::arg<proto::unary_expr<keeper_tag, as_keeper<Gram> > > > {}; template<typename Dummy> struct case_<proto::tag::comma, Dummy> : in_sequence<as_list_set<ListSet<Char> > > {}; template<typename Dummy> struct case_<proto::tag::assign, Dummy> : proto::or_< proto::transform::compose<as_marker<proto::assign<basic_mark_tag, Gram> >, Gram> , in_sequence<as_list_set<ListSet<Char> > > > {}; template<typename Dummy> struct case_<proto::tag::subscript, Dummy> : proto::or_< in_sequence<proto::transform::right<proto::subscript<set_initializer_type, as_set<Gram> > > > , proto::transform::compose<as_action<proto::subscript<ActionableGrammar<Char>, proto::_> >, ActionableGrammar<Char> > > {}; }; /////////////////////////////////////////////////////////////////////////// // ActionableCases template<typename Char, typename Gram> struct ActionableCases { template<typename Tag, typename Dummy = void> struct case_ : Cases<Char, Gram>::template case_<Tag> {}; // Only in sub-expressions with actions attached do we allow attribute assignements template<typename Dummy> struct case_<proto::tag::assign, Dummy> : proto::or_< typename Cases<Char, Gram>::template case_<proto::tag::assign> , in_sequence<as_attr_matcher<proto::assign<proto::terminal<attribute_placeholder<proto::_> >, proto::_> > > > {}; }; } // namespace detail /////////////////////////////////////////////////////////////////////////// // Grammar template<typename Char> struct Grammar : proto::switch_<detail::Cases<Char, Grammar<Char> > > {}; template<typename Char> struct ActionableGrammar : proto::switch_<detail::ActionableCases<Char, ActionableGrammar<Char> > > {}; /////////////////////////////////////////////////////////////////////////// // INVALID_REGULAR_EXPRESSION struct INVALID_REGULAR_EXPRESSION : mpl::false_ {}; /////////////////////////////////////////////////////////////////////////// // is_valid_regex template<typename Expr, typename Char> struct is_valid_regex : proto::matches<Expr, Grammar<Char> > {}; }} // namespace boost::xpressive #endif
39.335404
137
0.507974
foxostro
4fbd58f757ee63b8af07dd815009c8a44d374d34
2,893
cpp
C++
P1/test_BST.cpp
jayx2thez/c100
e81e5182b452a2bf698d37315791cd2e45f73a6e
[ "MIT" ]
null
null
null
P1/test_BST.cpp
jayx2thez/c100
e81e5182b452a2bf698d37315791cd2e45f73a6e
[ "MIT" ]
null
null
null
P1/test_BST.cpp
jayx2thez/c100
e81e5182b452a2bf698d37315791cd2e45f73a6e
[ "MIT" ]
1
2018-07-31T01:45:51.000Z
2018-07-31T01:45:51.000Z
#include "BST.hpp" #include <iostream> #include <algorithm> #include <vector> using namespace std; /** * A simple test driver for the BST class template. * P1 CSE 100 2013 * Author: P. Kube (c) 2013 */ int main() { /* Create an STL vector of some ints */ vector<int> v; v.push_back(3); v.push_back(4); v.push_back(1); v.push_back(100); v.push_back(-33); /* Create an instance of BST holding int */ BST<int> b; /* Insert a few data items. */ vector<int>::iterator vit = v.begin(); vector<int>::iterator ven = v.end(); for(; vit != ven; ++vit) { // all these inserts are unique, so should return a std::pair // with second part true std::pair<BST<int>::iterator,bool> pr = b.insert(*vit); if(! pr.second ) { cout << "Incorrect bool return value when inserting " << *vit << endl; return -1; } if(*(pr.first) != *vit) { cout << "Incorrect iterator return value when inserting " << *vit << endl; return -1; } } /* Test size. */ cout << "Size is: " << b.size() << endl; if(b.size() != v.size()) { cout << "... which is incorrect." << endl; return -1; } /* Test find return value. */ vit = v.begin(); int count = 0; for(; vit != ven; ++vit) { if(*(b.find(*vit)) != *vit) { cout << "Incorrect return value when finding " << *vit << endl; return -1; } cout << "been through " << ++count << endl; } /* Sort the vector, to compare with inorder iteration on the BST */ cout << "this is v: " << *(v.begin()) << endl; sort(v.begin(),v.end()); cout << "sort done" << endl; /* Test BST iterator; should iterate inorder */ cout << "traversal using iterator:" << endl; vit = v.begin(); BST<int>::iterator en = b.end(); BST<int>::iterator it = b.begin(); cout << "entering iteration" << endl; for(; vit != ven; ++vit) { cout << "iterating..." << endl; if(! (it != en) ) { cout << "entered first if" << endl; cout << *it << "," << *vit << ": Early termination of BST iteration." << endl; return -1; } cout << *it << endl; if(*it != *vit) { cout << *it << "," << *vit << ": Incorrect inorder iteration of BST." << endl; return -1; } ++it; } cout << "OK." << endl; vector<int> dup; dup.push_back(5); dup.push_back(3); dup.push_back(3); BST<int> duplicateBST; vector<int>::iterator bit = dup.begin(); vector<int>::iterator ben = dup.end(); for(; bit != ben; ++bit) { // all these inserts are unique, so should return a std::pair // with second part true std::pair<BST<int>::iterator,bool> br = duplicateBST.insert(*bit); if(br.second == false) { cout << "Value is duplicate " << *bit << endl; } if(*(br.first) != *bit) { cout << "Incorrect iterator return value when inserting " << *bit << endl; return -1; } } }
25.830357
84
0.550294
jayx2thez
4fc5d5093b8b7b73dc755edb88a22df40abcea4b
15,207
cpp
C++
src/game/server/hl2/weapon_ar2.cpp
LillyWho/TF2HLCoop
04d572fbf7da76c7d4e8f9481bad5a27b5406203
[ "Unlicense" ]
2
2019-04-08T00:09:06.000Z
2020-11-22T23:12:30.000Z
src/game/server/hl2/weapon_ar2.cpp
Kenzzer/TF2HLCoop
86097fe5c7f097fbfff4b3c394280cc53c2cadf9
[ "Unlicense" ]
null
null
null
src/game/server/hl2/weapon_ar2.cpp
Kenzzer/TF2HLCoop
86097fe5c7f097fbfff4b3c394280cc53c2cadf9
[ "Unlicense" ]
1
2021-05-01T15:43:17.000Z
2021-05-01T15:43:17.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "basecombatweapon.h" #include "npcevent.h" #include "basecombatcharacter.h" #include "ai_basenpc.h" #include "player.h" #include "weapon_ar2.h" #include "grenade_ar2.h" #include "gamerules.h" #include "game.h" #include "in_buttons.h" #include "ai_memory.h" #include "soundent.h" #include "hl2_player.h" #include "EntityFlame.h" #include "weapon_flaregun.h" #include "te_effect_dispatch.h" #include "prop_combine_ball.h" #include "beam_shared.h" #include "npc_combine.h" #include "rumble_shared.h" #include "gamestats.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" ConVar sk_weapon_ar2_alt_fire_radius( "sk_weapon_ar2_alt_fire_radius", "10" ); ConVar sk_weapon_ar2_alt_fire_duration( "sk_weapon_ar2_alt_fire_duration", "2" ); ConVar sk_weapon_ar2_alt_fire_mass( "sk_weapon_ar2_alt_fire_mass", "150" ); //========================================================= //========================================================= BEGIN_DATADESC( CWeaponAR2 ) DEFINE_FIELD( m_flDelayedFire, FIELD_TIME ), DEFINE_FIELD( m_bShotDelayed, FIELD_BOOLEAN ), //DEFINE_FIELD( m_nVentPose, FIELD_INTEGER ), END_DATADESC() IMPLEMENT_SERVERCLASS_ST(CWeaponAR2, DT_WeaponAR2) END_SEND_TABLE() LINK_ENTITY_TO_CLASS( weapon_ar2, CWeaponAR2 ); PRECACHE_WEAPON_REGISTER(weapon_ar2); acttable_t CWeaponAR2::m_acttable[] = { { ACT_RANGE_ATTACK1, ACT_RANGE_ATTACK_AR2, true }, { ACT_RELOAD, ACT_RELOAD_SMG1, true }, // FIXME: hook to AR2 unique { ACT_IDLE, ACT_IDLE_SMG1, true }, // FIXME: hook to AR2 unique { ACT_IDLE_ANGRY, ACT_IDLE_ANGRY_SMG1, true }, // FIXME: hook to AR2 unique { ACT_WALK, ACT_WALK_RIFLE, true }, // Readiness activities (not aiming) { ACT_IDLE_RELAXED, ACT_IDLE_SMG1_RELAXED, false },//never aims { ACT_IDLE_STIMULATED, ACT_IDLE_SMG1_STIMULATED, false }, { ACT_IDLE_AGITATED, ACT_IDLE_ANGRY_SMG1, false },//always aims { ACT_WALK_RELAXED, ACT_WALK_RIFLE_RELAXED, false },//never aims { ACT_WALK_STIMULATED, ACT_WALK_RIFLE_STIMULATED, false }, { ACT_WALK_AGITATED, ACT_WALK_AIM_RIFLE, false },//always aims { ACT_RUN_RELAXED, ACT_RUN_RIFLE_RELAXED, false },//never aims { ACT_RUN_STIMULATED, ACT_RUN_RIFLE_STIMULATED, false }, { ACT_RUN_AGITATED, ACT_RUN_AIM_RIFLE, false },//always aims // Readiness activities (aiming) { ACT_IDLE_AIM_RELAXED, ACT_IDLE_SMG1_RELAXED, false },//never aims { ACT_IDLE_AIM_STIMULATED, ACT_IDLE_AIM_RIFLE_STIMULATED, false }, { ACT_IDLE_AIM_AGITATED, ACT_IDLE_ANGRY_SMG1, false },//always aims { ACT_WALK_AIM_RELAXED, ACT_WALK_RIFLE_RELAXED, false },//never aims { ACT_WALK_AIM_STIMULATED, ACT_WALK_AIM_RIFLE_STIMULATED, false }, { ACT_WALK_AIM_AGITATED, ACT_WALK_AIM_RIFLE, false },//always aims { ACT_RUN_AIM_RELAXED, ACT_RUN_RIFLE_RELAXED, false },//never aims { ACT_RUN_AIM_STIMULATED, ACT_RUN_AIM_RIFLE_STIMULATED, false }, { ACT_RUN_AIM_AGITATED, ACT_RUN_AIM_RIFLE, false },//always aims //End readiness activities { ACT_WALK_AIM, ACT_WALK_AIM_RIFLE, true }, { ACT_WALK_CROUCH, ACT_WALK_CROUCH_RIFLE, true }, { ACT_WALK_CROUCH_AIM, ACT_WALK_CROUCH_AIM_RIFLE, true }, { ACT_RUN, ACT_RUN_RIFLE, true }, { ACT_RUN_AIM, ACT_RUN_AIM_RIFLE, true }, { ACT_RUN_CROUCH, ACT_RUN_CROUCH_RIFLE, true }, { ACT_RUN_CROUCH_AIM, ACT_RUN_CROUCH_AIM_RIFLE, true }, { ACT_GESTURE_RANGE_ATTACK1, ACT_GESTURE_RANGE_ATTACK_AR2, false }, { ACT_COVER_LOW, ACT_COVER_SMG1_LOW, false }, // FIXME: hook to AR2 unique { ACT_RANGE_AIM_LOW, ACT_RANGE_AIM_AR2_LOW, false }, { ACT_RANGE_ATTACK1_LOW, ACT_RANGE_ATTACK_SMG1_LOW, true }, // FIXME: hook to AR2 unique { ACT_RELOAD_LOW, ACT_RELOAD_SMG1_LOW, false }, { ACT_GESTURE_RELOAD, ACT_GESTURE_RELOAD_SMG1, true }, // { ACT_RANGE_ATTACK2, ACT_RANGE_ATTACK_AR2_GRENADE, true }, }; IMPLEMENT_ACTTABLE(CWeaponAR2); CWeaponAR2::CWeaponAR2( ) { m_fMinRange1 = 65; m_fMaxRange1 = 2048; m_fMinRange2 = 256; m_fMaxRange2 = 1024; m_nShotsFired = 0; m_nVentPose = -1; m_bAltFiresUnderwater = false; } void CWeaponAR2::Precache( void ) { BaseClass::Precache(); UTIL_PrecacheOther( "prop_combine_ball" ); UTIL_PrecacheOther( "env_entity_dissolver" ); } //----------------------------------------------------------------------------- // Purpose: Handle grenade detonate in-air (even when no ammo is left) //----------------------------------------------------------------------------- void CWeaponAR2::ItemPostFrame( void ) { // See if we need to fire off our secondary round if ( m_bShotDelayed && gpGlobals->curtime > m_flDelayedFire ) { DelayedAttack(); } // Update our pose parameter for the vents CBasePlayer *pOwner = ToBasePlayer( GetOwner() ); if ( pOwner ) { CBaseViewModel *pVM = pOwner->GetViewModel(); if ( pVM ) { if ( m_nVentPose == -1 ) { m_nVentPose = pVM->LookupPoseParameter( "VentPoses" ); } float flVentPose = RemapValClamped( m_nShotsFired, 0, 5, 0.0f, 1.0f ); pVM->SetPoseParameter( m_nVentPose, flVentPose ); } } BaseClass::ItemPostFrame(); } //----------------------------------------------------------------------------- // Purpose: // Output : Activity //----------------------------------------------------------------------------- Activity CWeaponAR2::GetPrimaryAttackActivity( void ) { if ( m_nShotsFired < 2 ) return ACT_VM_PRIMARYATTACK; if ( m_nShotsFired < 3 ) return ACT_VM_RECOIL1; if ( m_nShotsFired < 4 ) return ACT_VM_RECOIL2; return ACT_VM_RECOIL3; } //----------------------------------------------------------------------------- // Purpose: // Input : &tr - // nDamageType - //----------------------------------------------------------------------------- void CWeaponAR2::DoImpactEffect( trace_t &tr, int nDamageType ) { CEffectData data; data.m_vOrigin = tr.endpos + ( tr.plane.normal * 1.0f ); data.m_vNormal = tr.plane.normal; DispatchEffect( "AR2Impact", data ); BaseClass::DoImpactEffect( tr, nDamageType ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponAR2::DelayedAttack( void ) { m_bShotDelayed = false; CBasePlayer *pOwner = ToBasePlayer( GetOwner() ); if ( pOwner == NULL ) return; // Deplete the clip completely SendWeaponAnim( ACT_VM_SECONDARYATTACK ); m_flNextSecondaryAttack = pOwner->m_flNextAttack = gpGlobals->curtime + SequenceDuration(); // Register a muzzleflash for the AI pOwner->DoMuzzleFlash(); pOwner->SetMuzzleFlashTime( gpGlobals->curtime + 0.5 ); WeaponSound( WPN_DOUBLE ); pOwner->RumbleEffect(RUMBLE_SHOTGUN_DOUBLE, 0, RUMBLE_FLAG_RESTART ); // Fire the bullets Vector vecSrc = pOwner->Weapon_ShootPosition( ); Vector vecAiming = pOwner->GetAutoaimVector( AUTOAIM_SCALE_DEFAULT ); Vector impactPoint = vecSrc + ( vecAiming * MAX_TRACE_LENGTH ); // Fire the bullets Vector vecVelocity = vecAiming * 1000.0f; // Fire the combine ball CreateCombineBall( vecSrc, vecVelocity, sk_weapon_ar2_alt_fire_radius.GetFloat(), sk_weapon_ar2_alt_fire_mass.GetFloat(), sk_weapon_ar2_alt_fire_duration.GetFloat(), pOwner ); // View effects color32 white = {255, 255, 255, 64}; UTIL_ScreenFade( pOwner, white, 0.1, 0, FFADE_IN ); //Disorient the player QAngle angles = pOwner->GetLocalAngles(); angles.x += random->RandomInt( -4, 4 ); angles.y += random->RandomInt( -4, 4 ); angles.z = 0; pOwner->SnapEyeAngles( angles ); pOwner->ViewPunch( QAngle( random->RandomInt( -8, -12 ), random->RandomInt( 1, 2 ), 0 ) ); // Decrease ammo pOwner->RemoveAmmo( 1, m_iSecondaryAmmoType ); // Can shoot again immediately m_flNextPrimaryAttack = gpGlobals->curtime + 0.5f; // Can blow up after a short delay (so have time to release mouse button) m_flNextSecondaryAttack = gpGlobals->curtime + 1.0f; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponAR2::SecondaryAttack( void ) { if ( m_bShotDelayed ) return; // Cannot fire underwater if ( GetOwner() && GetOwner()->GetWaterLevel() == 3 ) { SendWeaponAnim( ACT_VM_DRYFIRE ); BaseClass::WeaponSound( EMPTY ); m_flNextSecondaryAttack = gpGlobals->curtime + 0.5f; return; } m_bShotDelayed = true; m_flNextPrimaryAttack = m_flNextSecondaryAttack = m_flDelayedFire = gpGlobals->curtime + 0.5f; CBasePlayer *pPlayer = ToBasePlayer( GetOwner() ); if( pPlayer ) { pPlayer->RumbleEffect(RUMBLE_AR2_ALT_FIRE, 0, RUMBLE_FLAG_RESTART ); } SendWeaponAnim( ACT_VM_FIDGET ); WeaponSound( SPECIAL1 ); m_iSecondaryAttacks++; gamestats->Event_WeaponFired( pPlayer, false, GetClassname() ); } //----------------------------------------------------------------------------- // Purpose: Override if we're waiting to release a shot // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CWeaponAR2::CanHolster( void ) const { if ( m_bShotDelayed ) return false; return BaseClass::CanHolster(); } //----------------------------------------------------------------------------- // Purpose: Override if we're waiting to release a shot //----------------------------------------------------------------------------- bool CWeaponAR2::Reload( void ) { if ( m_bShotDelayed ) return false; return BaseClass::Reload(); } //----------------------------------------------------------------------------- // Purpose: // Input : *pOperator - //----------------------------------------------------------------------------- void CWeaponAR2::FireNPCPrimaryAttack( CBaseCombatCharacter *pOperator, bool bUseWeaponAngles ) { Vector vecShootOrigin, vecShootDir; CAI_BaseNPC *npc = pOperator->MyNPCPointer(); ASSERT( npc != NULL ); if ( bUseWeaponAngles ) { QAngle angShootDir; GetAttachment( LookupAttachment( "muzzle" ), vecShootOrigin, angShootDir ); AngleVectors( angShootDir, &vecShootDir ); } else { vecShootOrigin = pOperator->Weapon_ShootPosition(); vecShootDir = npc->GetActualShootTrajectory( vecShootOrigin ); } WeaponSoundRealtime( SINGLE_NPC ); CSoundEnt::InsertSound( SOUND_COMBAT|SOUND_CONTEXT_GUNFIRE, pOperator->GetAbsOrigin(), SOUNDENT_VOLUME_MACHINEGUN, 0.2, pOperator, SOUNDENT_CHANNEL_WEAPON, pOperator->GetEnemy() ); pOperator->FireBullets( 1, vecShootOrigin, vecShootDir, VECTOR_CONE_PRECALCULATED, MAX_TRACE_LENGTH, m_iPrimaryAmmoType, 2 ); // NOTENOTE: This is overriden on the client-side // pOperator->DoMuzzleFlash(); m_iClip1 = m_iClip1 - 1; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponAR2::FireNPCSecondaryAttack( CBaseCombatCharacter *pOperator, bool bUseWeaponAngles ) { WeaponSound( WPN_DOUBLE ); if ( !GetOwner() ) return; CAI_BaseNPC *pNPC = GetOwner()->MyNPCPointer(); if ( !pNPC ) return; // Fire! Vector vecSrc; Vector vecAiming; if ( bUseWeaponAngles ) { QAngle angShootDir; GetAttachment( LookupAttachment( "muzzle" ), vecSrc, angShootDir ); AngleVectors( angShootDir, &vecAiming ); } else { vecSrc = pNPC->Weapon_ShootPosition( ); Vector vecTarget; CNPC_Combine *pSoldier = dynamic_cast<CNPC_Combine *>( pNPC ); if ( pSoldier ) { // In the distant misty past, elite soldiers tried to use bank shots. // Therefore, we must ask them specifically what direction they are shooting. vecTarget = pSoldier->GetAltFireTarget(); } else { // All other users of the AR2 alt-fire shoot directly at their enemy. if ( !pNPC->GetEnemy() ) return; vecTarget = pNPC->GetEnemy()->BodyTarget( vecSrc ); } vecAiming = vecTarget - vecSrc; VectorNormalize( vecAiming ); } Vector impactPoint = vecSrc + ( vecAiming * MAX_TRACE_LENGTH ); float flAmmoRatio = 1.0f; float flDuration = RemapValClamped( flAmmoRatio, 0.0f, 1.0f, 0.5f, sk_weapon_ar2_alt_fire_duration.GetFloat() ); float flRadius = RemapValClamped( flAmmoRatio, 0.0f, 1.0f, 4.0f, sk_weapon_ar2_alt_fire_radius.GetFloat() ); // Fire the bullets Vector vecVelocity = vecAiming * 1000.0f; // Fire the combine ball CreateCombineBall( vecSrc, vecVelocity, flRadius, sk_weapon_ar2_alt_fire_mass.GetFloat(), flDuration, pNPC ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponAR2::Operator_ForceNPCFire( CBaseCombatCharacter *pOperator, bool bSecondary ) { if ( bSecondary ) { FireNPCSecondaryAttack( pOperator, true ); } else { // Ensure we have enough rounds in the clip m_iClip1++; FireNPCPrimaryAttack( pOperator, true ); } } //----------------------------------------------------------------------------- // Purpose: // Input : *pEvent - // *pOperator - //----------------------------------------------------------------------------- void CWeaponAR2::Operator_HandleAnimEvent( animevent_t *pEvent, CBaseCombatCharacter *pOperator ) { switch( pEvent->event ) { case EVENT_WEAPON_AR2: { FireNPCPrimaryAttack( pOperator, false ); } break; case EVENT_WEAPON_AR2_ALTFIRE: { FireNPCSecondaryAttack( pOperator, false ); } break; default: CBaseCombatWeapon::Operator_HandleAnimEvent( pEvent, pOperator ); break; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponAR2::AddViewKick( void ) { #define EASY_DAMPEN 0.5f #define MAX_VERTICAL_KICK 8.0f //Degrees #define SLIDE_LIMIT 5.0f //Seconds //Get the view kick CBasePlayer *pPlayer = ToBasePlayer( GetOwner() ); if (!pPlayer) return; float flDuration = m_fFireDuration; if( g_pGameRules->GetAutoAimMode() == AUTOAIM_ON_CONSOLE ) { // On the 360 (or in any configuration using the 360 aiming scheme), don't let the // AR2 progressive into the late, highly inaccurate stages of its kick. Just // spoof the time to make it look (to the kicking code) like we haven't been // firing for very long. flDuration = MIN( flDuration, 0.75f ); } DoMachineGunKick( pPlayer, EASY_DAMPEN, MAX_VERTICAL_KICK, flDuration, SLIDE_LIMIT ); } //----------------------------------------------------------------------------- const WeaponProficiencyInfo_t *CWeaponAR2::GetProficiencyValues() { static WeaponProficiencyInfo_t proficiencyTable[] = { { 7.0, 0.75 }, { 5.00, 0.75 }, { 3.0, 0.85 }, { 5.0/3.0, 0.75 }, { 1.00, 1.0 }, }; COMPILE_TIME_ASSERT( ARRAYSIZE(proficiencyTable) == WEAPON_PROFICIENCY_PERFECT + 1); return proficiencyTable; }
29.643275
181
0.61544
LillyWho
4fc6268918834168640fa817c73b0d200ef3e34b
1,507
cpp
C++
az_ykan_v1.0.1/Arduino-master/variants/wifi_slot/analogRead.cpp
angelbarusta/ind-matageyco
08be088f2178312e9bac94b9604bacd5223f4b53
[ "Apache-2.0" ]
null
null
null
az_ykan_v1.0.1/Arduino-master/variants/wifi_slot/analogRead.cpp
angelbarusta/ind-matageyco
08be088f2178312e9bac94b9604bacd5223f4b53
[ "Apache-2.0" ]
null
null
null
az_ykan_v1.0.1/Arduino-master/variants/wifi_slot/analogRead.cpp
angelbarusta/ind-matageyco
08be088f2178312e9bac94b9604bacd5223f4b53
[ "Apache-2.0" ]
null
null
null
#include "wiring_private.h" #include "pins_arduino.h" extern "C" int __analogRead(uint8_t pin); extern "C" int analogRead(uint8_t pin) { static uint8_t currentAin = 0; delay(0); if (pin >= ANALOG_INPUT_HARDWARE) { return 0; } uint8_t ain = analog_pin_to_mux_channel[pin]; if (ain == (uint8_t)NOT_A_PIN) { return 0; } if (currentAin > ain) { for (int i = 0; i < (8 - currentAin); ++i) { digitalWrite(ANALOG_INPUT_SELECTOR_PIN, HIGH); digitalWrite(ANALOG_INPUT_SELECTOR_PIN, LOW); digitalWrite(ANALOG_INPUT_SELECTOR_PIN, HIGH); digitalWrite(ANALOG_INPUT_SELECTOR_PIN, LOW); } currentAin = 0; } for (int i = currentAin; i < ain; ++i) { digitalWrite(ANALOG_INPUT_SELECTOR_PIN, HIGH); digitalWrite(ANALOG_INPUT_SELECTOR_PIN, LOW); digitalWrite(ANALOG_INPUT_SELECTOR_PIN, HIGH); digitalWrite(ANALOG_INPUT_SELECTOR_PIN, LOW); } currentAin = ain; return __analogRead(ANALOG_INPUT_HARDWARE); } void initVariant() { // we need to reset analog mux. When ANALOG_INPUT_SELECTOR_PIN is high // on ~0.4 ms, mux channel is becoming 0. // Mux channel is swithing on back \_ front. But there is no switching // - rc reset is still high when ANALOG_INPUT_SELECTOR_PIN became low uint16_t resetDelay = 777; pinMode(ANALOG_INPUT_SELECTOR_PIN, OUTPUT); digitalWrite(ANALOG_INPUT_SELECTOR_PIN, HIGH); delayMicroseconds(resetDelay); digitalWrite(ANALOG_INPUT_SELECTOR_PIN, LOW); delayMicroseconds(resetDelay); }
29.54902
72
0.716656
angelbarusta
4fc6a482195e682396076802e47835ad06cbf005
8,023
cpp
C++
src/curl/curl.cpp
rolandhill/vsgXchange
a7564a032bb1c6cc5c324d24a852e274c417d3a9
[ "MIT" ]
null
null
null
src/curl/curl.cpp
rolandhill/vsgXchange
a7564a032bb1c6cc5c324d24a852e274c417d3a9
[ "MIT" ]
null
null
null
src/curl/curl.cpp
rolandhill/vsgXchange
a7564a032bb1c6cc5c324d24a852e274c417d3a9
[ "MIT" ]
null
null
null
/* <editor-fold desc="MIT License"> Copyright(c) 2021 Robert Osfield 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. </editor-fold> */ #include <vsg/io/read.h> #include <vsgXchange/curl.h> #include <curl/curl.h> #include <fstream> #include <iostream> #include <sstream> using namespace vsgXchange; namespace vsgXchange { bool containsServerAddress(const vsg::Path& filename) { return filename.compare(0, 7, "http://") == 0 || filename.compare(0, 8, "https://") == 0; } std::pair<vsg::Path, vsg::Path> getServerPathAndFilename(const vsg::Path& filename) { auto pos = filename.find("://"); if (pos != vsg::Path::npos) { auto pos_slash = filename.find_first_of('/', pos + 3); if (pos_slash != vsg::Path::npos) { return {filename.substr(pos + 3, pos_slash - pos - 3), filename.substr(pos_slash + 1, vsg::Path::npos)}; } else { return {filename.substr(pos + 3, vsg::Path::npos), ""}; } } return {}; } vsg::Path getFileCachePath(const vsg::Path& fileCache, const vsg::Path& filename) { auto pos = filename.find("://"); if (pos != vsg::Path::npos) { return fileCache / filename.substr(pos + 3, vsg::Path::npos); } return {}; } class curl::Implementation { public: Implementation(); virtual ~Implementation(); vsg::ref_ptr<vsg::Object> read(const vsg::Path& filename, vsg::ref_ptr<const vsg::Options> options = {}) const; protected: }; } // namespace vsgXchange //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // CURL ReaderWriter fascade // curl::curl() : _implementation(nullptr) { } curl::~curl() { delete _implementation; } vsg::ref_ptr<vsg::Object> curl::read(const vsg::Path& filename, vsg::ref_ptr<const vsg::Options> options) const { vsg::Path serverFilename = filename; bool contains_serverAddress = containsServerAddress(filename); if (options) { if (!contains_serverAddress && !options->paths.empty()) { contains_serverAddress = containsServerAddress(options->paths.front()); if (contains_serverAddress) { serverFilename = options->paths.front() / filename; } } if (contains_serverAddress && options->fileCache) { auto fileCachePath = getFileCachePath(options->fileCache, serverFilename); if (vsg::fileExists(fileCachePath)) { auto local_options = vsg::Options::create(*options); local_options->paths.insert(local_options->paths.begin(), vsg::filePath(serverFilename)); local_options->extensionHint = vsg::lowerCaseFileExtension(filename); std::ifstream fin(fileCachePath, std::ios::in | std::ios::binary); auto object = vsg::read(fin, local_options); // do we need to remove any http URL? if (object) { return object; } } } } if (contains_serverAddress) { { std::scoped_lock<std::mutex> lock(_mutex); if (!_implementation) _implementation = new curl::Implementation(); } return _implementation->read(serverFilename, options); } else { return {}; } } bool curl::getFeatures(Features& features) const { features.protocolFeatureMap["http"] = vsg::ReaderWriter::READ_FILENAME; features.protocolFeatureMap["https"] = vsg::ReaderWriter::READ_FILENAME; return true; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // CURL ReaderWriter implementation // // use static mutex and counter to track whether the curl_global_init(..) and curl_global_cleanup() should be called. bool curl::s_do_curl_global_init_and_cleanup = true; std::mutex s_curlImplementationMutex; uint32_t s_curlImplementationCount = 0; curl::Implementation::Implementation() { if (curl::s_do_curl_global_init_and_cleanup) { std::scoped_lock<std::mutex> lock(s_curlImplementationMutex); if (s_curlImplementationCount == 0) { //std::cout<<"curl_global_init()"<<std::endl; curl_global_init(CURL_GLOBAL_ALL); } ++s_curlImplementationCount; } } curl::Implementation::~Implementation() { if (s_do_curl_global_init_and_cleanup) { std::scoped_lock<std::mutex> lock(s_curlImplementationMutex); --s_curlImplementationCount; if (s_curlImplementationCount == 0) { //std::cout<<"curl_global_cleanup()"<<std::endl; curl_global_cleanup(); } } } size_t StreamCallback(void* ptr, size_t size, size_t nmemb, void* user_data) { size_t realsize = size * nmemb; if (user_data) { std::ostream* ostr = reinterpret_cast<std::ostream*>(user_data); ostr->write(reinterpret_cast<const char*>(ptr), realsize); } return realsize; } vsg::ref_ptr<vsg::Object> curl::Implementation::read(const vsg::Path& filename, vsg::ref_ptr<const vsg::Options> options) const { auto _curl = curl_easy_init(); curl_easy_setopt(_curl, CURLOPT_USERAGENT, "libcurl-agent/1.0"); // make user controllable? curl_easy_setopt(_curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(_curl, CURLOPT_WRITEFUNCTION, StreamCallback); std::stringstream sstr; curl_easy_setopt(_curl, CURLOPT_URL, filename.string().c_str()); curl_easy_setopt(_curl, CURLOPT_WRITEDATA, (void*)&sstr); vsg::ref_ptr<vsg::Object> object; CURLcode responseCode = curl_easy_perform(_curl); if (responseCode == 0) { // success auto local_options = vsg::Options::create(*options); local_options->paths.insert(local_options->paths.begin(), vsg::filePath(filename)); local_options->extensionHint = vsg::fileExtension(filename); object = vsg::read(sstr, local_options); if (object && options->fileCache) { auto fileCachePath = getFileCachePath(options->fileCache, filename); if (fileCachePath) { vsg::makeDirectory(vsg::filePath(fileCachePath)); // reset the stringstream iterator to the beginning so we can copy it to the file cache file. sstr.clear(std::stringstream::goodbit); sstr.seekg(0); std::ofstream fout(fileCachePath, std::ios::out | std::ios::binary); fout << sstr.rdbuf(); } } } else { std::cerr << "libcurl error responseCode = " << responseCode << ", " << curl_easy_strerror(responseCode) << std::endl; } if (_curl) curl_easy_cleanup(_curl); return object; }
32.613821
460
0.613736
rolandhill
4fc8274e871319a985672f67145114b8ad3f85af
1,683
hpp
C++
webot/controllers/waypoints_runner/lidar_wrapper.hpp
DEIS-Tools/model-utilities
a1a38f7f8adcedc0b175fa7d3d06e4551688903a
[ "MIT" ]
null
null
null
webot/controllers/waypoints_runner/lidar_wrapper.hpp
DEIS-Tools/model-utilities
a1a38f7f8adcedc0b175fa7d3d06e4551688903a
[ "MIT" ]
6
2019-11-14T13:49:39.000Z
2019-12-04T09:36:21.000Z
webot/controllers/waypoints_runner/lidar_wrapper.hpp
DEIS-Tools/model-utilities
a1a38f7f8adcedc0b175fa7d3d06e4551688903a
[ "MIT" ]
2
2019-11-20T18:01:34.000Z
2020-05-05T07:18:37.000Z
/*Copyright 2019 Anders Madsen, Emil Jørgensen Njor, Emil Stenderup Bækdahl, Frederik Baymler *Mathiesen, Nikolaj Jensen Ulrik, Simon Mejlby Virenfeldt * *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. */ #ifndef LIDAR_WRAPPER_HPP #define LIDAR_WRAPPER_HPP #include <webots/Lidar.hpp> struct LidarWrapper { webots::Lidar *lidar; int get_number_of_points() const; const float *get_range_image() const; const webots::LidarPoint *get_point_cloud() const; double get_fov() const; double get_max_range() const; double get_min_range() const; int get_resolution() const; void enable(const int time_step); bool is_enabled() const; }; #endif
43.153846
100
0.766488
DEIS-Tools
4fc8ffd7dbce8068b401550114dac7d9970c41ea
5,986
cpp
C++
src/frameworks/wilhelm/src/itf/IBassBoost.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
null
null
null
src/frameworks/wilhelm/src/itf/IBassBoost.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
null
null
null
src/frameworks/wilhelm/src/itf/IBassBoost.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2010 The Android 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. */ /* BassBoost implementation */ #include "sles_allinclusive.h" #ifdef ANDROID #include <system/audio_effects/effect_bassboost.h> #endif #define BASSBOOST_STRENGTH_MIN 0 #define BASSBOOST_STRENGTH_MAX 1000 #if defined(ANDROID) /** * returns true if this interface is not associated with an initialized BassBoost effect */ static inline bool NO_BASSBOOST(IBassBoost* v) { return (v->mBassBoostEffect == 0); } #endif static SLresult IBassBoost_SetEnabled(SLBassBoostItf self, SLboolean enabled) { SL_ENTER_INTERFACE IBassBoost *thiz = (IBassBoost *) self; interface_lock_exclusive(thiz); thiz->mEnabled = (SLboolean) enabled; #if !defined(ANDROID) result = SL_RESULT_SUCCESS; #else if (NO_BASSBOOST(thiz)) { result = SL_RESULT_CONTROL_LOST; } else { android::status_t status = thiz->mBassBoostEffect->setEnabled((bool) thiz->mEnabled); result = android_fx_statusToResult(status); } #endif interface_unlock_exclusive(thiz); SL_LEAVE_INTERFACE } static SLresult IBassBoost_IsEnabled(SLBassBoostItf self, SLboolean *pEnabled) { SL_ENTER_INTERFACE if (NULL == pEnabled) { result = SL_RESULT_PARAMETER_INVALID; } else { IBassBoost *thiz = (IBassBoost *) self; interface_lock_exclusive(thiz); #if !defined(ANDROID) SLboolean enabled = thiz->mEnabled; *pEnabled = enabled; result = SL_RESULT_SUCCESS; #else if (NO_BASSBOOST(thiz)) { result = SL_RESULT_CONTROL_LOST; } else { *pEnabled = (SLboolean) thiz->mBassBoostEffect->getEnabled(); result = SL_RESULT_SUCCESS; } #endif interface_unlock_exclusive(thiz); } SL_LEAVE_INTERFACE } static SLresult IBassBoost_SetStrength(SLBassBoostItf self, SLpermille strength) { SL_ENTER_INTERFACE if ((BASSBOOST_STRENGTH_MIN > strength) || (BASSBOOST_STRENGTH_MAX < strength)) { result = SL_RESULT_PARAMETER_INVALID; } else { IBassBoost *thiz = (IBassBoost *) self; interface_lock_exclusive(thiz); #if !defined(ANDROID) thiz->mStrength = strength; result = SL_RESULT_SUCCESS; #else if (NO_BASSBOOST(thiz)) { result = SL_RESULT_CONTROL_LOST; } else { android::status_t status = android_bb_setParam(thiz->mBassBoostEffect, BASSBOOST_PARAM_STRENGTH, &strength); result = android_fx_statusToResult(status); } #endif interface_unlock_exclusive(thiz); } SL_LEAVE_INTERFACE } static SLresult IBassBoost_GetRoundedStrength(SLBassBoostItf self, SLpermille *pStrength) { SL_ENTER_INTERFACE if (NULL == pStrength) { result = SL_RESULT_PARAMETER_INVALID; } else { IBassBoost *thiz = (IBassBoost *) self; interface_lock_exclusive(thiz); SLpermille strength = thiz->mStrength;; #if !defined(ANDROID) result = SL_RESULT_SUCCESS; #else if (NO_BASSBOOST(thiz)) { result = SL_RESULT_CONTROL_LOST; } else { android::status_t status = android_bb_getParam(thiz->mBassBoostEffect, BASSBOOST_PARAM_STRENGTH, &strength); result = android_fx_statusToResult(status); } #endif interface_unlock_exclusive(thiz); *pStrength = strength; } SL_LEAVE_INTERFACE } static SLresult IBassBoost_IsStrengthSupported(SLBassBoostItf self, SLboolean *pSupported) { SL_ENTER_INTERFACE if (NULL == pSupported) { result = SL_RESULT_PARAMETER_INVALID; } else { #if !defined(ANDROID) *pSupported = SL_BOOLEAN_TRUE; result = SL_RESULT_SUCCESS; #else IBassBoost *thiz = (IBassBoost *) self; int32_t supported = 0; interface_lock_exclusive(thiz); if (NO_BASSBOOST(thiz)) { result = SL_RESULT_CONTROL_LOST; } else { android::status_t status = android_bb_getParam(thiz->mBassBoostEffect, BASSBOOST_PARAM_STRENGTH_SUPPORTED, &supported); result = android_fx_statusToResult(status); } interface_unlock_exclusive(thiz); *pSupported = (SLboolean) (supported != 0); #endif } SL_LEAVE_INTERFACE } static const struct SLBassBoostItf_ IBassBoost_Itf = { IBassBoost_SetEnabled, IBassBoost_IsEnabled, IBassBoost_SetStrength, IBassBoost_GetRoundedStrength, IBassBoost_IsStrengthSupported }; void IBassBoost_init(void *self) { IBassBoost *thiz = (IBassBoost *) self; thiz->mItf = &IBassBoost_Itf; thiz->mEnabled = SL_BOOLEAN_FALSE; thiz->mStrength = 0; #if defined(ANDROID) memset(&thiz->mBassBoostDescriptor, 0, sizeof(effect_descriptor_t)); // placement new (explicit constructor) (void) new (&thiz->mBassBoostEffect) android::sp<android::AudioEffect>(); #endif } void IBassBoost_deinit(void *self) { #if defined(ANDROID) IBassBoost *thiz = (IBassBoost *) self; // explicit destructor thiz->mBassBoostEffect.~sp(); #endif } bool IBassBoost_Expose(void *self) { #if defined(ANDROID) IBassBoost *thiz = (IBassBoost *) self; if (!android_fx_initEffectDescriptor(SL_IID_BASSBOOST, &thiz->mBassBoostDescriptor)) { SL_LOGE("BassBoost initialization failed."); return false; } #endif return true; }
27.458716
100
0.679419
dAck2cC2
4fc99370f30980c4192c1681f81b9f0482de01f8
122
cc
C++
main.cc
marcopush/util-cpp
560c46bae8cbfa00ef76db4bd139ede21543ccf8
[ "Apache-2.0" ]
null
null
null
main.cc
marcopush/util-cpp
560c46bae8cbfa00ef76db4bd139ede21543ccf8
[ "Apache-2.0" ]
null
null
null
main.cc
marcopush/util-cpp
560c46bae8cbfa00ef76db4bd139ede21543ccf8
[ "Apache-2.0" ]
1
2020-08-30T20:10:53.000Z
2020-08-30T20:10:53.000Z
#include "util.hh" // A basic main function to test compilation int main (int, char const* const* const) { return 0; }
17.428571
44
0.688525
marcopush
4fc99c40dbab9bdb0947d5f3b28a7c044cec2255
11,095
cpp
C++
tests/FontHostTest.cpp
fmalita/skia
8367b8cb7a6b2f163ee41365323cb219b7049b15
[ "BSD-3-Clause" ]
1
2020-02-21T01:15:42.000Z
2020-02-21T01:15:42.000Z
tests/FontHostTest.cpp
fmalita/skia
8367b8cb7a6b2f163ee41365323cb219b7049b15
[ "BSD-3-Clause" ]
null
null
null
tests/FontHostTest.cpp
fmalita/skia
8367b8cb7a6b2f163ee41365323cb219b7049b15
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Resources.h" #include "SkEndian.h" #include "SkFontStream.h" #include "SkOSFile.h" #include "SkPaint.h" #include "SkStream.h" #include "SkTypeface.h" #include "Test.h" //#define DUMP_TABLES //#define DUMP_TTC_TABLES #define kFontTableTag_head SkSetFourByteTag('h', 'e', 'a', 'd') #define kFontTableTag_hhea SkSetFourByteTag('h', 'h', 'e', 'a') #define kFontTableTag_maxp SkSetFourByteTag('m', 'a', 'x', 'p') static const struct TagSize { SkFontTableTag fTag; size_t fSize; } gKnownTableSizes[] = { { kFontTableTag_head, 54 }, { kFontTableTag_hhea, 36 }, { kFontTableTag_maxp, 32 }, }; // Test that getUnitsPerEm() agrees with a direct lookup in the 'head' table // (if that table is available). static void test_unitsPerEm(skiatest::Reporter* reporter, SkTypeface* face) { int nativeUPEM = face->getUnitsPerEm(); int tableUPEM = -1; size_t size = face->getTableSize(kFontTableTag_head); if (size) { // unitsPerEm is at offset 18 into the 'head' table. uint16_t rawUPEM; face->getTableData(kFontTableTag_head, 18, sizeof(rawUPEM), &rawUPEM); tableUPEM = SkEndian_SwapBE16(rawUPEM); } if (tableUPEM >= 0) { REPORTER_ASSERT(reporter, tableUPEM == nativeUPEM); } } // Test that countGlyphs() agrees with a direct lookup in the 'maxp' table // (if that table is available). static void test_countGlyphs(skiatest::Reporter* reporter, SkTypeface* face) { int nativeGlyphs = face->countGlyphs(); int tableGlyphs = -1; size_t size = face->getTableSize(kFontTableTag_maxp); if (size) { // glyphs is at offset 4 into the 'maxp' table. uint16_t rawGlyphs; face->getTableData(kFontTableTag_maxp, 4, sizeof(rawGlyphs), &rawGlyphs); tableGlyphs = SkEndian_SwapBE16(rawGlyphs); } if (tableGlyphs >= 0) { REPORTER_ASSERT(reporter, tableGlyphs == nativeGlyphs); } } // The following three are all the same code points in various encodings. static uint8_t utf8Chars[] = { 0x61, 0xE4, 0xB8, 0xAD, 0xD0, 0xAF, 0xD7, 0x99, 0xD7, 0x95, 0xF0, 0x9D, 0x84, 0x9E, 0x61 }; static uint16_t utf16Chars[] = { 0x0061, 0x4E2D, 0x042F, 0x05D9, 0x05D5, 0xD834, 0xDD1E, 0x0061 }; static uint32_t utf32Chars[] = { 0x00000061, 0x00004E2D, 0x0000042F, 0x000005D9, 0x000005D5, 0x0001D11E, 0x00000061 }; struct CharsToGlyphs_TestData { const void* chars; int charCount; size_t charsByteLength; SkTypeface::Encoding typefaceEncoding; const char* name; } static charsToGlyphs_TestData[] = { { utf8Chars, 7, sizeof(utf8Chars), SkTypeface::kUTF8_Encoding, "Simple UTF-8" }, { utf16Chars, 7, sizeof(utf16Chars), SkTypeface::kUTF16_Encoding, "Simple UTF-16" }, { utf32Chars, 7, sizeof(utf32Chars), SkTypeface::kUTF32_Encoding, "Simple UTF-32" }, }; // Test that SkPaint::textToGlyphs agrees with SkTypeface::charsToGlyphs. static void test_charsToGlyphs(skiatest::Reporter* reporter, SkTypeface* face) { uint16_t paintGlyphIds[256]; uint16_t faceGlyphIds[256]; for (size_t testIndex = 0; testIndex < SK_ARRAY_COUNT(charsToGlyphs_TestData); ++testIndex) { CharsToGlyphs_TestData& test = charsToGlyphs_TestData[testIndex]; SkPaint paint; paint.setTypeface(face); paint.setTextEncoding((SkPaint::TextEncoding)test.typefaceEncoding); paint.textToGlyphs(test.chars, test.charsByteLength, paintGlyphIds); face->charsToGlyphs(test.chars, test.typefaceEncoding, faceGlyphIds, test.charCount); for (int i = 0; i < test.charCount; ++i) { SkString name; face->getFamilyName(&name); SkString a; a.appendf("%s, paintGlyphIds[%d] = %d, faceGlyphIds[%d] = %d, face = %s", test.name, i, (int)paintGlyphIds[i], i, (int)faceGlyphIds[i], name.c_str()); REPORTER_ASSERT_MESSAGE(reporter, paintGlyphIds[i] == faceGlyphIds[i], a.c_str()); } } } static void test_fontstream(skiatest::Reporter* reporter, SkStream* stream, int ttcIndex) { int n = SkFontStream::GetTableTags(stream, ttcIndex, NULL); SkAutoTArray<SkFontTableTag> array(n); int n2 = SkFontStream::GetTableTags(stream, ttcIndex, array.get()); REPORTER_ASSERT(reporter, n == n2); for (int i = 0; i < n; ++i) { #ifdef DUMP_TTC_TABLES SkString str; SkFontTableTag t = array[i]; str.appendUnichar((t >> 24) & 0xFF); str.appendUnichar((t >> 16) & 0xFF); str.appendUnichar((t >> 8) & 0xFF); str.appendUnichar((t >> 0) & 0xFF); SkDebugf("[%d:%d] '%s'\n", ttcIndex, i, str.c_str()); #endif size_t size = SkFontStream::GetTableSize(stream, ttcIndex, array[i]); for (size_t j = 0; j < SK_ARRAY_COUNT(gKnownTableSizes); ++j) { if (gKnownTableSizes[j].fTag == array[i]) { REPORTER_ASSERT(reporter, gKnownTableSizes[j].fSize == size); } } } } static void test_fontstream(skiatest::Reporter* reporter, SkStream* stream) { int count = SkFontStream::CountTTCEntries(stream); #ifdef DUMP_TTC_TABLES SkDebugf("CountTTCEntries %d\n", count); #endif for (int i = 0; i < count; ++i) { test_fontstream(reporter, stream, i); } } static void test_fontstream(skiatest::Reporter* reporter) { // This test cannot run if there is no resource path. SkString resourcePath = GetResourcePath(); if (resourcePath.isEmpty()) { SkDebugf("Could not run fontstream test because resourcePath not specified."); return; } SkString filename = SkOSPath::Join(resourcePath.c_str(), "test.ttc"); SkFILEStream stream(filename.c_str()); if (stream.isValid()) { test_fontstream(reporter, &stream); } else { SkDebugf("Could not run fontstream test because test.ttc not found."); } } static void test_tables(skiatest::Reporter* reporter, SkTypeface* face) { if (false) { // avoid bit rot, suppress warning SkFontID fontID = face->uniqueID(); REPORTER_ASSERT(reporter, fontID); } int count = face->countTables(); SkAutoTMalloc<SkFontTableTag> storage(count); SkFontTableTag* tags = storage.get(); int count2 = face->getTableTags(tags); REPORTER_ASSERT(reporter, count2 == count); for (int i = 0; i < count; ++i) { size_t size = face->getTableSize(tags[i]); REPORTER_ASSERT(reporter, size > 0); #ifdef DUMP_TABLES char name[5]; name[0] = (tags[i] >> 24) & 0xFF; name[1] = (tags[i] >> 16) & 0xFF; name[2] = (tags[i] >> 8) & 0xFF; name[3] = (tags[i] >> 0) & 0xFF; name[4] = 0; SkDebugf("%s %d\n", name, size); #endif for (size_t j = 0; j < SK_ARRAY_COUNT(gKnownTableSizes); ++j) { if (gKnownTableSizes[j].fTag == tags[i]) { REPORTER_ASSERT(reporter, gKnownTableSizes[j].fSize == size); } } // do we get the same size from GetTableData and GetTableSize { SkAutoMalloc data(size); size_t size2 = face->getTableData(tags[i], 0, size, data.get()); REPORTER_ASSERT(reporter, size2 == size); } } } static void test_tables(skiatest::Reporter* reporter) { static const char* const gNames[] = { NULL, // default font "Arial", "Times", "Times New Roman", "Helvetica", "Courier", "Courier New", "Terminal", "MS Sans Serif", }; for (size_t i = 0; i < SK_ARRAY_COUNT(gNames); ++i) { SkAutoTUnref<SkTypeface> face(SkTypeface::CreateFromName(gNames[i], SkTypeface::kNormal)); if (face) { #ifdef DUMP_TABLES SkDebugf("%s\n", gNames[i]); #endif test_tables(reporter, face); test_unitsPerEm(reporter, face); test_countGlyphs(reporter, face); test_charsToGlyphs(reporter, face); } } } /* * Verifies that the advance values returned by generateAdvance and * generateMetrics match. */ static void test_advances(skiatest::Reporter* reporter) { static const char* const faces[] = { NULL, // default font "Arial", "Times", "Times New Roman", "Helvetica", "Courier", "Courier New", "Verdana", "monospace", }; static const struct { SkPaint::Hinting hinting; unsigned flags; } settings[] = { { SkPaint::kNo_Hinting, 0 }, { SkPaint::kNo_Hinting, SkPaint::kLinearText_Flag }, { SkPaint::kNo_Hinting, SkPaint::kSubpixelText_Flag }, { SkPaint::kSlight_Hinting, 0 }, { SkPaint::kSlight_Hinting, SkPaint::kLinearText_Flag }, { SkPaint::kSlight_Hinting, SkPaint::kSubpixelText_Flag }, { SkPaint::kNormal_Hinting, 0 }, { SkPaint::kNormal_Hinting, SkPaint::kLinearText_Flag }, { SkPaint::kNormal_Hinting, SkPaint::kSubpixelText_Flag }, }; static const struct { SkScalar fScaleX; SkScalar fSkewX; } gScaleRec[] = { { SK_Scalar1, 0 }, { SK_Scalar1/2, 0 }, // these two exercise obliquing (skew) { SK_Scalar1, -SK_Scalar1/4 }, { SK_Scalar1/2, -SK_Scalar1/4 }, }; SkPaint paint; char txt[] = "long.text.with.lots.of.dots."; for (size_t i = 0; i < SK_ARRAY_COUNT(faces); i++) { SkAutoTUnref<SkTypeface> face(SkTypeface::CreateFromName(faces[i], SkTypeface::kNormal)); paint.setTypeface(face); for (size_t j = 0; j < SK_ARRAY_COUNT(settings); j++) { paint.setHinting(settings[j].hinting); paint.setLinearText((settings[j].flags & SkPaint::kLinearText_Flag) != 0); paint.setSubpixelText((settings[j].flags & SkPaint::kSubpixelText_Flag) != 0); for (size_t k = 0; k < SK_ARRAY_COUNT(gScaleRec); ++k) { paint.setTextScaleX(gScaleRec[k].fScaleX); paint.setTextSkewX(gScaleRec[k].fSkewX); SkRect bounds; // For no hinting and light hinting this should take the // optimized generateAdvance path. SkScalar width1 = paint.measureText(txt, strlen(txt)); // Requesting the bounds forces a generateMetrics call. SkScalar width2 = paint.measureText(txt, strlen(txt), &bounds); // SkDebugf("Font: %s, generateAdvance: %f, generateMetrics: %f\n", // faces[i], SkScalarToFloat(width1), SkScalarToFloat(width2)); REPORTER_ASSERT(reporter, width1 == width2); } } } } DEF_TEST(FontHost, reporter) { test_tables(reporter); test_fontstream(reporter); test_advances(reporter); } // need tests for SkStrSearch
35.790323
122
0.616133
fmalita
4fcb86b80a848674c44c68665b88b0a8a8f621ae
83,462
cc
C++
src/bbdep_sm.cc
poluyan/PEPSGO
d1039bf0362bddca6247ffadf7b2124e6cfb64cf
[ "Apache-2.0" ]
1
2021-06-07T16:07:04.000Z
2021-06-07T16:07:04.000Z
src/bbdep_sm.cc
poluyan/PEPSGO
d1039bf0362bddca6247ffadf7b2124e6cfb64cf
[ "Apache-2.0" ]
null
null
null
src/bbdep_sm.cc
poluyan/PEPSGO
d1039bf0362bddca6247ffadf7b2124e6cfb64cf
[ "Apache-2.0" ]
null
null
null
/************************************************************************** Copyright © 2018 Sergey Poluyan <svpoluyan@gmail.com> 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 <omp.h> #include <bbdep_sm.hh> #include <bbutils.hh> #include <data_io.hh> namespace pepsgo { namespace bbdep { double pdf_normal_dst(double x, double mu, double sigma) { double ps = 2 * sigma * sigma; double e = exp(-std::pow(x - mu, 2.0) / ps); double C = std::sqrt(2.0 * ps * numeric::NumericTraits<core::Real>::pi()); return e / C; } void plot_chi1_all(pepsgo::bbdep::BBDEP_Dunbrack_sm& bbdep_sm) { auto ser = bbdep_sm.get_chi1_all(bbdep_sm.aa_sm_1d[0].lib); auto val = bbdep_sm.get_chi1_all(bbdep_sm.aa_sm_1d[1].lib); auto cys = bbdep_sm.get_chi1_all(bbdep_sm.aa_sm_1d[2].lib); auto thr = bbdep_sm.get_chi1_all(bbdep_sm.aa_sm_1d[3].lib); std::vector<std::vector<double>> to_plot; for(size_t i = 0; i != ser.pdf.size(); i++) { std::vector<double> temp = {ser.grid[i], ser.pdf[i], val.pdf[i], cys.pdf[i], thr.pdf[i]}; if(temp[0] < 0) { temp[0] += 360.0; } to_plot.push_back(temp); } pepsgo::write_default2d("maps/bbdep/SVCT.dat", to_plot, 4); } BBDEP_Dunbrack_sm::BBDEP_Dunbrack_sm() { uniform_peaks = true; } void BBDEP_Dunbrack_sm::set_path(std::string path_to_files) { path = path_to_files; } void BBDEP_Dunbrack_sm::set_step(size_t step) { cdf_grid_step = step; } void BBDEP_Dunbrack_sm::create_cdf_sums(core::chemical::AA amino_acid) { switch(amino_acid) { // 0 ser, 1 val, 2 cys, 3 thr case core::chemical::aa_ser: fill_grid_and_states_and_create_cdf_chi1(aa_sm_1d[0].lib, aa_sm_1d[0].lib_grid, aa_sm_1d[0].lib_independent, aa_sm_1d[0].lib_cdf_sum_all, aa_sm_1d[0].lib_states); break; case core::chemical::aa_val: fill_grid_and_states_and_create_cdf_chi1(aa_sm_1d[1].lib, aa_sm_1d[1].lib_grid, aa_sm_1d[1].lib_independent, aa_sm_1d[1].lib_cdf_sum_all, aa_sm_1d[1].lib_states); break; case core::chemical::aa_cys: fill_grid_and_states_and_create_cdf_chi1(aa_sm_1d[2].lib, aa_sm_1d[2].lib_grid, aa_sm_1d[2].lib_independent, aa_sm_1d[2].lib_cdf_sum_all, aa_sm_1d[2].lib_states); break; case core::chemical::aa_thr: fill_grid_and_states_and_create_cdf_chi1(aa_sm_1d[3].lib, aa_sm_1d[3].lib_grid, aa_sm_1d[3].lib_independent, aa_sm_1d[3].lib_cdf_sum_all, aa_sm_1d[3].lib_states); break; // 0 trp, 1 his, 2 asn, 3 asp, 4 phe, 5 tyr, 6 ile, 7 leu case core::chemical::aa_trp: fill_grid_and_states_and_create_cdf_chi2(aa_sm_2d[0].lib, aa_sm_2d[0].lib_grid, aa_sm_2d[0].lib_independent, aa_sm_2d[0].lib_cdf_sum_all, aa_sm_2d[0].lib_chi2_depend_chi1, aa_sm_2d[0].lib_states_chi1); break; case core::chemical::aa_his: fill_grid_and_states_and_create_cdf_chi2(aa_sm_2d[1].lib, aa_sm_2d[1].lib_grid, aa_sm_2d[1].lib_independent, aa_sm_2d[1].lib_cdf_sum_all, aa_sm_2d[1].lib_chi2_depend_chi1, aa_sm_2d[1].lib_states_chi1); break; case core::chemical::aa_asn: fill_grid_and_states_and_create_cdf_chi2(aa_sm_2d[2].lib, aa_sm_2d[2].lib_grid, aa_sm_2d[2].lib_independent, aa_sm_2d[2].lib_cdf_sum_all, aa_sm_2d[2].lib_chi2_depend_chi1, aa_sm_2d[2].lib_states_chi1); break; case core::chemical::aa_asp: fill_grid_and_states_and_create_cdf_chi2(aa_sm_2d[3].lib, aa_sm_2d[3].lib_grid, aa_sm_2d[3].lib_independent, aa_sm_2d[3].lib_cdf_sum_all, aa_sm_2d[3].lib_chi2_depend_chi1, aa_sm_2d[3].lib_states_chi1); break; case core::chemical::aa_phe: fill_grid_and_states_and_create_cdf_chi2(aa_sm_2d[4].lib, aa_sm_2d[4].lib_grid, aa_sm_2d[4].lib_independent, aa_sm_2d[4].lib_cdf_sum_all, aa_sm_2d[4].lib_chi2_depend_chi1, aa_sm_2d[4].lib_states_chi1); break; case core::chemical::aa_tyr: fill_grid_and_states_and_create_cdf_chi2(aa_sm_2d[5].lib, aa_sm_2d[5].lib_grid, aa_sm_2d[5].lib_independent, aa_sm_2d[5].lib_cdf_sum_all, aa_sm_2d[5].lib_chi2_depend_chi1, aa_sm_2d[5].lib_states_chi1); break; case core::chemical::aa_ile: fill_grid_and_states_and_create_cdf_chi2(aa_sm_2d[6].lib, aa_sm_2d[6].lib_grid, aa_sm_2d[6].lib_independent, aa_sm_2d[6].lib_cdf_sum_all, aa_sm_2d[6].lib_chi2_depend_chi1, aa_sm_2d[6].lib_states_chi1); break; case core::chemical::aa_leu: fill_grid_and_states_and_create_cdf_chi2(aa_sm_2d[7].lib, aa_sm_2d[7].lib_grid, aa_sm_2d[7].lib_independent, aa_sm_2d[7].lib_cdf_sum_all, aa_sm_2d[7].lib_chi2_depend_chi1, aa_sm_2d[7].lib_states_chi1); break; // 0 met, 1 glu, 2 gln, 3 pro case core::chemical::aa_met: fill_grid_and_states_and_create_cdf_chi3( aa_sm_3d[0].lib, aa_sm_3d[0].lib_grid, aa_sm_3d[0].lib_independent, aa_sm_3d[0].lib_cdf_sum_all, aa_sm_3d[0].lib_chi2_depend_chi1, aa_sm_3d[0].lib_chi3_depend_chi12, aa_sm_3d[0].lib_states_chi1, aa_sm_3d[0].lib_states_chi2); break; case core::chemical::aa_glu: fill_grid_and_states_and_create_cdf_chi3( aa_sm_3d[1].lib, aa_sm_3d[1].lib_grid, aa_sm_3d[1].lib_independent, aa_sm_3d[1].lib_cdf_sum_all, aa_sm_3d[1].lib_chi2_depend_chi1, aa_sm_3d[1].lib_chi3_depend_chi12, aa_sm_3d[1].lib_states_chi1, aa_sm_3d[1].lib_states_chi2); break; case core::chemical::aa_gln: fill_grid_and_states_and_create_cdf_chi3( aa_sm_3d[2].lib, aa_sm_3d[2].lib_grid, aa_sm_3d[2].lib_independent, aa_sm_3d[2].lib_cdf_sum_all, aa_sm_3d[2].lib_chi2_depend_chi1, aa_sm_3d[2].lib_chi3_depend_chi12, aa_sm_3d[2].lib_states_chi1, aa_sm_3d[2].lib_states_chi2); break; case core::chemical::aa_pro: fill_grid_and_states_and_create_cdf_chi3( aa_sm_3d[3].lib, aa_sm_3d[3].lib_grid, aa_sm_3d[3].lib_independent, aa_sm_3d[3].lib_cdf_sum_all, aa_sm_3d[3].lib_chi2_depend_chi1, aa_sm_3d[3].lib_chi3_depend_chi12, aa_sm_3d[3].lib_states_chi1, aa_sm_3d[3].lib_states_chi2); break; // 0 arg, 1 lys case core::chemical::aa_arg: { fill_grid_and_states_and_create_cdf_chi4( aa_sm_4d[0].lib, aa_sm_4d[0].lib_grid, aa_sm_4d[0].lib_independent, aa_sm_4d[0].lib_cdf_sum_all, aa_sm_4d[0].lib_chi2_depend_chi1, aa_sm_4d[0].lib_chi3_depend_chi12, aa_sm_4d[0].lib_chi4_depend_chi123, aa_sm_4d[0].lib_states_chi1, aa_sm_4d[0].lib_states_chi2, aa_sm_4d[0].lib_states_chi3); fill_impossible_conformations(aa_sm_4d[0].lib, aa_sm_4d[0].lib_impossible_conformations); break; } case core::chemical::aa_lys: { fill_grid_and_states_and_create_cdf_chi4( aa_sm_4d[1].lib, aa_sm_4d[1].lib_grid, aa_sm_4d[1].lib_independent, aa_sm_4d[1].lib_cdf_sum_all, aa_sm_4d[1].lib_chi2_depend_chi1, aa_sm_4d[1].lib_chi3_depend_chi12, aa_sm_4d[1].lib_chi4_depend_chi123, aa_sm_4d[1].lib_states_chi1, aa_sm_4d[1].lib_states_chi2, aa_sm_4d[1].lib_states_chi3); fill_impossible_conformations(aa_sm_4d[1].lib, aa_sm_4d[1].lib_impossible_conformations); break; } default: break; } } // amino acids in 1letter code format void BBDEP_Dunbrack_sm::initialize_all(bool create_cdf_sum, std::string amino_acids, int threads_number) { amino_acids.erase(std::remove(amino_acids.begin(), amino_acids.end(), 'A'), amino_acids.end()); amino_acids.erase(std::remove(amino_acids.begin(), amino_acids.end(), 'G'), amino_acids.end()); load_data_sm(amino_acids); if(create_cdf_sum) { int n = amino_acids.size(); omp_set_dynamic(0); omp_set_num_threads(threads_number); #pragma omp parallel for for(int i = 0; i < n; ++i) { create_cdf_sums(core::chemical::aa_from_oneletter_code(amino_acids[i])); } // // 0 ser, 1 val, 2 cys, 3 thr // if(amino_acids.find("S") != std::string::npos) // fill_grid_and_states_and_create_cdf_chi1(aa_sm_1d[0].lib, aa_sm_1d[0].lib_grid, // aa_sm_1d[0].lib_independent, // aa_sm_1d[0].lib_cdf_sum_all, // aa_sm_1d[0].lib_states); // if(amino_acids.find("V") != std::string::npos) // fill_grid_and_states_and_create_cdf_chi1(aa_sm_1d[1].lib, aa_sm_1d[1].lib_grid, // aa_sm_1d[1].lib_independent, // aa_sm_1d[1].lib_cdf_sum_all, // aa_sm_1d[1].lib_states); // if(amino_acids.find("C") != std::string::npos) // fill_grid_and_states_and_create_cdf_chi1(aa_sm_1d[2].lib, aa_sm_1d[2].lib_grid, // aa_sm_1d[2].lib_independent, // aa_sm_1d[2].lib_cdf_sum_all, // aa_sm_1d[2].lib_states); // if(amino_acids.find("T") != std::string::npos) // fill_grid_and_states_and_create_cdf_chi1(aa_sm_1d[3].lib, aa_sm_1d[3].lib_grid, // aa_sm_1d[3].lib_independent, // aa_sm_1d[3].lib_cdf_sum_all, // aa_sm_1d[3].lib_states); // // // 0 trp, 1 his, 2 asn, 3 asp, 4 phe, 5 tyr, 6 ile, 7 leu // if(amino_acids.find("W") != std::string::npos) // fill_grid_and_states_and_create_cdf_chi2(aa_sm_2d[0].lib, aa_sm_2d[0].lib_grid, // aa_sm_2d[0].lib_independent, // aa_sm_2d[0].lib_cdf_sum_all, // aa_sm_2d[0].lib_chi2_depend_chi1, // aa_sm_2d[0].lib_states_chi1); // if(amino_acids.find("H") != std::string::npos) // fill_grid_and_states_and_create_cdf_chi2(aa_sm_2d[1].lib, aa_sm_2d[1].lib_grid, // aa_sm_2d[1].lib_independent, // aa_sm_2d[1].lib_cdf_sum_all, // aa_sm_2d[1].lib_chi2_depend_chi1, // aa_sm_2d[1].lib_states_chi1); // if(amino_acids.find("N") != std::string::npos) // fill_grid_and_states_and_create_cdf_chi2(aa_sm_2d[2].lib, aa_sm_2d[2].lib_grid, // aa_sm_2d[2].lib_independent, // aa_sm_2d[2].lib_cdf_sum_all, // aa_sm_2d[2].lib_chi2_depend_chi1, // aa_sm_2d[2].lib_states_chi1); // if(amino_acids.find("D") != std::string::npos) // fill_grid_and_states_and_create_cdf_chi2(aa_sm_2d[3].lib, aa_sm_2d[3].lib_grid, // aa_sm_2d[3].lib_independent, // aa_sm_2d[3].lib_cdf_sum_all, // aa_sm_2d[3].lib_chi2_depend_chi1, // aa_sm_2d[3].lib_states_chi1); // if(amino_acids.find("F") != std::string::npos) // fill_grid_and_states_and_create_cdf_chi2(aa_sm_2d[4].lib, aa_sm_2d[4].lib_grid, // aa_sm_2d[4].lib_independent, // aa_sm_2d[4].lib_cdf_sum_all, // aa_sm_2d[4].lib_chi2_depend_chi1, // aa_sm_2d[4].lib_states_chi1); // if(amino_acids.find("Y") != std::string::npos) // fill_grid_and_states_and_create_cdf_chi2(aa_sm_2d[5].lib, aa_sm_2d[5].lib_grid, // aa_sm_2d[5].lib_independent, // aa_sm_2d[5].lib_cdf_sum_all, // aa_sm_2d[5].lib_chi2_depend_chi1, // aa_sm_2d[5].lib_states_chi1); // if(amino_acids.find("I") != std::string::npos) // fill_grid_and_states_and_create_cdf_chi2(aa_sm_2d[6].lib, aa_sm_2d[6].lib_grid, // aa_sm_2d[6].lib_independent, // aa_sm_2d[6].lib_cdf_sum_all, // aa_sm_2d[6].lib_chi2_depend_chi1, // aa_sm_2d[6].lib_states_chi1); // if(amino_acids.find("L") != std::string::npos) // fill_grid_and_states_and_create_cdf_chi2(aa_sm_2d[7].lib, aa_sm_2d[7].lib_grid, // aa_sm_2d[7].lib_independent, // aa_sm_2d[7].lib_cdf_sum_all, // aa_sm_2d[7].lib_chi2_depend_chi1, // aa_sm_2d[7].lib_states_chi1); // // // 0 met, 1 glu, 2 gln, 3 pro // if(amino_acids.find("M") != std::string::npos) // fill_grid_and_states_and_create_cdf_chi3( // aa_sm_3d[0].lib, // aa_sm_3d[0].lib_grid, // aa_sm_3d[0].lib_independent, // aa_sm_3d[0].lib_cdf_sum_all, // aa_sm_3d[0].lib_chi2_depend_chi1, // aa_sm_3d[0].lib_chi3_depend_chi12, // aa_sm_3d[0].lib_states_chi1, // aa_sm_3d[0].lib_states_chi2); // if(amino_acids.find("E") != std::string::npos) // fill_grid_and_states_and_create_cdf_chi3( // aa_sm_3d[1].lib, // aa_sm_3d[1].lib_grid, // aa_sm_3d[1].lib_independent, // aa_sm_3d[1].lib_cdf_sum_all, // aa_sm_3d[1].lib_chi2_depend_chi1, // aa_sm_3d[1].lib_chi3_depend_chi12, // aa_sm_3d[1].lib_states_chi1, // aa_sm_3d[1].lib_states_chi2); // if(amino_acids.find("Q") != std::string::npos) // fill_grid_and_states_and_create_cdf_chi3( // aa_sm_3d[2].lib, // aa_sm_3d[2].lib_grid, // aa_sm_3d[2].lib_independent, // aa_sm_3d[2].lib_cdf_sum_all, // aa_sm_3d[2].lib_chi2_depend_chi1, // aa_sm_3d[2].lib_chi3_depend_chi12, // aa_sm_3d[2].lib_states_chi1, // aa_sm_3d[2].lib_states_chi2); // if(amino_acids.find("P") != std::string::npos) // fill_grid_and_states_and_create_cdf_chi3( // aa_sm_3d[3].lib, // aa_sm_3d[3].lib_grid, // aa_sm_3d[3].lib_independent, // aa_sm_3d[3].lib_cdf_sum_all, // aa_sm_3d[3].lib_chi2_depend_chi1, // aa_sm_3d[3].lib_chi3_depend_chi12, // aa_sm_3d[3].lib_states_chi1, // aa_sm_3d[3].lib_states_chi2); // // // 0 arg, 1 lys // if(amino_acids.find("R") != std::string::npos) // { // fill_grid_and_states_and_create_cdf_chi4( // aa_sm_4d[0].lib, // aa_sm_4d[0].lib_grid, // aa_sm_4d[0].lib_independent, // aa_sm_4d[0].lib_cdf_sum_all, // aa_sm_4d[0].lib_chi2_depend_chi1, // aa_sm_4d[0].lib_chi3_depend_chi12, // aa_sm_4d[0].lib_chi4_depend_chi123, // aa_sm_4d[0].lib_states_chi1, // aa_sm_4d[0].lib_states_chi2, // aa_sm_4d[0].lib_states_chi3); // fill_impossible_conformations(aa_sm_4d[0].lib, aa_sm_4d[0].lib_impossible_conformations); // } // if(amino_acids.find("K") != std::string::npos) // { // fill_grid_and_states_and_create_cdf_chi4( // aa_sm_4d[1].lib, // aa_sm_4d[1].lib_grid, // aa_sm_4d[1].lib_independent, // aa_sm_4d[1].lib_cdf_sum_all, // aa_sm_4d[1].lib_chi2_depend_chi1, // aa_sm_4d[1].lib_chi3_depend_chi12, // aa_sm_4d[1].lib_chi4_depend_chi123, // aa_sm_4d[1].lib_states_chi1, // aa_sm_4d[1].lib_states_chi2, // aa_sm_4d[1].lib_states_chi3); // fill_impossible_conformations(aa_sm_4d[1].lib, aa_sm_4d[1].lib_impossible_conformations); // } } } void BBDEP_Dunbrack_sm::load_data_sm(std::string amino_acids) { aa_sm_1d.resize(4); // 0 ser, 1 val, 2 cys, 3 thr aa_sm_2d.resize(8); // 0 trp, 1 his, 2 asn, 3 asp, 4 phe, 5 tyr, 6 ile, 7 leu aa_sm_3d.resize(4); // 0 met, 1 glu, 2 gln, 3 pro aa_sm_4d.resize(2); // 0 arg, 1 lys // 0 ser, 1 val, 2 cys, 3 thr if(amino_acids.find("S") != std::string::npos) pepsgo::bbdep::load_data_sm(path + "ser.bbdep.rotamers.lib.gz", aa_sm_1d[0].lib, aa_sm_1d[0].libn); if(amino_acids.find("V") != std::string::npos) pepsgo::bbdep::load_data_sm(path + "val.bbdep.rotamers.lib.gz", aa_sm_1d[1].lib, aa_sm_1d[1].libn); if(amino_acids.find("C") != std::string::npos) pepsgo::bbdep::load_data_sm(path + "cys.bbdep.rotamers.lib.gz", aa_sm_1d[2].lib, aa_sm_1d[2].libn); if(amino_acids.find("T") != std::string::npos) pepsgo::bbdep::load_data_sm(path + "thr.bbdep.rotamers.lib.gz", aa_sm_1d[3].lib, aa_sm_1d[3].libn); // 0 trp, 1 his, 2 asn, 3 asp, 4 phe, 5 tyr, 6 ile, 7 leu if(amino_acids.find("W") != std::string::npos) pepsgo::bbdep::load_data_sm(path + "trp.bbdep.rotamers.lib.gz", aa_sm_2d[0].lib, aa_sm_2d[0].libn); if(amino_acids.find("H") != std::string::npos) pepsgo::bbdep::load_data_sm(path + "his.bbdep.rotamers.lib.gz", aa_sm_2d[1].lib, aa_sm_2d[1].libn); if(amino_acids.find("N") != std::string::npos) pepsgo::bbdep::load_data_sm(path + "asn.bbdep.rotamers.lib.gz", aa_sm_2d[2].lib, aa_sm_2d[2].libn); if(amino_acids.find("D") != std::string::npos) pepsgo::bbdep::load_data_sm(path + "asp.bbdep.rotamers.lib.gz", aa_sm_2d[3].lib, aa_sm_2d[3].libn); if(amino_acids.find("F") != std::string::npos) pepsgo::bbdep::load_data_sm(path + "phe.bbdep.rotamers.lib.gz", aa_sm_2d[4].lib, aa_sm_2d[4].libn); if(amino_acids.find("Y") != std::string::npos) pepsgo::bbdep::load_data_sm(path + "tyr.bbdep.rotamers.lib.gz", aa_sm_2d[5].lib, aa_sm_2d[5].libn); if(amino_acids.find("I") != std::string::npos) pepsgo::bbdep::load_data_sm(path + "ile.bbdep.rotamers.lib.gz", aa_sm_2d[6].lib, aa_sm_2d[6].libn); if(amino_acids.find("L") != std::string::npos) pepsgo::bbdep::load_data_sm(path + "leu.bbdep.rotamers.lib.gz", aa_sm_2d[7].lib, aa_sm_2d[7].libn); // 0 met, 1 glu, 2 gln, 3 pro if(amino_acids.find("M") != std::string::npos) pepsgo::bbdep::load_data_sm(path + "met.bbdep.rotamers.lib.gz", aa_sm_3d[0].lib, aa_sm_3d[0].libn); if(amino_acids.find("E") != std::string::npos) pepsgo::bbdep::load_data_sm(path + "glu.bbdep.rotamers.lib.gz", aa_sm_3d[1].lib, aa_sm_3d[1].libn); if(amino_acids.find("Q") != std::string::npos) pepsgo::bbdep::load_data_sm(path + "gln.bbdep.rotamers.lib.gz", aa_sm_3d[2].lib, aa_sm_3d[2].libn); if(amino_acids.find("P") != std::string::npos) pepsgo::bbdep::load_data_sm(path + "pro.bbdep.rotamers.lib.gz", aa_sm_3d[3].lib, aa_sm_3d[3].libn); // 0 arg, 1 lys if(amino_acids.find("R") != std::string::npos) pepsgo::bbdep::load_data_sm(path + "arg.bbdep.rotamers.lib.gz", aa_sm_4d[0].lib, aa_sm_4d[0].libn); if(amino_acids.find("K") != std::string::npos) pepsgo::bbdep::load_data_sm(path + "lys.bbdep.rotamers.lib.gz", aa_sm_4d[1].lib, aa_sm_4d[1].libn); } void BBDEP_Dunbrack_sm::fill_grid_and_states_and_create_cdf_chi1(const std::vector<bbdep::Dunbrack_data> &data, std::vector<std::pair<double, double>> &all_chi1_index, std::vector<bbutils::distribution_1d> &all_independent, std::vector<std::vector<bbutils::distribution_1d>> &all_chi1_value, std::vector<std::vector<double>> &states) { std::vector<Dunbrack_data> complete_independent(data.begin(), data.end()); all_independent.push_back(get_chi1_all(complete_independent)); for(auto i = data.begin(); i != data.end();) { bbdep::Dunbrack_data search_data; search_data.Phi = i->Phi; search_data.Psi = i->Psi; auto p = std::equal_range( i, data.end(), search_data, [](const bbdep::Dunbrack_data &lhs, const bbdep::Dunbrack_data &rhs) -> bool { return lhs.Phi < rhs.Phi; }); auto q = std::equal_range(p.first, p.second, search_data, [](const bbdep::Dunbrack_data &lhs, const bbdep::Dunbrack_data &rhs) -> bool { return lhs.Psi < rhs.Psi; }); std::vector<bbdep::Dunbrack_data> temp(q.first, q.second); all_chi1_index.push_back(std::make_pair(search_data.Phi, search_data.Psi)); std::vector<bbutils::distribution_1d> temp2; temp2.push_back(get_chi1_all(temp)); all_chi1_value.push_back(temp2); //states std::vector<double> temp3; for(size_t j = 1; j != 4; j++) { std::vector<bbdep::Dunbrack_data> matches; std::copy_if(q.first, q.second, std::back_inserter(matches), [&](const bbdep::Dunbrack_data &value) -> bool {if(j == value.r1) return true; else return false; }); if(matches.size() != 1) std::cout << "wrong fill states 1d" << std::endl; temp3.push_back(matches.front().chi1Val < 0 ? matches.front().chi1Val + 360.0 : matches.front().chi1Val); } states.push_back(temp3); i = q.second; } } void BBDEP_Dunbrack_sm::fill_grid_and_states_and_create_cdf_chi2(const std::vector<bbdep::Dunbrack_data> &data, std::vector<std::pair<double, double>> &all_chi1_index, std::vector<bbutils::distribution_1d> &all_independent, std::vector<std::vector<bbutils::distribution_1d>> &all_chi12_value, std::vector<std::vector<bbutils::distribution_1d>> &chi2_depend_chi1, std::vector<std::vector<double>> &states) { chi2_depend_chi1.resize(3); std::vector<Dunbrack_data> complete_independent(data.begin(), data.end()); all_independent.push_back(get_chi1_all(complete_independent)); all_independent.push_back(get_chi2_all(complete_independent)); for(auto i = data.begin(); i != data.end();) { bbdep::Dunbrack_data search_data; search_data.Phi = i->Phi; search_data.Psi = i->Psi; auto p = std::equal_range( i, data.end(), search_data, [](const bbdep::Dunbrack_data &lhs, const bbdep::Dunbrack_data &rhs) -> bool { return lhs.Phi < rhs.Phi; }); auto q = std::equal_range(p.first, p.second, search_data, [](const bbdep::Dunbrack_data &lhs, const bbdep::Dunbrack_data &rhs) -> bool { return lhs.Psi < rhs.Psi; }); // range_bounds.push_back(std::make_pair(std::distance(data.begin(),q.first), // std::distance(data.begin(),q.second))); std::vector<bbdep::Dunbrack_data> temp(q.first, q.second); all_chi1_index.push_back(std::make_pair(search_data.Phi, search_data.Psi)); std::vector<bbutils::distribution_1d> temp2; temp2.push_back(get_chi1_all(temp)); temp2.push_back(get_chi2_all(temp)); all_chi12_value.push_back(temp2); for(size_t j = 1; j != 4; j++) { std::vector<bbdep::Dunbrack_data> temp3(q.first, q.second); temp3.erase( std::remove_if(temp3.begin(), temp3.end(), [j](bbdep::Dunbrack_data n) { return n.r1 != j; }), temp3.end()); if(temp3.size()) { chi2_depend_chi1[j - 1].push_back(get_chi2_all(temp3)); } else { chi2_depend_chi1[j - 1].push_back(fill_uniformly()); } } //states std::vector<double> temp4; for(size_t j = 1; j != 4; j++) { std::vector<bbdep::Dunbrack_data> matches; std::copy_if(q.first, q.second, std::back_inserter(matches), [&](const bbdep::Dunbrack_data &value) -> bool { if(j == value.r1) return true; else return false; }); double state = 0.0, sum = 0.0; for(auto &h : matches) { state += (h.chi1Val < 0 ? h.chi1Val + 360.0 : h.chi1Val) * h.Probabil; sum += h.Probabil; } state = state / sum; temp4.push_back(state); } states.push_back(temp4); i = q.second; } } void BBDEP_Dunbrack_sm::fill_grid_and_states_and_create_cdf_chi3(const std::vector<bbdep::Dunbrack_data> &data, std::vector<std::pair<double, double>> &all_chi1_index, std::vector<bbutils::distribution_1d> &all_independent, std::vector<std::vector<bbutils::distribution_1d>> &all_chi123_value, std::vector<std::vector<bbutils::distribution_1d>> &chi2_depend_chi1, std::vector<std::vector<std::vector<bbutils::distribution_1d>>> &chi3_depend_chi12, std::vector<std::vector<double>> &chi1_states, std::vector<std::vector<std::vector<double>>> &chi2_states) { chi2_depend_chi1.resize(3); chi3_depend_chi12.resize(3); for(size_t i = 0; i != chi3_depend_chi12.size(); i++) { chi3_depend_chi12[i].resize(3); } std::vector<Dunbrack_data> complete_independent(data.begin(), data.end()); all_independent.push_back(get_chi1_all(complete_independent)); all_independent.push_back(get_chi2_all(complete_independent)); all_independent.push_back(get_chi3_all(complete_independent)); for(auto i = data.begin(); i != data.end();) { bbdep::Dunbrack_data search_data; search_data.Phi = i->Phi; search_data.Psi = i->Psi; auto p = std::equal_range( i, data.end(), search_data, [](const bbdep::Dunbrack_data &lhs, const bbdep::Dunbrack_data &rhs) -> bool { return lhs.Phi < rhs.Phi; }); auto q = std::equal_range(p.first, p.second, search_data, [](const bbdep::Dunbrack_data &lhs, const bbdep::Dunbrack_data &rhs) -> bool { return lhs.Psi < rhs.Psi; }); std::vector<bbdep::Dunbrack_data> temp(q.first, q.second); all_chi1_index.push_back(std::make_pair(search_data.Phi, search_data.Psi)); std::vector<bbutils::distribution_1d> temp2; temp2.push_back(get_chi1_all(temp)); temp2.push_back(get_chi2_all(temp)); temp2.push_back(get_chi3_all(temp)); all_chi123_value.push_back(temp2); for(size_t j = 1; j != 4; j++) { std::vector<bbdep::Dunbrack_data> temp3(q.first, q.second); temp3.erase( std::remove_if(temp3.begin(), temp3.end(), [j](bbdep::Dunbrack_data n) { return n.r1 != j; }), temp3.end()); chi2_depend_chi1[j - 1].push_back(get_chi2_all(temp3)); } for(size_t j = 1; j != 4; j++) { for(size_t k = 1; k != 4; k++) { std::vector<bbdep::Dunbrack_data> temp3(q.first, q.second); temp3.erase(std::remove_if(temp3.begin(), temp3.end(), [j, k](bbdep::Dunbrack_data n) { return (n.r1 != j || n.r2 != k); }), temp3.end()); if(temp3.size()) { chi3_depend_chi12[j - 1][k - 1].push_back(get_chi3_all(temp3)); } else { chi3_depend_chi12[j - 1][k - 1].push_back(fill_uniformly()); } } } //states chi1 std::vector<double> temp4; for(size_t j = 1; j != 4; j++) { std::vector<bbdep::Dunbrack_data> matches; std::copy_if(q.first, q.second, std::back_inserter(matches), [&](const bbdep::Dunbrack_data &value) -> bool { if(j == value.r1) return true; else return false; }); if(!matches.size()) continue; double state = 0.0, sum = 0.0; for(auto &h : matches) { state += (h.chi1Val < 0 ? h.chi1Val + 360.0 : h.chi1Val) * h.Probabil; sum += h.Probabil; } temp4.push_back(state / sum); } chi1_states.push_back(temp4); //states chi2 std::vector<std::vector<double>> temp5; for(size_t j = 1; j != 4; j++) { std::vector<double> temp6; for(size_t k = 1; k != 4; k++) { std::vector<bbdep::Dunbrack_data> matches; std::copy_if(q.first, q.second, std::back_inserter(matches), [&](const bbdep::Dunbrack_data &value) -> bool { if(j == value.r1 && k == value.r2) return true; else return false; }); if(!matches.size()) continue; double state = 0.0, sum = 0.0; for(auto &h : matches) { state += (h.chi2Val < 0 ? h.chi2Val + 360.0 : h.chi2Val) * h.Probabil; sum += h.Probabil; } temp6.push_back(state / sum); } temp5.push_back(temp6); } chi2_states.push_back(temp5); i = q.second; } } void BBDEP_Dunbrack_sm::fill_grid_and_states_and_create_cdf_chi4(const std::vector<bbdep::Dunbrack_data> &data, std::vector<std::pair<double, double>> &all_chi1_index, std::vector<bbutils::distribution_1d> &all_independent, std::vector<std::vector<bbutils::distribution_1d>> &all_chi1234_value, std::vector<std::vector<bbutils::distribution_1d>> &chi2_depend_chi1, std::vector<std::vector<std::vector<bbutils::distribution_1d>>> &chi3_depend_chi12, std::vector<std::vector<std::vector<std::vector<bbutils::distribution_1d>>>> &chi4_depend_chi123, std::vector<std::vector<double>> &chi1_states, std::vector<std::vector<std::vector<double>>> &chi2_states, std::vector<std::vector<std::vector<std::vector<double>>>> &chi3_states) { chi2_depend_chi1.resize(3); chi3_depend_chi12.resize(3); for(size_t i = 0; i != chi3_depend_chi12.size(); i++) { chi3_depend_chi12[i].resize(3); } chi4_depend_chi123.resize(3); for(size_t i = 0; i != chi4_depend_chi123.size(); i++) { chi4_depend_chi123[i].resize(3); for(size_t j = 0; j != chi4_depend_chi123[i].size(); j++) { chi4_depend_chi123[i][j].resize(3); } } std::vector<Dunbrack_data> complete_independent(data.begin(), data.end()); all_independent.push_back(get_chi1_all(complete_independent)); all_independent.push_back(get_chi2_all(complete_independent)); all_independent.push_back(get_chi3_all(complete_independent)); all_independent.push_back(get_chi4_all(complete_independent)); for(auto i = data.begin(); i != data.end();) { bbdep::Dunbrack_data search_data; search_data.Phi = i->Phi; search_data.Psi = i->Psi; auto p = std::equal_range( i, data.end(), search_data, [](const bbdep::Dunbrack_data &lhs, const bbdep::Dunbrack_data &rhs) -> bool { return lhs.Phi < rhs.Phi; }); auto q = std::equal_range(p.first, p.second, search_data, [](const bbdep::Dunbrack_data &lhs, const bbdep::Dunbrack_data &rhs) -> bool { return lhs.Psi < rhs.Psi; }); std::vector<bbdep::Dunbrack_data> temp(q.first, q.second); all_chi1_index.push_back(std::make_pair(search_data.Phi, search_data.Psi)); std::vector<bbutils::distribution_1d> temp2; temp2.push_back(get_chi1_all(temp)); temp2.push_back(get_chi2_all(temp)); temp2.push_back(get_chi3_all(temp)); temp2.push_back(get_chi4_all(temp)); all_chi1234_value.push_back(temp2); for(size_t j = 1; j != 4; j++) { std::vector<bbdep::Dunbrack_data> temp3(q.first, q.second); temp3.erase( std::remove_if(temp3.begin(), temp3.end(), [j](bbdep::Dunbrack_data n) { return n.r1 != j; }), temp3.end()); if(temp3.size()) { chi2_depend_chi1[j - 1].push_back(get_chi2_all(temp3)); } else { chi2_depend_chi1[j - 1].push_back(fill_uniformly()); } } for(size_t j = 1; j != 4; j++) { for(size_t k = 1; k != 4; k++) { std::vector<bbdep::Dunbrack_data> temp3(q.first, q.second); temp3.erase(std::remove_if(temp3.begin(), temp3.end(), [j, k](bbdep::Dunbrack_data n) { return (n.r1 != j || n.r2 != k); }), temp3.end()); if(temp3.size()) { chi3_depend_chi12[j - 1][k - 1].push_back(get_chi3_all(temp3)); } else { chi3_depend_chi12[j - 1][k - 1].push_back(fill_uniformly()); } } } for(size_t j = 1; j != 4; j++) { for(size_t k = 1; k != 4; k++) { for(size_t h = 1; h != 4; h++) { std::vector<bbdep::Dunbrack_data> temp3(q.first, q.second); temp3.erase( std::remove_if(temp3.begin(), temp3.end(), [j, k, h](bbdep::Dunbrack_data n) { return (n.r1 != j || n.r2 != k || n.r3 != h); }), temp3.end()); if(temp3.size()) { chi4_depend_chi123[j - 1][k - 1][h - 1].push_back(get_chi4_all(temp3)); } else { chi4_depend_chi123[j - 1][k - 1][h - 1].push_back(fill_uniformly()); } // if(j == 1 && k == 1 && h == 3 && search_data.Phi < 101.0 && search_data.Phi > 99.0 && // search_data.Psi < -179.0) //{ // for(auto a : temp3) // std::cout << std::fixed << a << std::endl; // std::cin.get(); //} } } } //states chi1 std::vector<double> temp4; for(size_t j = 1; j != 4; j++) { std::vector<bbdep::Dunbrack_data> matches; std::copy_if(q.first, q.second, std::back_inserter(matches), [&](const bbdep::Dunbrack_data &value) -> bool { if(j == value.r1) return true; else return false; }); if(!matches.size()) continue; double state = 0.0, sum = 0.0; for(auto &h : matches) { state += (h.chi1Val < 0 ? h.chi1Val + 360.0 : h.chi1Val) * h.Probabil; sum += h.Probabil; } temp4.push_back(state / sum); } chi1_states.push_back(temp4); //states chi2 std::vector<std::vector<double>> temp5; for(size_t j = 1; j != 4; j++) { std::vector<double> temp6; for(size_t k = 1; k != 4; k++) { std::vector<bbdep::Dunbrack_data> matches; std::copy_if(q.first, q.second, std::back_inserter(matches), [&](const bbdep::Dunbrack_data &value) -> bool { if(j == value.r1 && k == value.r2) return true; else return false; }); if(!matches.size()) continue; double state = 0.0, sum = 0.0; for(auto &h : matches) { state += (h.chi2Val < 0 ? h.chi2Val + 360.0 : h.chi2Val) * h.Probabil; sum += h.Probabil; } temp6.push_back(state / sum); } temp5.push_back(temp6); } chi2_states.push_back(temp5); // states chi3 std::vector<std::vector<std::vector<double>>> temp7; for(size_t j = 1; j != 4; j++) { std::vector<std::vector<double>> temp8; for(size_t k = 1; k != 4; k++) { std::vector<double> temp9; for(size_t h = 1; h != 4; h++) { std::vector<bbdep::Dunbrack_data> matches; std::copy_if(q.first, q.second, std::back_inserter(matches), [&](const bbdep::Dunbrack_data &value) -> bool { if(j == value.r1 && k == value.r2 && h == value.r3) return true; else return false; }); if(!matches.size()) { switch(temp9.size()) { case 0: temp9.push_back(60.0); break; case 1: temp9.push_back(180.0); break; case 2: temp9.push_back(300.0); break; } continue; } double state = 0.0, sum = 0.0; for(auto &h : matches) { state += (h.chi3Val < 0 ? h.chi3Val + 360.0 : h.chi3Val) * h.Probabil; sum += h.Probabil; } temp9.push_back(state / sum); } temp8.push_back(temp9); } temp7.push_back(temp8); } chi3_states.push_back(temp7); i = q.second; } } void BBDEP_Dunbrack_sm::fill_impossible_conformations(std::vector<bbdep::Dunbrack_data> &data, std::vector<std::vector<std::vector<size_t>>> &imp_conf) { std::vector<int> rot_pos = { 1, 2, 3 }; std::vector<std::vector<size_t>> pp; for(size_t i = 1, m = 1; i < 4; i++) { for(size_t j = 1; j < 4; j++) { for(size_t k = 1; k < 4; k++) { for(size_t h = 1; h < 4; h++, m++) { // std::cout << i << '\t' << j << '\t' << k << '\t' << h << "\t\t" << m << std::endl; std::vector<size_t> temp; temp.push_back(i); temp.push_back(j); temp.push_back(k); temp.push_back(h); temp.push_back(m); pp.push_back(temp); } } } } for(auto i = data.begin(); i != data.end();) { bbdep::Dunbrack_data search_data; search_data.Phi = i->Phi; search_data.Psi = i->Psi; auto p = std::equal_range( i, data.end(), search_data, [](const bbdep::Dunbrack_data &lhs, const bbdep::Dunbrack_data &rhs) -> bool { return lhs.Phi < rhs.Phi; }); auto q = std::equal_range(p.first, p.second, search_data, [](const bbdep::Dunbrack_data &lhs, const bbdep::Dunbrack_data &rhs) -> bool { return lhs.Psi < rhs.Psi; }); std::vector<std::vector<size_t>> temp; for(size_t i = 0; i != pp.size(); i++) { auto a = std::find_if(q.first, q.second, [&](const bbdep::Dunbrack_data &value) -> bool { if(pp[i][0] == value.r1 && pp[i][1] == value.r2 && pp[i][2] == value.r3 && pp[i][3] == value.r4) return true; else return false; }); if(a == q.second) { // std::cout << pp[i][0] << '\t' << pp[i][1] << '\t' << pp[i][2] << '\t' << pp[i][3] << std::endl; std::vector<size_t> rot_string; rot_string.push_back(pp[i][0]); rot_string.push_back(pp[i][1]); rot_string.push_back(pp[i][2]); rot_string.push_back(pp[i][3]); temp.push_back(rot_string); } } imp_conf.push_back(temp); // std::cout << std::endl; i = q.second; } // std::cout << imp_conf.size() << '\t' << imp_conf[0].size() << '\t' << imp_conf[0][1].size() << std::endl; } bbutils::distribution_1d BBDEP_Dunbrack_sm::get_chi1_all(std::vector<bbdep::Dunbrack_data> &data) const { std::deque<double> x, pdf; size_t step = cdf_grid_step; double es = 360; double start = -180; for(size_t i = 0; i != step; i++) { x.push_back(start + i * es / step); double m = 0; for(auto j = data.begin(); j != data.end(); ++j) m += j->Probabil * pdf_normal_dst(x.back(), j->chi1Val, j->chi1Sig); for(auto j = data.begin(); j != data.end(); ++j) m += j->Probabil * pdf_normal_dst(x.back(), j->chi1Val + 360, j->chi1Sig); for(auto j = data.begin(); j != data.end(); ++j) m += j->Probabil * pdf_normal_dst(x.back(), j->chi1Val - 360, j->chi1Sig); // m = data.begin()->Probabil * pdf_normal_dst(x.back(), data.begin()->chi1Val, data.begin()->chi1Sig); pdf.push_back(m); } if(uniform_peaks) // uniform in peaks { auto max = *std::max_element(pdf.begin(), pdf.end()); auto min = *std::min_element(pdf.begin(), pdf.end()); for(auto &i : pdf) { i = (i - min)/(max - min); if(i < 0.1) i = 0.0; else i = 1.0; } } double S = std::accumulate(pdf.begin(), pdf.end(), 0.0); for(auto &a : pdf) { a /= S; } std::deque<double> cdf(pdf.size()); std::partial_sum(pdf.begin(), pdf.end(), cdf.begin(), std::plus<double>()); cdf.push_front(0); x.push_back(180.0); bbutils::distribution_1d result; result.pdf = pdf; result.cdf = cdf; result.grid = x; return result; } bbutils::distribution_1d BBDEP_Dunbrack_sm::get_chi2_all(std::vector<bbdep::Dunbrack_data> &data) const { std::deque<double> x, pdf; size_t step = cdf_grid_step; double es = 360; double start = -180; for(size_t i = 0; i != step; i++) { x.push_back(start + i * es / step); double m = 0; for(auto j = data.begin(); j != data.end(); ++j) m += j->Probabil * pdf_normal_dst(x.back(), j->chi2Val, j->chi2Sig); for(auto j = data.begin(); j != data.end(); ++j) m += j->Probabil * pdf_normal_dst(x.back(), j->chi2Val + 360, j->chi2Sig); for(auto j = data.begin(); j != data.end(); ++j) m += j->Probabil * pdf_normal_dst(x.back(), j->chi2Val - 360, j->chi2Sig); // m = data.begin()->Probabil * pdf_normal_dst(x.back(), data.begin()->chi2Val, data.begin()->chi2Sig); pdf.push_back(m); } if(uniform_peaks) // uniform in peaks { auto max = *std::max_element(pdf.begin(), pdf.end()); auto min = *std::min_element(pdf.begin(), pdf.end()); for(auto &i : pdf) { i = (i - min)/(max - min); if(i < 0.1) i = 0.0; else i = 1.0; } } double S = std::accumulate(pdf.begin(), pdf.end(), 0.0); for(auto &a : pdf) { a /= S; } std::deque<double> cdf(pdf.size()); std::partial_sum(pdf.begin(), pdf.end(), cdf.begin(), std::plus<double>()); cdf.push_front(0); x.push_back(180.0); bbutils::distribution_1d result; result.cdf = cdf; result.grid = x; return result; } bbutils::distribution_1d BBDEP_Dunbrack_sm::get_chi3_all(std::vector<bbdep::Dunbrack_data> &data) const { std::deque<double> x, pdf; size_t step = cdf_grid_step; double es = 360; double start = -180; for(size_t i = 0; i != step; i++) { x.push_back(start + i * es / step); double m = 0; for(auto j = data.begin(); j != data.end(); ++j) m += j->Probabil * pdf_normal_dst(x.back(), j->chi3Val, j->chi3Sig); for(auto j = data.begin(); j != data.end(); ++j) m += j->Probabil * pdf_normal_dst(x.back(), j->chi3Val + 360, j->chi3Sig); for(auto j = data.begin(); j != data.end(); ++j) m += j->Probabil * pdf_normal_dst(x.back(), j->chi3Val - 360, j->chi3Sig); // m = data.begin()->Probabil * pdf_normal_dst(x.back(), data.begin()->chi3Val, data.begin()->chi3Sig); pdf.push_back(m); } if(uniform_peaks) // uniform in peaks { auto max = *std::max_element(pdf.begin(), pdf.end()); auto min = *std::min_element(pdf.begin(), pdf.end()); for(auto &i : pdf) { i = (i - min)/(max - min); if(i < 0.1) i = 0.0; else i = 1.0; } } double S = std::accumulate(pdf.begin(), pdf.end(), 0.0); for(auto &a : pdf) { a /= S; } std::deque<double> cdf(pdf.size()); std::partial_sum(pdf.begin(), pdf.end(), cdf.begin(), std::plus<double>()); cdf.push_front(0); x.push_back(180.0); bbutils::distribution_1d result; result.cdf = cdf; result.grid = x; return result; } bbutils::distribution_1d BBDEP_Dunbrack_sm::get_chi4_all(std::vector<bbdep::Dunbrack_data> &data) const { std::deque<double> x, pdf; size_t step = cdf_grid_step; double es = 360; double start = -180; for(size_t i = 0; i != step; i++) { x.push_back(start + i * es / step); double m = 0; for(auto j = data.begin(); j != data.end(); ++j) m += j->Probabil * pdf_normal_dst(x.back(), j->chi4Val, j->chi4Sig); for(auto j = data.begin(); j != data.end(); ++j) m += j->Probabil * pdf_normal_dst(x.back(), j->chi4Val + 360, j->chi4Sig); for(auto j = data.begin(); j != data.end(); ++j) m += j->Probabil * pdf_normal_dst(x.back(), j->chi4Val - 360, j->chi4Sig); // m = data.begin()->Probabil * pdf_normal_dst(x.back(), data.begin()->chi4Val, data.begin()->chi4Sig); pdf.push_back(m); } if(uniform_peaks) // uniform in peaks { auto max = *std::max_element(pdf.begin(), pdf.end()); auto min = *std::min_element(pdf.begin(), pdf.end()); for(auto &i : pdf) { i = (i - min)/(max - min); if(i < 0.1) i = 0.0; else i = 1.0; } } double S = std::accumulate(pdf.begin(), pdf.end(), 0.0); for(auto &a : pdf) { a /= S; } std::deque<double> cdf(pdf.size()); std::partial_sum(pdf.begin(), pdf.end(), cdf.begin(), std::plus<double>()); cdf.push_front(0); x.push_back(180.0); bbutils::distribution_1d result; result.cdf = cdf; result.grid = x; return result; } bbutils::distribution_1d BBDEP_Dunbrack_sm::fill_uniformly() const { std::deque<double> x, pdf; size_t step = cdf_grid_step; double es = 360; double start = -180; for(size_t i = 0; i != step; i++) { x.push_back(start + i * es / step); double m = 1.0; // double m = 1.0 * pdf_normal_dst(x.back(), 0.0, 0.000000001); pdf.push_back(m); } double S = std::accumulate(pdf.begin(), pdf.end(), 0.0); for(auto &a : pdf) { a /= S; } std::deque<double> cdf(pdf.size()); std::partial_sum(pdf.begin(), pdf.end(), cdf.begin(), std::plus<double>()); cdf.push_front(0); x.push_back(180.0); bbutils::distribution_1d result; result.cdf = cdf; result.grid = x; return result; } bool BBDEP_Dunbrack_sm::is_impossible_conformation(std::vector<size_t> conf, double Phi, double Psi, std::vector<std::pair<double, double>> &lys_grid, std::vector<std::vector<std::vector<size_t>>> &imp_conf) { size_t i = get_index_from_phi_psi(lys_grid, Phi, Psi); auto a = std::find_if(imp_conf[i].begin(), imp_conf[i].end(), [&](const std::vector<size_t> &value) -> bool { if(conf[0] == value[0] && conf[1] == value[1] && conf[2] == value[2] && conf[3] == value[3]) return true; else return false; return true; }); return (a == imp_conf[i].end()) ? false : true; } Dunbrack_data BBDEP_Dunbrack_sm::get_max(core::chemical::AA amino_acid, double Phi, double Psi) { Dunbrack_data result; switch(amino_acid) { // 0 ser, 1 val, 2 cys, 3 thr case core::chemical::aa_ser: result = get_max_prob_object(aa_sm_1d[0].lib, aa_sm_1d[0].libn, Phi, Psi); break; case core::chemical::aa_val: result = get_max_prob_object(aa_sm_1d[1].lib, aa_sm_1d[1].libn, Phi, Psi); break; case core::chemical::aa_cys: result = get_max_prob_object(aa_sm_1d[2].lib, aa_sm_1d[2].libn, Phi, Psi); break; case core::chemical::aa_thr: result = get_max_prob_object(aa_sm_1d[3].lib, aa_sm_1d[3].libn, Phi, Psi); break; // 0 trp, 1 his, 2 asn, 3 asp, 4 phe, 5 tyr, 6 ile, 7 leu case core::chemical::aa_trp: result = get_max_prob_object(aa_sm_2d[0].lib, aa_sm_2d[0].libn, Phi, Psi); break; case core::chemical::aa_his: result = get_max_prob_object(aa_sm_2d[1].lib, aa_sm_2d[1].libn, Phi, Psi); break; case core::chemical::aa_asn: result = get_max_prob_object(aa_sm_2d[2].lib, aa_sm_2d[2].libn, Phi, Psi); break; case core::chemical::aa_asp: result = get_max_prob_object(aa_sm_2d[3].lib, aa_sm_2d[3].libn, Phi, Psi); break; case core::chemical::aa_phe: result = get_max_prob_object(aa_sm_2d[4].lib, aa_sm_2d[4].libn, Phi, Psi); break; case core::chemical::aa_tyr: result = get_max_prob_object(aa_sm_2d[5].lib, aa_sm_2d[5].libn, Phi, Psi); break; case core::chemical::aa_ile: result = get_max_prob_object(aa_sm_2d[6].lib, aa_sm_2d[6].libn, Phi, Psi); break; case core::chemical::aa_leu: result = get_max_prob_object(aa_sm_2d[7].lib, aa_sm_2d[7].libn, Phi, Psi); break; // 0 met, 1 glu, 2 gln, 3 pro case core::chemical::aa_met: result = get_max_prob_object(aa_sm_3d[0].lib, aa_sm_3d[0].libn, Phi, Psi); break; case core::chemical::aa_glu: result = get_max_prob_object(aa_sm_3d[1].lib, aa_sm_3d[1].libn, Phi, Psi); break; case core::chemical::aa_gln: result = get_max_prob_object(aa_sm_3d[2].lib, aa_sm_3d[2].libn, Phi, Psi); break; case core::chemical::aa_pro: result = get_max_prob_object(aa_sm_3d[3].lib, aa_sm_3d[3].libn, Phi, Psi); break; // 0 arg, 1 lys case core::chemical::aa_arg: result = get_max_prob_object(aa_sm_4d[0].lib, aa_sm_4d[0].libn, Phi, Psi); break; case core::chemical::aa_lys: result = get_max_prob_object(aa_sm_4d[1].lib, aa_sm_4d[1].libn, Phi, Psi); break; default: break; } return result; } size_t BBDEP_Dunbrack_sm::get_index_from_phi_psi(const std::vector<std::pair<double, double>> &data, double Phi, double Psi) const { std::pair<double, double> search_data; search_data.first = 10 * std::round(Phi / 10.0); search_data.second = 10 * std::round(Psi / 10.0); auto p = std::equal_range(data.begin(), data.end(), search_data, [](const std::pair<double, double> &lhs, const std::pair<double, double> &rhs) -> bool { return lhs.first < rhs.first; }); auto q = std::equal_range(p.first, p.second, search_data, [](const std::pair<double, double> &lhs, const std::pair<double, double> &rhs) -> bool { return lhs.second < rhs.second; }); return std::distance(data.begin(), q.first); } size_t BBDEP_Dunbrack_sm::determine_rotamer_state_0_2pi(double degree) const { std::vector<double> rotameric_states = { 60, 180, 300 }; auto i = std::min_element(rotameric_states.begin(), rotameric_states.end(), [=](double x, double y) { return std::abs(x - degree) < std::abs(y - degree); }); return std::distance(rotameric_states.begin(), i); } size_t BBDEP_Dunbrack_sm::determine_proline_rotamer_state_0_2pi(double degree) const { std::vector<double> rotameric_states = { 27.3, 334.9 }; auto i = std::min_element(rotameric_states.begin(), rotameric_states.end(), [=](double x, double y) { return std::abs(x - degree) < std::abs(y - degree); }); return std::distance(rotameric_states.begin(), i); } size_t BBDEP_Dunbrack_sm::determine_rotamer_state_0_2pi_actual_chi1(size_t index, double degree, core::chemical::AA amino_acid) const { std::vector<double> rotameric_states; switch(amino_acid) { // 0 ser, 1 val, 2 cys, 3 thr case core::chemical::aa_ser: rotameric_states = aa_sm_1d[0].lib_states[index]; break; case core::chemical::aa_val: rotameric_states = aa_sm_1d[1].lib_states[index]; break; case core::chemical::aa_cys: rotameric_states = aa_sm_1d[2].lib_states[index]; break; case core::chemical::aa_thr: rotameric_states = aa_sm_1d[3].lib_states[index]; break; // 0 trp, 1 his, 2 asn, 3 asp, 4 phe, 5 tyr, 6 ile, 7 leu case core::chemical::aa_trp: rotameric_states = aa_sm_2d[0].lib_states_chi1[index]; break; case core::chemical::aa_his: rotameric_states = aa_sm_2d[1].lib_states_chi1[index]; break; case core::chemical::aa_asn: rotameric_states = aa_sm_2d[2].lib_states_chi1[index]; break; case core::chemical::aa_asp: rotameric_states = aa_sm_2d[3].lib_states_chi1[index]; break; case core::chemical::aa_phe: rotameric_states = aa_sm_2d[4].lib_states_chi1[index]; break; case core::chemical::aa_tyr: rotameric_states = aa_sm_2d[5].lib_states_chi1[index]; break; case core::chemical::aa_ile: rotameric_states = aa_sm_2d[6].lib_states_chi1[index]; break; case core::chemical::aa_leu: rotameric_states = aa_sm_2d[7].lib_states_chi1[index]; break; // 0 met, 1 glu, 2 gln, 3 pro case core::chemical::aa_met: rotameric_states = aa_sm_3d[0].lib_states_chi1[index]; break; case core::chemical::aa_glu: rotameric_states = aa_sm_3d[1].lib_states_chi1[index]; break; case core::chemical::aa_gln: rotameric_states = aa_sm_3d[2].lib_states_chi1[index]; break; case core::chemical::aa_pro: rotameric_states = aa_sm_3d[3].lib_states_chi1[index]; break; // 0 arg, 1 lys case core::chemical::aa_arg: rotameric_states = aa_sm_4d[0].lib_states_chi1[index]; break; case core::chemical::aa_lys: rotameric_states = aa_sm_4d[1].lib_states_chi1[index]; break; default: break; } auto i = std::min_element(rotameric_states.begin(), rotameric_states.end(), [=](double x, double y) { return std::abs(x - degree) < std::abs(y - degree); }); return std::distance(rotameric_states.begin(), i); } size_t BBDEP_Dunbrack_sm::determine_rotamer_state_0_2pi_actual_chi2(size_t index, size_t chi1_state, double degree, core::chemical::AA amino_acid) const { std::vector<double> rotameric_states; switch(amino_acid) { // 0 met, 1 glu, 2 gln, 3 pro case core::chemical::aa_met: rotameric_states = aa_sm_3d[0].lib_states_chi2[index][chi1_state]; break; case core::chemical::aa_glu: rotameric_states = aa_sm_3d[1].lib_states_chi2[index][chi1_state]; break; case core::chemical::aa_gln: rotameric_states = aa_sm_3d[2].lib_states_chi2[index][chi1_state]; break; case core::chemical::aa_pro: rotameric_states = aa_sm_3d[3].lib_states_chi2[index][chi1_state]; break; // 0 arg, 1 lys case core::chemical::aa_arg: rotameric_states = aa_sm_4d[0].lib_states_chi2[index][chi1_state]; break; case core::chemical::aa_lys: rotameric_states = aa_sm_4d[1].lib_states_chi2[index][chi1_state]; break; default: break; } auto i = std::min_element(rotameric_states.begin(), rotameric_states.end(), [=](double x, double y) { return std::abs(x - degree) < std::abs(y - degree); }); return std::distance(rotameric_states.begin(), i); } size_t BBDEP_Dunbrack_sm::determine_rotamer_state_0_2pi_actual_chi3(size_t index, size_t chi1_state, size_t chi2_state, double degree, core::chemical::AA amino_acid) const { std::vector<double> rotameric_states; switch(amino_acid) { // 0 arg, 1 lys case core::chemical::aa_arg: rotameric_states = aa_sm_4d[0].lib_states_chi3[index][chi1_state][chi2_state]; break; case core::chemical::aa_lys: rotameric_states = aa_sm_4d[1].lib_states_chi3[index][chi1_state][chi2_state]; break; default: break; } auto i = std::min_element(rotameric_states.begin(), rotameric_states.end(), [=](double x, double y) { return std::abs(x - degree) < std::abs(y - degree); }); return std::distance(rotameric_states.begin(), i); } size_t BBDEP_Dunbrack_sm::find_index_for_cdf_chi234(core::chemical::AA amino_acid, double Phi, double Psi) const { size_t index = 0; switch(amino_acid) { // 0 ser, 1 val, 2 cys, 3 thr case core::chemical::aa_ser: index = get_index_from_phi_psi(aa_sm_1d[0].lib_grid, Phi, Psi); break; case core::chemical::aa_val: index = get_index_from_phi_psi(aa_sm_1d[1].lib_grid, Phi, Psi); break; case core::chemical::aa_cys: index = get_index_from_phi_psi(aa_sm_1d[2].lib_grid, Phi, Psi); break; case core::chemical::aa_thr: index = get_index_from_phi_psi(aa_sm_1d[3].lib_grid, Phi, Psi); break; // 0 trp, 1 his, 2 asn, 3 asp, 4 phe, 5 tyr, 6 ile, 7 leu case core::chemical::aa_trp: index = get_index_from_phi_psi(aa_sm_2d[0].lib_grid, Phi, Psi); break; case core::chemical::aa_his: index = get_index_from_phi_psi(aa_sm_2d[1].lib_grid, Phi, Psi); break; case core::chemical::aa_asn: index = get_index_from_phi_psi(aa_sm_2d[2].lib_grid, Phi, Psi); break; case core::chemical::aa_asp: index = get_index_from_phi_psi(aa_sm_2d[3].lib_grid, Phi, Psi); break; case core::chemical::aa_phe: index = get_index_from_phi_psi(aa_sm_2d[4].lib_grid, Phi, Psi); break; case core::chemical::aa_tyr: index = get_index_from_phi_psi(aa_sm_2d[5].lib_grid, Phi, Psi); break; case core::chemical::aa_ile: index = get_index_from_phi_psi(aa_sm_2d[6].lib_grid, Phi, Psi); break; case core::chemical::aa_leu: index = get_index_from_phi_psi(aa_sm_2d[7].lib_grid, Phi, Psi); break; // 0 met, 1 glu, 2 gln, 3 pro case core::chemical::aa_met: index = get_index_from_phi_psi(aa_sm_3d[0].lib_grid, Phi, Psi); break; case core::chemical::aa_glu: index = get_index_from_phi_psi(aa_sm_3d[1].lib_grid, Phi, Psi); break; case core::chemical::aa_gln: index = get_index_from_phi_psi(aa_sm_3d[2].lib_grid, Phi, Psi); break; case core::chemical::aa_pro: index = get_index_from_phi_psi(aa_sm_3d[3].lib_grid, Phi, Psi); break; // 0 arg, 1 lys case core::chemical::aa_arg: index = get_index_from_phi_psi(aa_sm_4d[0].lib_grid, Phi, Psi); break; case core::chemical::aa_lys: index = get_index_from_phi_psi(aa_sm_4d[1].lib_grid, Phi, Psi); break; default: break; } return index; } double BBDEP_Dunbrack_sm::get_degree_bbdep_from_phi_psi_x01_chi1_dep(size_t index, core::chemical::AA amino_acid, double chi1_positive_degree, double x01) const { double result = 0; size_t state = (amino_acid == core::chemical::aa_pro) ? determine_proline_rotamer_state_0_2pi(chi1_positive_degree) : determine_rotamer_state_0_2pi(chi1_positive_degree); switch(amino_acid) { // 0 trp, 1 his, 2 asn, 3 asp, 4 phe, 5 tyr, 6 ile, 7 leu case core::chemical::aa_trp: result = bbutils::get_1d_from_dst(aa_sm_2d[0].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_his: result = bbutils::get_1d_from_dst(aa_sm_2d[1].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_asn: result = bbutils::get_1d_from_dst(aa_sm_2d[2].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_asp: result = bbutils::get_1d_from_dst(aa_sm_2d[3].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_phe: result = bbutils::get_1d_from_dst(aa_sm_2d[4].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_tyr: result = bbutils::get_1d_from_dst(aa_sm_2d[5].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_ile: result = bbutils::get_1d_from_dst(aa_sm_2d[6].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_leu: result = bbutils::get_1d_from_dst(aa_sm_2d[7].lib_chi2_depend_chi1[state][index], x01); break; // 0 met, 1 glu, 2 gln, 3 pro case core::chemical::aa_met: result = bbutils::get_1d_from_dst(aa_sm_3d[0].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_glu: result = bbutils::get_1d_from_dst(aa_sm_3d[1].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_gln: result = bbutils::get_1d_from_dst(aa_sm_3d[2].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_pro: result = bbutils::get_1d_from_dst(aa_sm_3d[3].lib_chi2_depend_chi1[state][index], x01); break; // 0 arg, 1 lys case core::chemical::aa_arg: result = bbutils::get_1d_from_dst(aa_sm_4d[0].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_lys: result = bbutils::get_1d_from_dst(aa_sm_4d[1].lib_chi2_depend_chi1[state][index], x01); break; default: break; } return result; } double BBDEP_Dunbrack_sm::get_degree_bbdep_from_phi_psi_x01_chi12_dep(size_t index, core::chemical::AA amino_acid, double chi1_positive_degree, double chi2_positive_degree, double x01) const { double result = 0; size_t state1 = (amino_acid == core::chemical::aa_pro) ? determine_proline_rotamer_state_0_2pi(chi1_positive_degree) : determine_rotamer_state_0_2pi(chi1_positive_degree); size_t state2 = (amino_acid == core::chemical::aa_pro) ? 0 : determine_rotamer_state_0_2pi(chi2_positive_degree); switch(amino_acid) { case core::chemical::aa_met: result = bbutils::get_1d_from_dst(aa_sm_3d[0].lib_chi3_depend_chi12[state1][state2][index], x01); break; case core::chemical::aa_glu: result = bbutils::get_1d_from_dst(aa_sm_3d[1].lib_chi3_depend_chi12[state1][state2][index], x01); break; case core::chemical::aa_gln: result = bbutils::get_1d_from_dst(aa_sm_3d[2].lib_chi3_depend_chi12[state1][state2][index], x01); break; case core::chemical::aa_pro: result = bbutils::get_1d_from_dst(aa_sm_3d[3].lib_chi3_depend_chi12[state1][state2][index], x01); break; case core::chemical::aa_arg: result = bbutils::get_1d_from_dst(aa_sm_4d[0].lib_chi3_depend_chi12[state1][state2][index], x01); break; case core::chemical::aa_lys: result = bbutils::get_1d_from_dst(aa_sm_4d[1].lib_chi3_depend_chi12[state1][state2][index], x01); break; default: break; } return result; } double BBDEP_Dunbrack_sm::get_degree_bbdep_from_phi_psi_x01_chi123_dep(size_t index, core::chemical::AA amino_acid, double chi1_positive_degree, double chi2_positive_degree, double chi3_positive_degree, double x01) const { double result = 0; size_t state1 = determine_rotamer_state_0_2pi(chi1_positive_degree); size_t state2 = determine_rotamer_state_0_2pi(chi2_positive_degree); size_t state3 = determine_rotamer_state_0_2pi(chi3_positive_degree); switch(amino_acid) { case core::chemical::aa_arg: result = bbutils::get_1d_from_dst(aa_sm_4d[0].lib_chi4_depend_chi123[state1][state2][state3][index], x01); break; case core::chemical::aa_lys: result = bbutils::get_1d_from_dst(aa_sm_4d[1].lib_chi4_depend_chi123[state1][state2][state3][index], x01); break; default: break; } return result; } double BBDEP_Dunbrack_sm::get_degree_bbdep_from_phi_psi_x01_chi1_dep_actual_states(size_t index, core::chemical::AA amino_acid, double chi1_positive_degree, double x01) const { double result = 0; size_t state = determine_rotamer_state_0_2pi_actual_chi1(index, chi1_positive_degree, amino_acid); switch(amino_acid) { case core::chemical::aa_trp: result = bbutils::get_1d_from_dst(aa_sm_2d[0].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_his: result = bbutils::get_1d_from_dst(aa_sm_2d[1].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_asn: result = bbutils::get_1d_from_dst(aa_sm_2d[2].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_asp: result = bbutils::get_1d_from_dst(aa_sm_2d[3].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_phe: result = bbutils::get_1d_from_dst(aa_sm_2d[4].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_tyr: result = bbutils::get_1d_from_dst(aa_sm_2d[5].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_ile: result = bbutils::get_1d_from_dst(aa_sm_2d[6].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_leu: result = bbutils::get_1d_from_dst(aa_sm_2d[7].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_met: result = bbutils::get_1d_from_dst(aa_sm_3d[0].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_glu: result = bbutils::get_1d_from_dst(aa_sm_3d[1].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_gln: result = bbutils::get_1d_from_dst(aa_sm_3d[2].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_pro: result = bbutils::get_1d_from_dst(aa_sm_3d[3].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_arg: result = bbutils::get_1d_from_dst(aa_sm_4d[0].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_lys: result = bbutils::get_1d_from_dst(aa_sm_4d[1].lib_chi2_depend_chi1[state][index], x01); break; default: break; } return result; } double BBDEP_Dunbrack_sm::get_degree_bbdep_from_phi_psi_x01_chi12_dep_actual_states(size_t index, core::chemical::AA amino_acid, double chi1_positive_degree, double chi2_positive_degree, double x01) const { double result = 0; size_t state1 = determine_rotamer_state_0_2pi_actual_chi1(index, chi1_positive_degree, amino_acid); size_t state2 = determine_rotamer_state_0_2pi_actual_chi2(index, state1, chi2_positive_degree, amino_acid); switch(amino_acid) { case core::chemical::aa_met: result = bbutils::get_1d_from_dst(aa_sm_3d[0].lib_chi3_depend_chi12[state1][state2][index], x01); break; case core::chemical::aa_glu: result = bbutils::get_1d_from_dst(aa_sm_3d[1].lib_chi3_depend_chi12[state1][state2][index], x01); break; case core::chemical::aa_gln: result = bbutils::get_1d_from_dst(aa_sm_3d[2].lib_chi3_depend_chi12[state1][state2][index], x01); break; case core::chemical::aa_pro: result = bbutils::get_1d_from_dst(aa_sm_3d[3].lib_chi3_depend_chi12[state1][state2][index], x01); break; case core::chemical::aa_arg: result = bbutils::get_1d_from_dst(aa_sm_4d[0].lib_chi3_depend_chi12[state1][state2][index], x01); break; case core::chemical::aa_lys: result = bbutils::get_1d_from_dst(aa_sm_4d[1].lib_chi3_depend_chi12[state1][state2][index], x01); break; default: break; } return result; } double BBDEP_Dunbrack_sm::get_degree_bbdep_from_phi_psi_x01_chi123_dep_actual_states(size_t index, core::chemical::AA amino_acid, double chi1_positive_degree, double chi2_positive_degree, double chi3_positive_degree, double x01) const { double result = 0; size_t state1 = determine_rotamer_state_0_2pi_actual_chi1(index, chi1_positive_degree, amino_acid); size_t state2 = determine_rotamer_state_0_2pi_actual_chi2(index, state1, chi2_positive_degree, amino_acid); size_t state3 = determine_rotamer_state_0_2pi_actual_chi3(index, state1, state2, chi3_positive_degree, amino_acid); switch(amino_acid) { case core::chemical::aa_arg: result = bbutils::get_1d_from_dst(aa_sm_4d[0].lib_chi4_depend_chi123[state1][state2][state3][index], x01); break; case core::chemical::aa_lys: result = bbutils::get_1d_from_dst(aa_sm_4d[1].lib_chi4_depend_chi123[state1][state2][state3][index], x01); break; default: break; } return result; } double BBDEP_Dunbrack_sm::get_inverse_degree_bbdep_from_phi_psi_x01_chi1_dep(size_t index, core::chemical::AA amino_acid, double chi1_positive_degree, double x01) const { double result = 0; size_t state = determine_rotamer_state_0_2pi(chi1_positive_degree); switch(amino_acid) { case core::chemical::aa_trp: result = bbutils::get_inverse_1d_from_dst(aa_sm_2d[0].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_his: result = bbutils::get_inverse_1d_from_dst(aa_sm_2d[1].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_asn: result = bbutils::get_inverse_1d_from_dst(aa_sm_2d[2].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_asp: result = bbutils::get_inverse_1d_from_dst(aa_sm_2d[3].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_phe: result = bbutils::get_inverse_1d_from_dst(aa_sm_2d[4].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_tyr: result = bbutils::get_inverse_1d_from_dst(aa_sm_2d[5].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_ile: result = bbutils::get_inverse_1d_from_dst(aa_sm_2d[6].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_leu: result = bbutils::get_inverse_1d_from_dst(aa_sm_2d[7].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_met: result = bbutils::get_inverse_1d_from_dst(aa_sm_3d[0].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_glu: result = bbutils::get_inverse_1d_from_dst(aa_sm_3d[1].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_gln: result = bbutils::get_inverse_1d_from_dst(aa_sm_3d[2].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_pro: result = bbutils::get_inverse_1d_from_dst(aa_sm_3d[3].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_arg: result = bbutils::get_inverse_1d_from_dst(aa_sm_4d[0].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_lys: result = bbutils::get_inverse_1d_from_dst(aa_sm_4d[1].lib_chi2_depend_chi1[state][index], x01); break; default: break; } return result; } double BBDEP_Dunbrack_sm::get_inverse_degree_bbdep_from_phi_psi_x01_chi12_dep(size_t index, core::chemical::AA amino_acid, double chi1_positive_degree, double chi2_positive_degree, double x01) const { double result = 0; size_t state1 = determine_rotamer_state_0_2pi(chi1_positive_degree); size_t state2 = determine_rotamer_state_0_2pi(chi2_positive_degree); switch(amino_acid) { case core::chemical::aa_met: result = bbutils::get_inverse_1d_from_dst(aa_sm_3d[0].lib_chi3_depend_chi12[state1][state2][index], x01); break; case core::chemical::aa_glu: result = bbutils::get_inverse_1d_from_dst(aa_sm_3d[1].lib_chi3_depend_chi12[state1][state2][index], x01); break; case core::chemical::aa_gln: result = bbutils::get_inverse_1d_from_dst(aa_sm_3d[2].lib_chi3_depend_chi12[state1][state2][index], x01); break; case core::chemical::aa_pro: result = bbutils::get_inverse_1d_from_dst(aa_sm_3d[3].lib_chi3_depend_chi12[state1][state2][index], x01); break; case core::chemical::aa_arg: result = bbutils::get_inverse_1d_from_dst(aa_sm_4d[0].lib_chi3_depend_chi12[state1][state2][index], x01); break; case core::chemical::aa_lys: result = bbutils::get_inverse_1d_from_dst(aa_sm_4d[1].lib_chi3_depend_chi12[state1][state2][index], x01); break; default: break; } return result; } double BBDEP_Dunbrack_sm::get_inverse_degree_bbdep_from_phi_psi_x01_chi123_dep(size_t index, core::chemical::AA amino_acid, double chi1_positive_degree, double chi2_positive_degree, double chi3_positive_degree, double x01) const { double result = 0; size_t state1 = determine_rotamer_state_0_2pi(chi1_positive_degree); size_t state2 = determine_rotamer_state_0_2pi(chi2_positive_degree); size_t state3 = determine_rotamer_state_0_2pi(chi3_positive_degree); switch(amino_acid) { case core::chemical::aa_arg: result = bbutils::get_inverse_1d_from_dst(aa_sm_4d[0].lib_chi4_depend_chi123[state1][state2][state3][index], x01); break; case core::chemical::aa_lys: result = bbutils::get_inverse_1d_from_dst(aa_sm_4d[1].lib_chi4_depend_chi123[state1][state2][state3][index], x01); break; default: break; } return result; } double BBDEP_Dunbrack_sm::get_inverse_degree_bbdep_from_phi_psi_x01_chi1_dep_actual_states(size_t index, core::chemical::AA amino_acid, double chi1_positive_degree, double x01) const { double result = 0; size_t state = determine_rotamer_state_0_2pi(chi1_positive_degree); switch(amino_acid) { case core::chemical::aa_trp: result = bbutils::get_inverse_1d_from_dst(aa_sm_2d[0].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_his: result = bbutils::get_inverse_1d_from_dst(aa_sm_2d[1].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_asn: result = bbutils::get_inverse_1d_from_dst(aa_sm_2d[2].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_asp: result = bbutils::get_inverse_1d_from_dst(aa_sm_2d[3].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_phe: result = bbutils::get_inverse_1d_from_dst(aa_sm_2d[4].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_tyr: result = bbutils::get_inverse_1d_from_dst(aa_sm_2d[5].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_ile: result = bbutils::get_inverse_1d_from_dst(aa_sm_2d[6].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_leu: result = bbutils::get_inverse_1d_from_dst(aa_sm_2d[7].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_met: result = bbutils::get_inverse_1d_from_dst(aa_sm_3d[0].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_glu: result = bbutils::get_inverse_1d_from_dst(aa_sm_3d[1].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_gln: result = bbutils::get_inverse_1d_from_dst(aa_sm_3d[2].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_pro: result = bbutils::get_inverse_1d_from_dst(aa_sm_3d[3].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_arg: result = bbutils::get_inverse_1d_from_dst(aa_sm_4d[0].lib_chi2_depend_chi1[state][index], x01); break; case core::chemical::aa_lys: result = bbutils::get_inverse_1d_from_dst(aa_sm_4d[1].lib_chi2_depend_chi1[state][index], x01); break; default: break; } return result; } double BBDEP_Dunbrack_sm::get_inverse_degree_bbdep_from_phi_psi_x01_chi12_dep_actual_states(size_t index, core::chemical::AA amino_acid, double chi1_positive_degree, double chi2_positive_degree, double x01) const { double result = 0; size_t state1 = determine_rotamer_state_0_2pi(chi1_positive_degree); size_t state2 = determine_rotamer_state_0_2pi(chi2_positive_degree); switch(amino_acid) { case core::chemical::aa_met: result = bbutils::get_inverse_1d_from_dst(aa_sm_3d[0].lib_chi3_depend_chi12[state1][state2][index], x01); break; case core::chemical::aa_glu: result = bbutils::get_inverse_1d_from_dst(aa_sm_3d[1].lib_chi3_depend_chi12[state1][state2][index], x01); break; case core::chemical::aa_gln: result = bbutils::get_inverse_1d_from_dst(aa_sm_3d[2].lib_chi3_depend_chi12[state1][state2][index], x01); break; case core::chemical::aa_pro: result = bbutils::get_inverse_1d_from_dst(aa_sm_3d[3].lib_chi3_depend_chi12[state1][state2][index], x01); break; case core::chemical::aa_arg: result = bbutils::get_inverse_1d_from_dst(aa_sm_4d[0].lib_chi3_depend_chi12[state1][state2][index], x01); break; case core::chemical::aa_lys: result = bbutils::get_inverse_1d_from_dst(aa_sm_4d[1].lib_chi3_depend_chi12[state1][state2][index], x01); break; default: break; } return result; } double BBDEP_Dunbrack_sm::get_inverse_degree_bbdep_from_phi_psi_x01_chi123_dep_actual_states(size_t index, core::chemical::AA amino_acid, double chi1_positive_degree, double chi2_positive_degree, double chi3_positive_degree, double x01) const { double result = 0; size_t state1 = determine_rotamer_state_0_2pi(chi1_positive_degree); size_t state2 = determine_rotamer_state_0_2pi(chi2_positive_degree); size_t state3 = determine_rotamer_state_0_2pi(chi3_positive_degree); switch(amino_acid) { case core::chemical::aa_arg: result = bbutils::get_inverse_1d_from_dst(aa_sm_4d[0].lib_chi4_depend_chi123[state1][state2][state3][index], x01); break; case core::chemical::aa_lys: result = bbutils::get_inverse_1d_from_dst(aa_sm_4d[1].lib_chi4_depend_chi123[state1][state2][state3][index], x01); break; default: break; } return result; } bbdep::Dunbrack_data BBDEP_Dunbrack_sm::get_first_line(core::chemical::AA amino_acid) const { pepsgo::bbdep::Dunbrack_data result; switch(amino_acid) { case core::chemical::aa_ser: result = aa_sm_1d.front().lib.front(); break; case core::chemical::aa_val: result = aa_sm_1d[1].lib.front(); break; case core::chemical::aa_cys: result = aa_sm_1d[2].lib.front(); break; case core::chemical::aa_thr: result = aa_sm_1d.back().lib.front(); break; case core::chemical::aa_trp: result = aa_sm_2d.front().lib.front(); break; case core::chemical::aa_his: result = aa_sm_2d[1].lib.front(); break; case core::chemical::aa_asn: result = aa_sm_2d[2].lib.front(); break; case core::chemical::aa_asp: result = aa_sm_2d[3].lib.front(); break; case core::chemical::aa_phe: result = aa_sm_2d[4].lib.front(); break; case core::chemical::aa_tyr: result = aa_sm_2d[5].lib.front(); break; case core::chemical::aa_ile: result = aa_sm_2d[6].lib.front(); break; case core::chemical::aa_leu: result = aa_sm_2d.back().lib.front(); break; case core::chemical::aa_met: result = aa_sm_3d.front().lib.front(); break; case core::chemical::aa_glu: result = aa_sm_3d[1].lib.front(); break; case core::chemical::aa_gln: result = aa_sm_3d[2].lib.front(); break; case core::chemical::aa_pro: result = aa_sm_3d.back().lib.front(); break; case core::chemical::aa_arg: result = aa_sm_4d.front().lib.front(); break; case core::chemical::aa_lys: result = aa_sm_4d.back().lib.front(); break; default: break; } return result; } double BBDEP_Dunbrack_sm::get_degree_bbind(core::chemical::AA amino_acid, double x01, size_t chinumber) const { double result = 0; switch(amino_acid) { case core::chemical::aa_ser: result = bbutils::get_1d_from_dst(aa_sm_1d.front().lib_independent[chinumber], x01); break; case core::chemical::aa_val: result = bbutils::get_1d_from_dst(aa_sm_1d[1].lib_independent[chinumber], x01); break; case core::chemical::aa_cys: result = bbutils::get_1d_from_dst(aa_sm_1d[2].lib_independent[chinumber], x01); break; case core::chemical::aa_thr: result = bbutils::get_1d_from_dst(aa_sm_1d.back().lib_independent[chinumber], x01); break; case core::chemical::aa_trp: result = bbutils::get_1d_from_dst(aa_sm_2d.front().lib_independent[chinumber], x01); break; case core::chemical::aa_his: result = bbutils::get_1d_from_dst(aa_sm_2d[1].lib_independent[chinumber], x01); break; case core::chemical::aa_asn: result = bbutils::get_1d_from_dst(aa_sm_2d[2].lib_independent[chinumber], x01); break; case core::chemical::aa_asp: result = bbutils::get_1d_from_dst(aa_sm_2d[3].lib_independent[chinumber], x01); break; case core::chemical::aa_phe: result = bbutils::get_1d_from_dst(aa_sm_2d[4].lib_independent[chinumber], x01); break; case core::chemical::aa_tyr: result = bbutils::get_1d_from_dst(aa_sm_2d[5].lib_independent[chinumber], x01); break; case core::chemical::aa_ile: result = bbutils::get_1d_from_dst(aa_sm_2d[6].lib_independent[chinumber], x01); break; case core::chemical::aa_leu: result = bbutils::get_1d_from_dst(aa_sm_2d.back().lib_independent[chinumber], x01); break; case core::chemical::aa_met: result = bbutils::get_1d_from_dst(aa_sm_3d.front().lib_independent[chinumber], x01); break; case core::chemical::aa_glu: result = bbutils::get_1d_from_dst(aa_sm_3d[1].lib_independent[chinumber], x01); break; case core::chemical::aa_gln: result = bbutils::get_1d_from_dst(aa_sm_3d[2].lib_independent[chinumber], x01); break; case core::chemical::aa_pro: result = bbutils::get_1d_from_dst(aa_sm_3d.back().lib_independent[chinumber], x01); break; case core::chemical::aa_arg: result = bbutils::get_1d_from_dst(aa_sm_4d.front().lib_independent[chinumber], x01); break; case core::chemical::aa_lys: result = bbutils::get_1d_from_dst(aa_sm_4d.back().lib_independent[chinumber], x01); break; default: break; } return result; } // std::vector<sm_1d> aa_sm_1d; // 0 ser, 1 val, 2 cys, 3 thr // std::vector<sm_2d> aa_sm_2d; // 0 trp, 1 his, 2 asn, 3 asp, 4 phe, 5 tyr, 6 ile, 7 leu // std::vector<sm_3d> aa_sm_3d; // 0 met, 1 glu, 2 gln, 3 pro // std::vector<sm_4d> aa_sm_4d; // 0 arg, 1 lys double BBDEP_Dunbrack_sm::get_degree_bbdep_from_phi_psi_x01_chinumber(size_t index, core::chemical::AA amino_acid, double x01, size_t chinumber) const { double result = 0; switch(amino_acid) { case core::chemical::aa_ser: result = bbutils::get_1d_from_dst(aa_sm_1d.front().lib_cdf_sum_all[index][chinumber], x01); break; case core::chemical::aa_val: result = bbutils::get_1d_from_dst(aa_sm_1d[1].lib_cdf_sum_all[index][chinumber], x01); break; case core::chemical::aa_cys: result = bbutils::get_1d_from_dst(aa_sm_1d[2].lib_cdf_sum_all[index][chinumber], x01); break; case core::chemical::aa_thr: result = bbutils::get_1d_from_dst(aa_sm_1d.back().lib_cdf_sum_all[index][chinumber], x01); break; case core::chemical::aa_trp: result = bbutils::get_1d_from_dst(aa_sm_2d.front().lib_cdf_sum_all[index][chinumber], x01); break; case core::chemical::aa_his: result = bbutils::get_1d_from_dst(aa_sm_2d[1].lib_cdf_sum_all[index][chinumber], x01); break; case core::chemical::aa_asn: result = bbutils::get_1d_from_dst(aa_sm_2d[2].lib_cdf_sum_all[index][chinumber], x01); break; case core::chemical::aa_asp: result = bbutils::get_1d_from_dst(aa_sm_2d[3].lib_cdf_sum_all[index][chinumber], x01); break; case core::chemical::aa_phe: result = bbutils::get_1d_from_dst(aa_sm_2d[4].lib_cdf_sum_all[index][chinumber], x01); break; case core::chemical::aa_tyr: result = bbutils::get_1d_from_dst(aa_sm_2d[5].lib_cdf_sum_all[index][chinumber], x01); break; case core::chemical::aa_ile: result = bbutils::get_1d_from_dst(aa_sm_2d[6].lib_cdf_sum_all[index][chinumber], x01); break; case core::chemical::aa_leu: result = bbutils::get_1d_from_dst(aa_sm_2d.back().lib_cdf_sum_all[index][chinumber], x01); break; case core::chemical::aa_met: result = bbutils::get_1d_from_dst(aa_sm_3d.front().lib_cdf_sum_all[index][chinumber], x01); break; case core::chemical::aa_glu: result = bbutils::get_1d_from_dst(aa_sm_3d[1].lib_cdf_sum_all[index][chinumber], x01); break; case core::chemical::aa_gln: result = bbutils::get_1d_from_dst(aa_sm_3d[2].lib_cdf_sum_all[index][chinumber], x01); break; case core::chemical::aa_pro: result = bbutils::get_1d_from_dst(aa_sm_3d.back().lib_cdf_sum_all[index][chinumber], x01); break; case core::chemical::aa_arg: result = bbutils::get_1d_from_dst(aa_sm_4d.front().lib_cdf_sum_all[index][chinumber], x01); break; case core::chemical::aa_lys: result = bbutils::get_1d_from_dst(aa_sm_4d.back().lib_cdf_sum_all[index][chinumber], x01); break; default: break; } return result; } } }
34.804837
174
0.63859
poluyan
4fd75de455ab7f708bc3978e215ddd1c9716a9d3
2,884
cpp
C++
source/example.cpp
M-Unterreiner/aufgabenblatt-3
05c032c4768346ee22b1fe4efe3f59a4577ea243
[ "MIT" ]
null
null
null
source/example.cpp
M-Unterreiner/aufgabenblatt-3
05c032c4768346ee22b1fe4efe3f59a4577ea243
[ "MIT" ]
null
null
null
source/example.cpp
M-Unterreiner/aufgabenblatt-3
05c032c4768346ee22b1fe4efe3f59a4577ea243
[ "MIT" ]
null
null
null
#include "window.hpp" #include <GLFW/glfw3.h> #include <utility> #include <cmath> #include "circle.hpp" #include "rectangle.hpp" #include "color.hpp" int main(int argc, char* argv[]) { Window win{std::make_pair(800,800)}; while (!win.should_close()) { if (win.get_key(GLFW_KEY_ESCAPE) == GLFW_PRESS) { win.close(); } // Hier kommt mein Code rein Vec2 v1 = {100.0f, 300.0f}; Vec2 v2 = {500.0f, 500.0f}; Vec2 v3 = {400.0f, 400.0f}; Vec2 v4 = {600.0f, 600.0f}; Color c1 = {0.2f, 0.1f, 0.9f}; Color c2 = {0.4f, 0.2f, 0.3f}; Color c3 = {1.0f, 0.0f, 1.0f}; Color c4 = {0.8f, 0.2f, 0.3f}; Rectangle firstRectangle{v1,v2,c1}; firstRectangle.draw(win,1.0f); Circle firstCircle{10.0f, c2, v3}; firstCircle.draw(win); Circle secondCirlce{10.f, c3, v4}; secondCirlce.draw(win, 2.0f); bool left_pressed = win.get_mouse_button(GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS; auto mouse_position = win.mouse_position(); Vec2 position{mouse_position.first, mouse_position.second}; if (firstCircle.is_inside(position)){ firstCircle.draw(win, 2.0f); } if (firstRectangle.is_inside(position)){ firstRectangle.draw(win, 5.0f); } // Hier endet mein Code auto t = win.get_time(); float x1 = 400.f + 380.f * std::sin(t); float y1 = 400.f + 380.f * std::cos(t); float x2 = 400.f + 380.f * std::sin(2.0f*t); float y2 = 400.f + 380.f * std::cos(2.0f*t); float x3 = 400.f + 380.f * std::sin(t-10.f); float y3 = 400.f + 380.f * std::cos(t-10.f); win.draw_point(x1, y1, 1.0f, 0.0f, 0.0f); win.draw_point(x2, y2, 0.0f, 1.0f, 0.0f); win.draw_point(x3, y3, 0.0f, 0.0f, 1.0f); if (left_pressed) { win.draw_line(30.0f, 30.0f, // FROM pixel idx with coords (x=30, y=30) mouse_position.first, mouse_position.second, // TO mouse position in pixel coords 1.0,0.0,0.0, // color with r,g,b in [0.0, 1.0] 1.0); // line thickness = 1.0 * default thickness } win.draw_line(0, mouse_position.second, 10, mouse_position.second, 0.0, 0.0, 0.0); win.draw_line(win.window_size().second - 10, mouse_position.second, win.window_size().second, mouse_position.second, 0.0, 0.0, 0.0); win.draw_line(mouse_position.first, 0, mouse_position.first, 10, 0.0, 0.0, 0.0); win.draw_line(mouse_position.first, win.window_size().second - 10, mouse_position.first, win.window_size().second, 0.0, 0.0, 0.0); std::string display_text = "mouse position: (" + std::to_string(mouse_position.first) + ", " + std::to_string(mouse_position.second) + ")"; int text_offset_x = 10; int text_offset_y = 5; unsigned int font_size = 35; win.draw_text(text_offset_x, text_offset_y, font_size, display_text); win.update(); } return 0; }
29.731959
143
0.61165
M-Unterreiner
4fd81c87641620b00666bc3172d99b13d10fe3d7
7,237
cpp
C++
vm/capi/module.cpp
drnic/rubinius
32ee5714fbfe0d5aeae5d71cac246b41f10d15b9
[ "BSD-3-Clause" ]
1
2019-06-27T12:45:49.000Z
2019-06-27T12:45:49.000Z
vm/capi/module.cpp
drnic/rubinius
32ee5714fbfe0d5aeae5d71cac246b41f10d15b9
[ "BSD-3-Clause" ]
null
null
null
vm/capi/module.cpp
drnic/rubinius
32ee5714fbfe0d5aeae5d71cac246b41f10d15b9
[ "BSD-3-Clause" ]
null
null
null
#include "builtin/object.hpp" #include "builtin/module.hpp" #include "builtin/symbol.hpp" #include "helpers.hpp" #include "call_frame.hpp" #include "capi/capi.hpp" #include "capi/include/ruby.h" using namespace rubinius; using namespace rubinius::capi; extern "C" { int rb_const_defined(VALUE module_handle, ID const_id) { VALUE ret = rb_funcall(module_handle, rb_intern("const_defined?"), 1, ID2SYM(const_id)); // This version also checks Object. le sigh. if(!RTEST(ret)) { ret = rb_funcall(rb_cObject, rb_intern("const_defined?"), 1, ID2SYM(const_id)); } return ret; } int rb_const_defined_at(VALUE module_handle, ID const_id) { return rb_funcall(module_handle, rb_intern("const_defined?"), 1, ID2SYM(const_id)); } ID rb_frame_last_func() { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); CallFrame* rcf = env->current_call_frame()->previous->top_ruby_frame(); return env->get_handle(rcf->name()); } static VALUE const_missing(VALUE klass, ID id) { return rb_funcall(klass, rb_intern("const_missing"), 1, ID2SYM(id)); } VALUE rb_const_get_at(VALUE module_handle, ID id_name) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); Symbol* name = reinterpret_cast<Symbol*>(id_name); Module* module = c_as<Module>(env->get_object(module_handle)); bool found = false; Object* val = module->get_const(env->state(), name, &found); if(found) return env->get_handle(val); return const_missing(module_handle, id_name); } VALUE rb_const_get_from(VALUE module_handle, ID id_name) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); Symbol* name = reinterpret_cast<Symbol*>(id_name); Module* module = c_as<Module>(env->get_object(module_handle)); bool found = false; while(!module->nil_p()) { Object* val = module->get_const(env->state(), name, &found); if(found) return env->get_handle(val); module = module->superclass(); } return const_missing(module_handle, id_name); } VALUE rb_const_get(VALUE module_handle, ID id_name) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); Symbol* name = reinterpret_cast<Symbol*>(id_name); Module* module = c_as<Module>(env->get_object(module_handle)); bool found = false; while(!module->nil_p()) { Object* val = module->get_const(env->state(), name, &found); if(found) return env->get_handle(val); module = module->superclass(); } // Try from Object as well. module = env->state()->globals().object.get(); while(!module->nil_p()) { Object* val = module->get_const(env->state(), name, &found); if(found) return env->get_handle(val); module = module->superclass(); } return const_missing(module_handle, id_name); } void rb_const_set(VALUE module_handle, ID name, VALUE obj_handle) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); Module* module = c_as<Module>(env->get_object(module_handle)); Object* object = env->get_object(obj_handle); module->set_const(env->state(), reinterpret_cast<Symbol*>(name), object); } void rb_define_alias(VALUE module_handle, const char* new_name, const char* old_name) { ID id_new = rb_intern(new_name); ID id_old = rb_intern(old_name); rb_funcall(module_handle, rb_intern("alias_method"), 2, id_new, id_old); } void rb_alias(VALUE module_handle, ID id_new, ID id_old) { rb_funcall(module_handle, rb_intern("alias_method"), 2, id_new, id_old); } void rb_define_alloc_func(VALUE class_handle, CApiAllocFunction allocator) { rb_define_singleton_method(class_handle, "allocate", allocator, 0); } void rb_undef_alloc_func(VALUE class_handle) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); rb_undef_method( env->get_handle(env->get_object(class_handle)->singleton_class(env->state())), "allocate"); } void rb_define_attr(VALUE module_handle, const char* attr_name, int readable, int writable) { if(readable) { rb_funcall(module_handle, rb_intern("attr_reader"), 1, rb_intern(attr_name)); } if(writable) { rb_funcall(module_handle, rb_intern("attr_writer"), 1, rb_intern(attr_name)); } } void rb_define_const(VALUE module_handle, const char* name, VALUE obj_handle) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); Module* module = c_as<Module>(env->get_object(module_handle)); Object* object = env->get_object(obj_handle); module->set_const(env->state(), name, object); } void rb_define_global_const(const char* name, VALUE obj) { rb_define_const(rb_cObject, name, obj); } void rb_define_global_function(const char* name, CApiGenericFunction func, int argc) { rb_define_module_function(rb_mKernel, name, func, argc); } VALUE rb_define_module(const char* name) { return rb_define_module_under(rb_cObject, name); } void rb_define_module_function(VALUE module_handle, const char* name, CApiGenericFunction func, int args) { rb_define_private_method(module_handle, name, func, args); rb_define_singleton_method(module_handle, name, func, args); } /** @note Shares code with rb_define_class_under, change there too. --rue */ VALUE rb_define_module_under(VALUE parent_handle, const char* name) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); Module* parent = c_as<Module>(env->get_object(parent_handle)); Symbol* constant = env->state()->symbol(name); Module* module = rubinius::Helpers::open_module(env->state(), env->current_call_frame(), parent, constant); return env->get_handle(module); } void rb_include_module(VALUE includer_handle, VALUE includee_handle) { rb_funcall(includer_handle, rb_intern("include"), 1, includee_handle); } void rb_undef_method(VALUE module_handle, const char* name) { rb_funcall(module_handle, rb_intern("undef_method!"), 1, ID2SYM(rb_intern(name))); } void rb_undef(VALUE handle, ID name) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); Symbol* sym = reinterpret_cast<Symbol*>(name); rb_undef_method(handle, sym->c_str(env->state())); // In MRI, rb_undef also calls the undef_method hooks, maybe we should? } VALUE rb_mod_ancestors(VALUE mod) { return rb_funcall(mod, rb_intern("ancestors"), 0); } VALUE rb_mod_name(VALUE mod) { return rb_funcall(mod, rb_intern("name"), 0); } VALUE rb_module_new(void) { return rb_funcall(rb_cModule, rb_intern("new"), 0); } VALUE rb_mod_remove_const(VALUE mod, VALUE name) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); Module* module = c_as<Module>(env->get_object(mod)); module->del_const(env->state(), reinterpret_cast<Symbol*>(name)); return Qnil; } const char* rb_class2name(VALUE module_handle) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); Module* module_object = c_as<Module>(env->get_object(module_handle)); String* str = module_object->name()->to_str(env->state()); return RSTRING_PTR(env->get_handle(str)); } }
31.881057
95
0.701396
drnic
4fdaf805a54f063e9f331fc49c7ddba8a468c415
3,113
cpp
C++
src/verification_platform/dut/centroiding_cpp_module.cpp
schulz89/Verification-Platform-for-Star-Trackers
5216feb8036506503713c0c1f89728ecc40b3d5c
[ "Apache-2.0" ]
3
2020-03-06T10:32:00.000Z
2022-01-18T21:14:26.000Z
src/verification_platform/dut/centroiding_cpp_module.cpp
schulz89/Verification-Platform-for-Star-Trackers
5216feb8036506503713c0c1f89728ecc40b3d5c
[ "Apache-2.0" ]
1
2020-10-30T06:25:21.000Z
2020-10-30T06:25:21.000Z
src/verification_platform/dut/centroiding_cpp_module.cpp
schulz89/Verification-Platform-for-Star-Trackers
5216feb8036506503713c0c1f89728ecc40b3d5c
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 Victor Hugo Schulz // 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 "centroiding_cpp_module.h" using namespace std; using namespace std::chrono; using namespace cv; using namespace uvm; using namespace sc_core; using namespace std_str; using namespace st; centroiding_cpp_module::centroiding_cpp_module(uvm_component_name name, vip_if *in, vip_if *out) : uvm_component(name) { vif_in = in; vif_out = out; double dtmp; FileStorage fs("config/dut.yml", FileStorage::READ); fs["gb_threshold"] >> dtmp; cfg_threshold = (int)dtmp; fs["gb_cdpu_count"] >> dtmp; cfg_cdpu_count = (int)dtmp; fs["gb_kalman_gain"] >> cfg_kalman_gain; fs.release(); star_filter = new StarFilterSW(cfg_threshold); centroider = new Centroider(cfg_cdpu_count); } centroiding_cpp_module::~centroiding_cpp_module() { // delete star_filter; delete centroider; } void centroiding_cpp_module::build_phase(uvm_phase &phase) { // cout << sc_time_stamp() << ": build_phase " << name() << endl; uvm_component::build_phase(phase); // if (!uvm_config_db<vip_if*>::get(this, "*", "vip_if_in_1", vif_in)) // UVM_FATAL(name(), "Virtual interface not defined! Simulation aborted!"); // if (!uvm_config_db<vip_if*>::get(this, "*", "vip_if_out_1", vif_out)) // UVM_FATAL(name(), "Virtual interface not defined! Simulation aborted!"); } void centroiding_cpp_module::run_phase(uvm_phase& phase) { uvm_component::run_phase(phase); while(true){ wait(vif_in->tlm_target.ev); Sky gsky = vif_in->tlm_target.packet.sky_str; // Mat color_image; // cvtColor(gsky.image, color_image, cv::COLOR_GRAY2BGR); auto t0 = high_resolution_clock::now(); vector<StarPixel> star_pixels = star_filter->GetStarPixels(gsky.image); auto t1 = high_resolution_clock::now(); vector<Centroid> centroids = centroider->ComputeFromList(star_pixels, cfg_kalman_gain); auto t2 = high_resolution_clock::now(); duration<double> elapsed_seconds = t2-t0; duration<double> c_time = t2 - t1; // time without threshold; Sky csky; for(auto &i : centroids){ Star s; s.centroid.x = i.x; s.centroid.y = i.y; s.mag = i.value; csky.stars.push_back(s); } csky.image = gsky.image; csky.time.push_back(elapsed_seconds.count()); csky.time.push_back(c_time.count()); output_packet.sky_str = csky; vif_out->tlm_socket.write_register(0,output_packet); } }
32.768421
118
0.67459
schulz89
4fdbf34a968150bbb1b6eef1d361852385579e53
2,430
cpp
C++
src/Functions/yesterday.cpp
akvasha/ClickHouse
2e3e56f3538f4b0ac9cfb58275ce2c0ff85754f9
[ "Apache-2.0" ]
null
null
null
src/Functions/yesterday.cpp
akvasha/ClickHouse
2e3e56f3538f4b0ac9cfb58275ce2c0ff85754f9
[ "Apache-2.0" ]
null
null
null
src/Functions/yesterday.cpp
akvasha/ClickHouse
2e3e56f3538f4b0ac9cfb58275ce2c0ff85754f9
[ "Apache-2.0" ]
null
null
null
#include <common/DateLUT.h> #include <Core/Field.h> #include <DataTypes/DataTypeDate.h> #include <Functions/IFunctionOld.h> #include <Functions/FunctionFactory.h> namespace DB { class ExecutableFunctionYesterday : public IExecutableFunction { public: explicit ExecutableFunctionYesterday(time_t time_) : day_value(time_) {} String getName() const override { return "yesterday"; } ColumnPtr executeImpl(const ColumnsWithTypeAndName &, const DataTypePtr &, size_t input_rows_count) const override { return DataTypeDate().createColumnConst(input_rows_count, day_value); } private: DayNum day_value; }; class FunctionBaseYesterday : public IFunctionBase { public: explicit FunctionBaseYesterday(DayNum day_value_) : day_value(day_value_), return_type(std::make_shared<DataTypeDate>()) {} String getName() const override { return "yesterday"; } const DataTypes & getArgumentTypes() const override { static const DataTypes argument_types; return argument_types; } const DataTypePtr & getResultType() const override { return return_type; } ExecutableFunctionPtr prepare(const ColumnsWithTypeAndName &) const override { return std::make_unique<ExecutableFunctionYesterday>(day_value); } bool isDeterministic() const override { return false; } bool isDeterministicInScopeOfQuery() const override { return true; } private: DayNum day_value; DataTypePtr return_type; }; class YesterdayOverloadResolver : public IFunctionOverloadResolver { public: static constexpr auto name = "yesterday"; String getName() const override { return name; } bool isDeterministic() const override { return false; } size_t getNumberOfArguments() const override { return 0; } static FunctionOverloadResolverPtr create(ContextPtr) { return std::make_unique<YesterdayOverloadResolver>(); } DataTypePtr getReturnTypeImpl(const DataTypes &) const override { return std::make_shared<DataTypeDate>(); } FunctionBasePtr buildImpl(const ColumnsWithTypeAndName &, const DataTypePtr &) const override { auto day_num = DateLUT::instance().toDayNum(time(nullptr)) - 1; return std::make_unique<FunctionBaseYesterday>(static_cast<DayNum>(day_num)); } }; void registerFunctionYesterday(FunctionFactory & factory) { factory.registerFunction<YesterdayOverloadResolver>(); } }
27.303371
127
0.738272
akvasha
4fde84abf2e9378aa82a7eb49bf617d2ba7ee61c
33
cpp
C++
r_utils/source/r_nullable.cpp
TroyDL/revere
541bdc2bed9db212c1b74414b24733cf39675d08
[ "BSD-3-Clause" ]
3
2022-02-15T19:30:32.000Z
2022-03-11T20:00:47.000Z
r_utils/source/r_nullable.cpp
TroyDL/revere
541bdc2bed9db212c1b74414b24733cf39675d08
[ "BSD-3-Clause" ]
6
2022-02-15T19:35:29.000Z
2022-02-16T00:36:46.000Z
r_utils/source/r_nullable.cpp
TroyDL/revere
541bdc2bed9db212c1b74414b24733cf39675d08
[ "BSD-3-Clause" ]
2
2020-11-17T06:46:32.000Z
2022-02-10T21:43:36.000Z
#include "r_utils/r_nullable.h"
11
31
0.757576
TroyDL
4fe00a1a9ac699c730bea42ce51d608d97cedbcc
6,500
cpp
C++
unlabeled_mapf/src/lib_ga.cpp
Kei18/tswap
4f1fb59579c88de122d04a3760dbdda8aa82ba34
[ "MIT" ]
2
2022-02-13T23:31:31.000Z
2022-02-14T05:34:38.000Z
unlabeled_mapf/src/lib_ga.cpp
Kei18/tswap
4f1fb59579c88de122d04a3760dbdda8aa82ba34
[ "MIT" ]
null
null
null
unlabeled_mapf/src/lib_ga.cpp
Kei18/tswap
4f1fb59579c88de122d04a3760dbdda8aa82ba34
[ "MIT" ]
1
2022-03-18T00:07:47.000Z
2022-03-18T00:07:47.000Z
#include "../include/lib_ga.hpp" #include <climits> #include <cstring> #include <queue> LibGA::FieldEdge::FieldEdge(int sindex, int gindex, Node* _s, Node* _g, int _d) : start_index(sindex), goal_index(gindex), s(_s), g(_g), evaled(false), inst_d(_d), d(0) { } LibGA::FieldEdge::FieldEdge(int sindex, int gindex, Node* _s, Node* _g, int _d1, int _d2) : start_index(sindex), goal_index(gindex), s(_s), g(_g), evaled(true), inst_d(_d1), d(_d2) { } void LibGA::FieldEdge::setRealDist(int _d) { if (!evaled) { evaled = true; d = _d; } } LibGA::Matching::Matching(Problem* P) : starts(P->getConfigStart()), goals(P->getConfigGoal()), N(P->getNum()), adj(N * 2, std::vector<int>()), mate(N * 2, NIL), cost(N, std::vector<int>(N, NIL)), matched_num(0), assigned_goals(N, nullptr) { } void LibGA::Matching::addEdge(FieldEdge const* e) { int s = e->start_index; int g = N + e->goal_index; adj[s].push_back(g); adj[g].push_back(s); cost[s][g - N] = e->d; } void LibGA::Matching::resetCurrentMate() { matched_num = 0; for (int i = 0; i < N * 2; ++i) { if (i < N) assigned_goals[i] = nullptr; mate[i] = NIL; } } void LibGA::Matching::mariage(const int s, const int g) { if (mate[s] == NIL) ++matched_num; mate[s] = g; mate[g] = s; assigned_goals[s] = goals[g - N]; } int LibGA::Matching::getCost() { int sum = 0; for (int i = 0; i < N; ++i) { if (mate[i] == NIL) continue; sum += cost[i][mate[i] - N]; } return sum; } int LibGA::Matching::getMakespan() { int score = 0; for (int i = 0; i < N; ++i) { if (mate[i] == NIL) continue; score = std::max(score, cost[i][mate[i] - N]); } return score; } void LibGA::Matching::updateByIncrementalFordFulkerson(FieldEdge const* e) { addEdge(e); // close list std::vector<bool> CLOSE(N * 2, false); // DFS std::function<bool(int)> dfs = [&](int v) { // start/goal if (CLOSE[v]) return false; CLOSE[v] = true; // expand neighbors for (int u : adj[v]) { // u: goal/start int w = mate[u]; // w: start/goal // unmatched goal/start is found || found augmented path if (w == NIL || (!CLOSE[w] && dfs(w))) { if (v < N) { // start mariage(v, u); } else { // goal mariage(u, v); } return true; } } return false; }; const int s = e->start_index; const int g = N + e->goal_index; if (mate[s] == NIL) { // new path must include s dfs(s); } else if (mate[g] == NIL) { // new path must include g dfs(g); } else { // search all for (int v = 0; v < N; ++v) { if (mate[v] == NIL && dfs(v)) break; } } } void LibGA::Matching::solveBySuccessiveShortestPath() { // clear the previous results resetCurrentMate(); // setup sink node const int SINK = N * 2; // setup neighbors std::vector<int> adj_sink(N); std::iota(adj_sink.begin(), adj_sink.end(), N); adj.push_back(adj_sink); for (int v = N; v < N * 2; ++v) adj[v].push_back(SINK); std::vector<bool> f_to_sink(N, false); // potential std::vector<int> potential(N * 2 + 1, 0); struct DijkstraNode { int v; // node int d; // distance DijkstraNode* p; // parent }; using DijkstraNodes = std::vector<DijkstraNode*>; auto compare = [&](DijkstraNode* v, DijkstraNode* u) { return v->d > u->d; }; // avoid "new" operation const int MEMORY_SIZE = N * 40; DijkstraNode GC[MEMORY_SIZE]; for (int _i = 0; _i < N; ++_i) { // priority queue std::priority_queue<DijkstraNode*, DijkstraNodes, decltype(compare)> OPEN( compare); int node_total_cnt = 0; auto createNewNode = [&](int _v, int _d, DijkstraNode* _p) { if (node_total_cnt >= MEMORY_SIZE) halt("lib_ga, memory over, increase MEMORY_SIZE..."); auto q = &(GC[node_total_cnt++]); q->v = _v; q->d = _d; q->p = _p; return q; }; // close list bool CLOSE[N * 2 + 1]; std::memset(CLOSE, false, sizeof(CLOSE)); // distance from source std::vector<int> dist(N * 2 + 1, INT_MAX); // for backtracking DijkstraNode* sink_p = nullptr; // initialize for (int v = 0; v < N; ++v) { if (mate[v] != NIL) continue; dist[v] = 0; OPEN.push(createNewNode(v, 0, nullptr)); } // calculate distance while (!OPEN.empty()) { // minimum node auto n = OPEN.top(); OPEN.pop(); // check CLOSE list if (CLOSE[n->v]) continue; CLOSE[n->v] = true; // expand neighbors for (auto m : adj[n->v]) { // already searched if (CLOSE[m]) continue; // check connectivity if (n->v < N) { // start -> goal if (mate[n->v] == m) continue; } else if (n->v < N * 2 && m < N) { // goal -> start if (mate[n->v] != m) continue; } else if (n->v < N * 2 && m == SINK) { // goal -> sink if (f_to_sink[n->v - N]) continue; } else if (n->v == SINK) { // sink -> goal if (!f_to_sink[m - N]) continue; } else { halt("unknown case"); } // update distance, s -> g or g -> s int _c = (m == SINK || n->v == SINK) ? 0 : ((n->v < N) ? cost[n->v][m - N] : -cost[m][n->v - N]); int c = _c + potential[n->v] - potential[m]; int d = dist[n->v] + c; if (c < 0) halt("invalid cost: " + std::to_string(c)); if (d < dist[m]) { dist[m] = d; auto p = createNewNode(m, d, n); OPEN.push(p); // for backtracking if (p->v == SINK) sink_p = p; } } } // update potential for (int v = 0; v < N * 2 + 1; ++v) { if (!CLOSE[v]) halt("unknown place: " + std::to_string(v)); potential[v] += dist[v]; } // backtracking if (sink_p != nullptr) { auto n = sink_p; while (n->p != nullptr) { if (n->v == SINK) { // goal -> sink f_to_sink[n->p->v - N] = true; } else if (n->p->v == SINK) { // sink -> goal f_to_sink[n->v - N] = false; // meaningless } else if (n->v >= N) { // start -> goal mariage(n->p->v, n->v); } else { // goal -> start // pass } n = n->p; } } } }
23.98524
80
0.505077
Kei18
4fe04a185fabfc7bfc0413598fb8c2dbac6effdc
371
cpp
C++
cpp/cpp_primer/chapter12/ex_12_23a.cpp
KaiserLancelot/Cpp-Primer
a4791a6765f0b6c864e8881e6a5328e2a3d68974
[ "MIT" ]
2
2019-12-21T00:53:47.000Z
2020-01-01T10:36:30.000Z
cpp/cpp_primer/chapter12/ex_12_23a.cpp
KaiserLancelot/Cpp-Primer
a4791a6765f0b6c864e8881e6a5328e2a3d68974
[ "MIT" ]
null
null
null
cpp/cpp_primer/chapter12/ex_12_23a.cpp
KaiserLancelot/Cpp-Primer
a4791a6765f0b6c864e8881e6a5328e2a3d68974
[ "MIT" ]
null
null
null
// // Created by kaiser on 18-12-19. // #include <cstring> #include <iostream> #include <memory> int main() { const char* s1{"hello"}; const char* s2{"world"}; auto size{std::strlen(s1) + std::strlen(s2) + 1}; auto s{std::make_unique<char[]>(size)}; std::strcpy(s.get(), s1); std::strcpy(s.get() + std::strlen(s1), s2); std::cout << s.get() << '\n'; }
17.666667
51
0.579515
KaiserLancelot
4fe09b802e897fdfdbf1e6cc59bb7cedb05148b4
324
cpp
C++
maximum array.cpp
0ishita-jana/-dev-info-day1
e6053be728856b3a92d3137bdfd30e16700f7d06
[ "MIT" ]
null
null
null
maximum array.cpp
0ishita-jana/-dev-info-day1
e6053be728856b3a92d3137bdfd30e16700f7d06
[ "MIT" ]
null
null
null
maximum array.cpp
0ishita-jana/-dev-info-day1
e6053be728856b3a92d3137bdfd30e16700f7d06
[ "MIT" ]
null
null
null
//maximum number in array using function #include<stdio.h> #include<conio.h> int max(int a[],int); int main() { int a[]={10,5,45,12,19}; int n=5,m; m=max(a,n); printf("\n maximum number is %d",m); return 0; getch(); } max(int x[],int k) { int t,i; t=x[0]; for(i=1;i<k;i++) { if(x[i]>t) t=x[i]; } return(t); }
12
40
0.561728
0ishita-jana
4fe14ce542efba945f2390b5c6b6c4195609930e
297
hh
C++
RecoDataProducts/inc/StrawHitPosition.hh
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
1
2021-06-25T00:00:12.000Z
2021-06-25T00:00:12.000Z
RecoDataProducts/inc/StrawHitPosition.hh
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
125
2020-04-03T13:44:30.000Z
2021-10-15T21:29:57.000Z
RecoDataProducts/inc/StrawHitPosition.hh
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
2
2019-10-14T17:46:58.000Z
2020-03-30T21:05:15.000Z
#ifndef RecoDataProducts_StrawHitPosition_hh #define RecoDataProducts_StrawHitPosition_hh // deprecated class, use ComboHit instead #include "RecoDataProducts/inc/ComboHit.hh" namespace mu2e { typedef ComboHit StrawHitPosition; typedef ComboHitCollection StrawHitPositionCollection; } #endif
27
56
0.851852
bonventre
4fe2a9e6273b242ea4bb3fb4b764e6137d01f5aa
15,441
cc
C++
proxy/ControlBase.cc
ibrezac/trafficserver
640c4f738b7858f93069f987ea141e0cafae72da
[ "Apache-2.0" ]
null
null
null
proxy/ControlBase.cc
ibrezac/trafficserver
640c4f738b7858f93069f987ea141e0cafae72da
[ "Apache-2.0" ]
null
null
null
proxy/ControlBase.cc
ibrezac/trafficserver
640c4f738b7858f93069f987ea141e0cafae72da
[ "Apache-2.0" ]
null
null
null
/** @file A brief file description @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. */ /***************************************************************************** * * ControlBase.cc - Base class to process generic modifiers to * ControlMatcher Directives * * ****************************************************************************/ #include "ink_unused.h" /* MAGIC_EDITING_TAG */ #include "Main.h" #include "URL.h" #include "Tokenizer.h" #include "ControlBase.h" #include "MatcherUtils.h" #include "HTTP.h" #include "ControlMatcher.h" #include "InkTime.h" #include "ink_platform.h" #include "HdrUtils.h" // iPort added static const char *ModTypeStrings[] = { "Modifier Invalid", "Port", "Scheme", "Prefix", "Suffix", "Method", "TimeOfDay", "SrcIP", "iPort", "Tag" }; const int secondsInDay = 24 * 60 * 60; struct timeMod { time_t start_time; time_t end_time; }; struct ipMod { ip_addr_t start_addr; ip_addr_t end_addr; }; struct portMod { int start_port; int end_port; }; ControlBase::~ControlBase() { int num_el; if (mod_elements != NULL) { // Free all Prefix/Postfix strings and // SrcIP, Port, Time Of Day Structures num_el = (*mod_elements).length() + 1; for (int i = 0; i < num_el; i++) { modifier_el & cur_el = (*mod_elements)[i]; if (cur_el.type == MOD_PREFIX || cur_el.type == MOD_SUFFIX || cur_el.type == MOD_TIME || cur_el.type == MOD_PORT || cur_el.type == MOD_SRC_IP || cur_el.type == MOD_TAG) { xfree(cur_el.opaque_data); } } delete mod_elements; } } static const modifier_el default_el = { MOD_INVALID, NULL }; void ControlBase::Print() { int num_el; struct in_addr a; int port; if (mod_elements == NULL) { return; } num_el = (*mod_elements).length(); if (num_el <= 0) { return; } printf("\t\t\t"); for (int i = 0; i < num_el; i++) { modifier_el & cur_el = (*mod_elements)[i]; switch (cur_el.type) { case MOD_INVALID: printf("%s ", ModTypeStrings[MOD_INVALID]); break; case MOD_PORT: port = ((portMod *) cur_el.opaque_data)->start_port; printf("%s=%d-", ModTypeStrings[MOD_PORT], port); port = ((portMod *) cur_el.opaque_data)->end_port; printf("%d ", port); break; case MOD_IPORT: printf("%s=%d ", ModTypeStrings[MOD_IPORT], (int) (long) cur_el.opaque_data); break; case MOD_SCHEME: printf("%s=%s ", ModTypeStrings[MOD_SCHEME], (char *) cur_el.opaque_data); break; case MOD_PREFIX: printf("%s=%s ", ModTypeStrings[MOD_PREFIX], (char *) cur_el.opaque_data); break; case MOD_SUFFIX: printf("%s=%s ", ModTypeStrings[MOD_SUFFIX], (char *) cur_el.opaque_data); break; case MOD_METHOD: printf("%s=%s ", ModTypeStrings[MOD_METHOD], (char *) cur_el.opaque_data); break; case MOD_TAG: printf("%s=%s ", ModTypeStrings[MOD_TAG], (char *) cur_el.opaque_data); break; case MOD_SRC_IP: a.s_addr = ((ipMod *) cur_el.opaque_data)->start_addr; printf("%s=%s-", ModTypeStrings[MOD_SRC_IP], inet_ntoa(a)); a.s_addr = ((ipMod *) cur_el.opaque_data)->end_addr; printf("%s ", inet_ntoa(a)); break; case MOD_TIME: printf("%s=%d-%d ", ModTypeStrings[MOD_TIME], (int) ((timeMod *) cur_el.opaque_data)->start_time, (int) ((timeMod *) cur_el.opaque_data)->end_time); break; } } printf("\n"); } bool ControlBase::CheckModifiers(HttpRequestData * request_data) { if (!request_data->hdr) { //we use the same request_data for Socks as well (only IpMatcher) //we just return false here return true; } const char *data; const char *path; const char *method; ipMod *ipRange; portMod *portRange; timeMod *timeRange; time_t timeOfDay; URL *request_url = request_data->hdr->url_get(); int data_len, path_len, scheme_len, method_len; char *tag, *request_tag; ip_addr_t src_ip; int port; // If the incoming request has no tag but the entry does, or both // have tags that do not match, then we do NOT have a match. request_tag = request_data->tag; if (!request_tag && mod_elements != NULL && getModElem(MOD_TAG) != NULL) return false; // If there are no modifiers, then of course we match them if (mod_elements == NULL) { return true; } for (int i = 0; i < mod_elements->length(); i++) { modifier_el & cur_el = (*mod_elements)[i]; switch (cur_el.type) { case MOD_PORT: port = request_url->port_get(); portRange = (portMod *) cur_el.opaque_data; if (port < portRange->start_port || port > portRange->end_port) { return false; } break; case MOD_IPORT: if (request_data->incoming_port != (long) cur_el.opaque_data) { return false; } break; case MOD_SCHEME: if (request_url->scheme_get(&scheme_len) != (char *) cur_el.opaque_data) { return false; } break; case MOD_PREFIX: // INKqa07820 // The problem is that path_get() returns the URL's path // without the leading '/'. // E.g., If URL is http://inktomi/foo/bar, // then path_get() returns "foo/bar" but not "/foo/bar". // A simple solution is to skip the leading '/' in data. data = (char *) cur_el.opaque_data; if (*data == '/') data++; path = request_url->path_get(&path_len); if (ptr_len_ncmp(path, path_len, data, strlen(data)) != 0) { return false; } break; case MOD_SUFFIX: data = (char *) cur_el.opaque_data; data_len = strlen(data); ink_assert(data_len > 0); path = request_url->path_get(&path_len); // Suffix matching is case-insentive b/c it's // mainly used for file type matching and // jpeg, JPEG, Jpeg all mean the same thing // (INKqa04363) if (path_len < data_len || strncasecmp(path + (path_len - data_len), data, data_len) != 0) { return false; } break; case MOD_METHOD: method = request_data->hdr->method_get(&method_len); if (ptr_len_casecmp(method, method_len, (char *) cur_el.opaque_data) != 0) { return false; } break; case MOD_TIME: timeRange = (timeMod *) cur_el.opaque_data; // INKqa11534 // daylight saving time is not taken into consideration // so use ink_localtime_r() instead. // timeOfDay = (request_data->xact_start - ink_timezone()) % secondsInDay; { struct tm cur_tm; timeOfDay = request_data->xact_start; ink_localtime_r(&timeOfDay, &cur_tm); timeOfDay = cur_tm.tm_hour * (60 * 60) + cur_tm.tm_min * 60 + cur_tm.tm_sec; } if (timeOfDay < timeRange->start_time || timeOfDay > timeRange->end_time) { return false; } break; case MOD_SRC_IP: src_ip = htonl(request_data->src_ip); ipRange = (ipMod *) cur_el.opaque_data; if (src_ip < ipRange->start_addr || src_ip > ipRange->end_addr) { return false; } break; case MOD_TAG: // Check for a tag match. tag = (char *) cur_el.opaque_data; ink_assert(tag); if (request_tag && strcmp(request_tag, tag) != 0) { return false; } break; case MOD_INVALID: // Fall Through default: // Should never get here ink_assert(0); break; } } return true; } enum mod_errors { ME_UNKNOWN, ME_PARSE_FAILED, ME_BAD_SCHEME, ME_BAD_METHOD, ME_BAD_MOD, ME_CALLEE_GENERATED, ME_BAD_IPORT }; static const char *errorFormats[] = { "Unknown error parsing modifier", "Unable to parse modifier", "Unknown scheme", "Unknown method", "Unknown modifier", "Callee Generated", "Bad incoming port" }; const void * ControlBase::getModElem(ModifierTypes t) { for (int i = 0; i < mod_elements->length(); i++) { modifier_el & cur_el = (*mod_elements) (i); if (cur_el.type == t) { return cur_el.opaque_data; } } return NULL; } const char * ControlBase::ProcessModifiers(matcher_line * line_info) { // Variables for error processing const char *errBuf = NULL; mod_errors err = ME_UNKNOWN; int num = 0; char *label; char *val; unsigned int tmp; int num_mod_elements; const char *tmp_scheme = NULL; // Set up the array to handle the modifier num_mod_elements = (line_info->num_el > 0) ? line_info->num_el : 1; mod_elements = new DynArray<modifier_el> (&default_el, num_mod_elements); for (int i = 0; i < MATCHER_MAX_TOKENS; i++) { label = line_info->line[0][i]; val = line_info->line[1][i]; // Skip NULL tags if (label == NULL) { continue; } modifier_el & cur_el = (*mod_elements) (num); num++; // Make sure we have a value if (val == NULL) { err = ME_PARSE_FAILED; goto error; } if (strcasecmp(label, "port") == 0) { cur_el.type = MOD_PORT; errBuf = ProcessPort(val, &cur_el.opaque_data); if (errBuf != NULL) { err = ME_CALLEE_GENERATED; goto error; } } else if (strcasecmp(label, "iport") == 0) { // coverity[secure_coding] if (sscanf(val, "%d", &tmp) == 1) { cur_el.type = MOD_IPORT; cur_el.opaque_data = (void *)(uintptr_t)tmp; } else { err = ME_BAD_IPORT; goto error; } } else if (strcasecmp(label, "scheme") == 0) { tmp_scheme = hdrtoken_string_to_wks(val); if (!tmp_scheme) { err = ME_BAD_SCHEME; goto error; } cur_el.type = MOD_SCHEME; cur_el.opaque_data = (void *) tmp_scheme; } else if (strcasecmp(label, "method") == 0) { cur_el.type = MOD_METHOD; cur_el.opaque_data = (void *) xstrdup(val); } else if (strcasecmp(label, "prefix") == 0) { cur_el.type = MOD_PREFIX; cur_el.opaque_data = (void *) xstrdup(val); } else if (strcasecmp(label, "suffix") == 0) { cur_el.type = MOD_SUFFIX; cur_el.opaque_data = (void *) xstrdup(val); } else if (strcasecmp(label, "src_ip") == 0) { cur_el.type = MOD_SRC_IP; errBuf = ProcessSrcIp(val, &cur_el.opaque_data); if (errBuf != NULL) { err = ME_CALLEE_GENERATED; goto error; } } else if (strcasecmp(label, "time") == 0) { cur_el.type = MOD_TIME; errBuf = ProcessTimeOfDay(val, &cur_el.opaque_data); if (errBuf != NULL) { err = ME_CALLEE_GENERATED; goto error; } } else if (strcasecmp(label, "tag") == 0) { cur_el.type = MOD_TAG; cur_el.opaque_data = (void *) xstrdup(val); } else { err = ME_BAD_MOD; goto error; } } return NULL; error: delete mod_elements; mod_elements = NULL; if (err == ME_CALLEE_GENERATED) { return errBuf; } else { return errorFormats[err]; } } // const char* ControlBase::ProcessSrcIp(char* val, void** opaque_ptr) // // Wrapper to Parse out the src ip range // // On success, sets *opaque_ptr to a malloc allocated ipMod // structure and returns NULL // On failure, returns a static error string // const char * ControlBase::ProcessSrcIp(char *val, void **opaque_ptr) { ipMod *range = (ipMod *) xmalloc(sizeof(ipMod)); const char *errBuf = ExtractIpRange(val, &range->start_addr, &range->end_addr); if (errBuf == NULL) { *opaque_ptr = range; return NULL; } else { *opaque_ptr = NULL; xfree(range); return errBuf; } } // const char* TODtoSeconds(const char* time_str, time_t* seconds) { // // Convents a TimeOfDay (TOD) to a second value // // On success, sets *seconds to number of seconds since midnight // represented by time_str and returns NULL // // On failure, returns a static error string // const char * TODtoSeconds(const char *time_str, time_t * seconds) { int hour = 0; int min = 0; int sec = 0; time_t tmp = 0; // coverity[secure_coding] if (sscanf(time_str, "%d:%d:%d", &hour, &min, &sec) != 3) { // coverity[secure_coding] if (sscanf(time_str, "%d:%d", &hour, &min) != 2) { return "Malformed time specified"; } } if (!(hour >= 0 && hour <= 23)) { return "Illegal hour specification"; } tmp = hour * 60; if (!(min >= 0 && min <= 59)) { return "Illegal minute specification"; } tmp = (tmp + min) * 60; if (!(sec >= 0 && sec <= 59)) { return "Illegal second specification"; } tmp += sec; *seconds = tmp; return NULL; } // const char* ControlBase::ProcessTimeOfDay(char* val, void** opaque_ptr) // // Parse out a time of day range. // // On success, sets *opaque_ptr to a malloc allocated timeMod // structure and returns NULL // On failure, returns a static error string // const char * ControlBase::ProcessTimeOfDay(char *val, void **opaque_ptr) { Tokenizer rangeTok("-"); timeMod *t_mod = NULL; int num_tok; const char *errBuf; *opaque_ptr = NULL; num_tok = rangeTok.Initialize(val, SHARE_TOKS); if (num_tok == 1) { return "End time not specified"; } else if (num_tok > 2) { return "Malformed Range"; } t_mod = (timeMod *) xmalloc(sizeof(timeMod)); errBuf = TODtoSeconds(rangeTok[0], &t_mod->start_time); if (errBuf != NULL) { xfree(t_mod); return errBuf; } errBuf = TODtoSeconds(rangeTok[1], &t_mod->end_time); if (errBuf != NULL) { xfree(t_mod); return errBuf; } *opaque_ptr = t_mod; return NULL; } // const char* ControlBase::ProcessPort(char* val, void** opaque_ptr) // // Parse out a port range. // // On success, sets *opaque_ptr to a malloc allocated portMod // structure and returns NULL // On failure, returns a static error string // const char * ControlBase::ProcessPort(char *val, void **opaque_ptr) { Tokenizer rangeTok("-"); portMod *p_mod = NULL; int num_tok; *opaque_ptr = NULL; num_tok = rangeTok.Initialize(val, SHARE_TOKS); if (num_tok > 2) { return "Malformed Range"; } p_mod = (portMod *) xmalloc(sizeof(portMod)); // coverity[secure_coding] if (sscanf(rangeTok[0], "%d", &p_mod->start_port) != 1) { xfree(p_mod); return "Invalid start port"; } if (num_tok == 2) { // coverity[secure_coding] if (sscanf(rangeTok[1], "%d", &p_mod->end_port) != 1) { xfree(p_mod); return "Invalid end port"; } if (p_mod->end_port < p_mod->start_port) { xfree(p_mod); return "Malformed Range: end port < start port"; } } else { p_mod->end_port = p_mod->start_port; } *opaque_ptr = p_mod; return NULL; }
25.777963
118
0.6111
ibrezac
4fe315cdb673da9b55946c57c21be1ba59907697
29,092
cpp
C++
src/arm7tdmidisasm.cpp
KellanClark/ecnavdA-yoBemaG
56e295181255fb6c23863a5064df016d8641220a
[ "MIT" ]
3
2022-02-17T05:58:51.000Z
2022-03-29T19:41:39.000Z
src/arm7tdmidisasm.cpp
KellanClark/ecnavdA-yoBemaG
56e295181255fb6c23863a5064df016d8641220a
[ "MIT" ]
null
null
null
src/arm7tdmidisasm.cpp
KellanClark/ecnavdA-yoBemaG
56e295181255fb6c23863a5064df016d8641220a
[ "MIT" ]
null
null
null
#include "arm7tdmidisasm.hpp" static const u32 armDataProcessingMask = 0b1100'0000'0000; static const u32 armDataProcessingBits = 0b0000'0000'0000; static const u32 armMultiplyMask = 0b1111'1100'1111; static const u32 armMultiplyBits = 0b0000'0000'1001; static const u32 armMultiplyLongMask = 0b1111'1000'1111; static const u32 armMultiplyLongBits = 0b0000'1000'1001; static const u32 armPsrLoadMask = 0b1111'1011'1111; static const u32 armPsrLoadBits = 0b0001'0000'0000; static const u32 armPsrStoreRegMask = 0b1111'1011'1111; static const u32 armPsrStoreRegBits = 0b0001'0010'0000; static const u32 armPsrStoreImmediateMask = 0b1111'1011'0000; static const u32 armPsrStoreImmediateBits = 0b0011'0010'0000; static const u32 armSingleDataSwapMask = 0b1111'1011'1111; static const u32 armSingleDataSwapBits = 0b0001'0000'1001; static const u32 armBranchExchangeMask = 0b1111'1111'1111; static const u32 armBranchExchangeBits = 0b0001'0010'0001; static const u32 armHalfwordDataTransferMask = 0b1110'0000'1001; static const u32 armHalfwordDataTransferBits = 0b0000'0000'1001; static const u32 armSingleDataTransferMask = 0b1100'0000'0000; static const u32 armSingleDataTransferBits = 0b0100'0000'0000; static const u32 armUndefinedMask = 0b1110'0000'0001; static const u32 armUndefinedBits = 0b0110'0000'0001; static const u32 armBlockDataTransferMask = 0b1110'0000'0000; static const u32 armBlockDataTransferBits = 0b1000'0000'0000; static const u32 armBranchMask = 0b1110'0000'0000; static const u32 armBranchBits = 0b1010'0000'0000; static const u32 armSoftwareInterruptMask = 0b1111'0000'0000; static const u32 armSoftwareInterruptBits = 0b1111'0000'0000; static const u16 thumbMoveShiftedRegMask = 0b1110'0000'00; static const u16 thumbMoveShiftedRegBits = 0b0000'0000'00; static const u16 thumbAddSubtractMask = 0b1111'1000'00; static const u16 thumbAddSubtractBits = 0b0001'1000'00; static const u16 thumbAluImmediateMask = 0b1110'0000'00; static const u16 thumbAluImmediateBits = 0b0010'0000'00; static const u16 thumbAluRegMask = 0b1111'1100'00; static const u16 thumbAluRegBits = 0b0100'0000'00; static const u16 thumbHighRegOperationMask = 0b1111'1100'00; static const u16 thumbHighRegOperationBits = 0b0100'0100'00; static const u16 thumbPcRelativeLoadMask = 0b1111'1000'00; static const u16 thumbPcRelativeLoadBits = 0b0100'1000'00; static const u16 thumbLoadStoreRegOffsetMask = 0b1111'0010'00; static const u16 thumbLoadStoreRegOffsetBits = 0b0101'0000'00; static const u16 thumbLoadStoreSextMask = 0b1111'0010'00; static const u16 thumbLoadStoreSextBits = 0b0101'0010'00; static const u16 thumbLoadStoreImmediateOffsetMask = 0b1110'0000'00; static const u16 thumbLoadStoreImmediateOffsetBits = 0b0110'0000'00; static const u16 thumbLoadStoreHalfwordMask = 0b1111'0000'00; static const u16 thumbLoadStoreHalfwordBits = 0b1000'0000'00; static const u16 thumbSpRelativeLoadStoreMask = 0b1111'0000'00; static const u16 thumbSpRelativeLoadStoreBits = 0b1001'0000'00; static const u16 thumbLoadAddressMask = 0b1111'0000'00; static const u16 thumbLoadAddressBits = 0b1010'0000'00; static const u16 thumbSpAddOffsetMask = 0b1111'1111'00; static const u16 thumbSpAddOffsetBits = 0b1011'0000'00; static const u16 thumbPushPopRegistersMask = 0b1111'0110'00; static const u16 thumbPushPopRegistersBits = 0b1011'0100'00; static const u16 thumbMultipleLoadStoreMask = 0b1111'0000'00; static const u16 thumbMultipleLoadStoreBits = 0b1100'0000'00; static const u16 thumbConditionalBranchMask = 0b1111'0000'00; static const u16 thumbConditionalBranchBits = 0b1101'0000'00; static const u16 thumbSoftwareInterruptMask = 0b1111'1111'00; static const u16 thumbSoftwareInterruptBits = 0b1101'1111'00; static const u16 thumbUnconditionalBranchMask = 0b1111'1000'00; static const u16 thumbUnconditionalBranchBits = 0b1110'0000'00; static const u16 thumbLongBranchLinkMask = 0b1111'0000'00; static const u16 thumbLongBranchLinkBits = 0b1111'0000'00; std::string ARM7TDMIDisassembler::disassemble(u32 address, u32 opcode, bool thumb) { std::stringstream disassembledOpcode; // Get condition code std::string conditionCode; switch (thumb ? ((opcode >> 8) & 0xF) : (opcode >> 28)) { case 0x0: conditionCode = "EQ"; break; case 0x1: conditionCode = "NE"; break; case 0x2: conditionCode = "CS"; break; case 0x3: conditionCode = "CC"; break; case 0x4: conditionCode = "MI"; break; case 0x5: conditionCode = "PL"; break; case 0x6: conditionCode = "VS"; break; case 0x7: conditionCode = "VC"; break; case 0x8: conditionCode = "HI"; break; case 0x9: conditionCode = "LS"; break; case 0xA: conditionCode = "GE"; break; case 0xB: conditionCode = "LT"; break; case 0xC: conditionCode = "GT"; break; case 0xD: conditionCode = "LE"; break; case 0xE: conditionCode = options.showALCondition ? "AL" : ""; break; default: if (thumb) { conditionCode = "Undefined"; break; } else { return "Undefined"; } } if (thumb) { u16 lutIndex = opcode >> 6; if ((lutIndex & thumbAddSubtractMask) == thumbAddSubtractBits) { bool immediate = lutIndex & 0b0000'0100'00; bool op = lutIndex & 0b0000'0010'00; int offset = lutIndex & 0b0000'0001'11; disassembledOpcode << (op ? "SUB " : "ADD "); disassembledOpcode << getRegName(opcode & 7) << ", " << getRegName((opcode >> 3) & 7) << ", "; if (immediate) { disassembledOpcode << "#"; if (options.printOperandsHex) disassembledOpcode << "0x" << std::hex; disassembledOpcode << offset; } else { disassembledOpcode << getRegName(offset); } return disassembledOpcode.str(); } else if ((lutIndex & thumbMoveShiftedRegMask) == thumbMoveShiftedRegBits) { int op = (lutIndex & 0b0001'1000'00) >> 5; int shiftAmount = lutIndex & 0b0000'0111'11; switch (op) { case 0: disassembledOpcode << "LSL"; break; case 1: disassembledOpcode << "LSR"; break; case 2: disassembledOpcode << "ASR"; break; } disassembledOpcode << " " << getRegName(opcode & 7) << ", " << getRegName((opcode >> 3) & 7) << ", #"; if ((shiftAmount == 0) && (op != 0)) shiftAmount = 32; disassembledOpcode << shiftAmount; return disassembledOpcode.str(); } else if ((lutIndex & thumbAluImmediateMask) == thumbAluImmediateBits) { int op = (lutIndex & 0b0001'1000'00) >> 5; int destinationReg = (lutIndex & 0b0000'0111'00) >> 2; switch (op) { case 0: disassembledOpcode << "MOV"; break; case 1: disassembledOpcode << "CMP"; break; case 2: disassembledOpcode << "ADD"; break; case 3: disassembledOpcode << "SUB"; break; } disassembledOpcode << " " << getRegName(destinationReg) << ", #"; if (options.printOperandsHex) { disassembledOpcode << "0x" << std::hex; } disassembledOpcode << (opcode & 0xFF); return disassembledOpcode.str(); } else if ((lutIndex & thumbAluRegMask) == thumbAluRegBits) { int op = lutIndex & 0b0000'0011'11; switch (op) { case 0x0: disassembledOpcode << "AND"; break; case 0x1: disassembledOpcode << "EOR"; break; case 0x2: disassembledOpcode << "LSL"; break; case 0x3: disassembledOpcode << "LSR"; break; case 0x4: disassembledOpcode << "ASR"; break; case 0x5: disassembledOpcode << "ADC"; break; case 0x6: disassembledOpcode << "SBC"; break; case 0x7: disassembledOpcode << "ROR"; break; case 0x8: disassembledOpcode << "TST"; break; case 0x9: disassembledOpcode << "NEG"; break; case 0xA: disassembledOpcode << "CMP"; break; case 0xB: disassembledOpcode << "CMN"; break; case 0xC: disassembledOpcode << "ORR"; break; case 0xD: disassembledOpcode << "MUL"; break; case 0xE: disassembledOpcode << "BIC"; break; case 0xF: disassembledOpcode << "MVN"; break; } disassembledOpcode << " " << getRegName(opcode & 7) << ", " << getRegName((opcode >> 3) & 7); return disassembledOpcode.str(); } else if ((lutIndex & thumbHighRegOperationMask) == thumbHighRegOperationBits) { int op = (lutIndex & 0b0000'0011'00) >> 2; bool opFlag1 = lutIndex & 0b0000'0000'10; bool opFlag2 = lutIndex & 0b0000'0000'01; switch (op) { case 0: disassembledOpcode << "ADD "; break; case 1: disassembledOpcode << "CMP "; break; case 2: disassembledOpcode << "MOV "; break; case 3: disassembledOpcode << "BX "; break; } if (op != 3) disassembledOpcode << getRegName((opcode & 0x7) + (opFlag1 ? 8 : 0)) << ", "; disassembledOpcode << getRegName(((opcode >> 3) & 0x7) + (opFlag2 ? 8 : 0)); return disassembledOpcode.str(); } else if ((lutIndex & thumbPcRelativeLoadMask) == thumbPcRelativeLoadBits) { int destinationReg = (lutIndex & 0b0000'0111'00) >> 2; disassembledOpcode << "LDR " << getRegName(destinationReg) << ", [" << getRegName(15) << ", "; if (options.printOperandsHex) disassembledOpcode << "0x" << std::hex; disassembledOpcode << ((opcode & 0xFF) << 2) << "]"; return disassembledOpcode.str(); } else if ((lutIndex & thumbLoadStoreRegOffsetMask) == thumbLoadStoreRegOffsetBits) { bool loadStore = lutIndex & 0b0000'1000'00; bool byteWord = lutIndex & 0b0000'0100'00; int offsetReg = lutIndex & 0b0000'0001'11; // I was lazy and put this all on one line disassembledOpcode << (loadStore ? "LDR" : "STR") << (byteWord ? "B " : " ") << getRegName(opcode & 7) << ", [" << getRegName((opcode >> 3) & 7) << ", " << getRegName(offsetReg) << "]"; return disassembledOpcode.str(); } else if ((lutIndex & thumbLoadStoreSextMask) == thumbLoadStoreSextBits) { int hsBits = (lutIndex & 0b0000'1100'00) >> 4; int offsetReg = lutIndex & 0b0000'0001'11; switch (hsBits) { case 0: disassembledOpcode << "STRH "; break; case 1: disassembledOpcode << "LDSB "; break; case 2: disassembledOpcode << "LDRH "; break; case 3: disassembledOpcode << "LDSH "; break; } disassembledOpcode << getRegName(opcode & 7) << ", [" << getRegName((opcode >> 3) & 7) << ", " << getRegName(offsetReg) << "]"; return disassembledOpcode.str(); } else if ((lutIndex & thumbLoadStoreImmediateOffsetMask) == thumbLoadStoreImmediateOffsetBits) { bool byteWord = lutIndex & 0b0001'0000'00; bool loadStore = lutIndex & 0b0000'1000'00; int offset = lutIndex & 0b0000'0111'11; disassembledOpcode << (loadStore ? "LDR" : "STR") << (byteWord ? "B " : " "); disassembledOpcode << getRegName(opcode & 7) << ", [" << getRegName((opcode >> 3) & 7) << ", #"; if (options.printOperandsHex) disassembledOpcode << "0x" << std::hex; disassembledOpcode << (byteWord ? offset : (offset << 2)) << "]"; return disassembledOpcode.str(); } else if ((lutIndex & thumbLoadStoreHalfwordMask) == thumbLoadStoreHalfwordBits) { bool loadStore = lutIndex & 0b0000'1000'00; int offset = lutIndex & 0b0000'0111'11; disassembledOpcode << (loadStore ? "LDRH " : "STRH "); disassembledOpcode << getRegName(opcode & 7) << ", [" << getRegName((opcode >> 3) & 7) << ", #"; if (options.printOperandsHex) disassembledOpcode << "0x" << std::hex; disassembledOpcode << (offset << 1) << "]"; return disassembledOpcode.str(); } else if ((lutIndex & thumbSpRelativeLoadStoreMask) == thumbSpRelativeLoadStoreBits) { bool loadStore = lutIndex & 0b0000'1000'00; int destinationReg = (lutIndex & 0b0000'0111'00) >> 2; disassembledOpcode << (loadStore ? "LDR " : "STR ") << getRegName(destinationReg) << ", [" << getRegName(13) << ", #"; if (options.printOperandsHex) disassembledOpcode << "0x" << std::hex; disassembledOpcode << ((opcode & 0xFF) << 2) << "]"; return disassembledOpcode.str(); } else if ((lutIndex & thumbLoadAddressMask) == thumbLoadAddressBits) { bool spPc = lutIndex & 0b0000'1000'00; int destinationReg = (lutIndex & 0b0000'0111'00) >> 2; disassembledOpcode << "ADD " << getRegName(destinationReg) << ", " << getRegName(spPc ? 13 : 15) << ", #"; if (options.printOperandsHex) { disassembledOpcode << "0x" << std::hex; } disassembledOpcode << ((opcode & 0xFF) << 2); return disassembledOpcode.str(); } else if ((lutIndex & thumbSpAddOffsetMask) == thumbSpAddOffsetBits) { bool isNegative = lutIndex & 0b0000'0000'10; disassembledOpcode << "ADD sp, #"; if (options.printOperandsHex) disassembledOpcode << "0x" << std::hex; disassembledOpcode << (isNegative ? "-" : "") << ((opcode & 0x7F) << 2); return disassembledOpcode.str(); } else if ((lutIndex & thumbPushPopRegistersMask) == thumbPushPopRegistersBits) { bool loadStore = lutIndex & 0b0000'1000'00; bool pcLr = lutIndex & 0b0000'0001'00; disassembledOpcode << (loadStore ? "POP" : "PUSH") << " {"; bool registerList[10] = {false}; for (int i = 0; i < 8; i++) registerList[i] = (opcode & (1 << i)); bool hasPrintedRegister = false; for (int i = 0; i < 8; i++) { if (registerList[i]) { disassembledOpcode << (hasPrintedRegister ? "," : "") << getRegName(i); hasPrintedRegister = true; if (registerList[i + 1] && registerList[i + 2]) { disassembledOpcode << "-"; do { ++i; } while (registerList[i + 1]); disassembledOpcode << getRegName(i); } } } if (pcLr) disassembledOpcode << (hasPrintedRegister ? "," : "") << getRegName(loadStore ? 15 : 14); disassembledOpcode << "}"; return disassembledOpcode.str(); } else if ((lutIndex & thumbMultipleLoadStoreMask) == thumbMultipleLoadStoreBits) { bool loadStore = lutIndex & 0b0000'1000'00; int baseReg = (lutIndex & 0b0000'0111'00) >> 2; disassembledOpcode << (loadStore ? "LDMIA " : "STMIA ") << getRegName(baseReg) << "!, {"; bool registerList[10] = {false}; for (int i = 0; i < 8; i++) registerList[i] = (opcode & (1 << i)); bool hasPrintedRegister = false; for (int i = 0; i < 8; i++) { if (registerList[i]) { disassembledOpcode << (hasPrintedRegister ? "," : "") << getRegName(i); hasPrintedRegister = true; if (registerList[i + 1] && registerList[i + 2]) { disassembledOpcode << "-"; do { ++i; } while (registerList[i + 1]); disassembledOpcode << getRegName(i); } } } disassembledOpcode << "}"; return disassembledOpcode.str(); } else if ((lutIndex & thumbSoftwareInterruptMask) == thumbSoftwareInterruptBits) { if (options.printOperandsHex) { disassembledOpcode << "SWI" << " #0x" << std::hex << (opcode & 0x00FF); } else { disassembledOpcode << "SWI" << " #" << (opcode & 0x00FF); } return disassembledOpcode.str(); } else if ((lutIndex & thumbConditionalBranchMask) == thumbConditionalBranchBits) { u32 jmpAddress = address + ((i16)((u16)opcode << 8) >> 7) + 4; disassembledOpcode << "B" << conditionCode << " #"; if (options.printAddressesHex) disassembledOpcode << "0x" << std::hex; disassembledOpcode << jmpAddress; return disassembledOpcode.str(); } else if ((lutIndex & thumbUnconditionalBranchMask) == thumbUnconditionalBranchBits) { u32 jmpAddress = address + ((i16)((u16)opcode << 5) >> 4) + 4; disassembledOpcode << "B #"; if (options.printAddressesHex) disassembledOpcode << "0x" << std::hex; disassembledOpcode << jmpAddress; return disassembledOpcode.str(); } else if ((lutIndex & thumbLongBranchLinkMask) == thumbLongBranchLinkBits) { bool lowHigh = lutIndex & 0b0000'1000'00; if (lowHigh) { disassembledOpcode << "ADD " << getRegName(14) << ", " << getRegName(14) << ", #"; if (options.printOperandsHex) disassembledOpcode << "0x" << std::hex; disassembledOpcode << ((opcode & 0x7FF) << 1); disassembledOpcode << "; BL " << getRegName(14); } else { disassembledOpcode << "ADD " << getRegName(14) << ", " << getRegName(15) << ", #"; if (options.printOperandsHex) disassembledOpcode << "0x" << std::hex; disassembledOpcode << ((i32)((u32)opcode << 21) >> 9); } return disassembledOpcode.str(); } return "Undefined THUMB"; } else { u32 lutIndex = ((opcode & 0x0FF00000) >> 16) | ((opcode & 0x000000F0) >> 4); if ((lutIndex & armMultiplyMask) == armMultiplyBits) { bool accumulate = lutIndex & 0b0000'0010'0000; bool sBit = lutIndex & 0b0000'0001'0000; if (accumulate) { disassembledOpcode << "MLA"; } else { disassembledOpcode << "MUL"; } disassembledOpcode << conditionCode << (sBit ? "S" : "") << " "; disassembledOpcode << getRegName((opcode >> 16) & 0xF) << ", " << getRegName(opcode & 0xF) << ", " << getRegName((opcode >> 8) & 0xF); if (accumulate) disassembledOpcode << ", " << getRegName((opcode >> 12) & 0xF); return disassembledOpcode.str(); } else if ((lutIndex & armMultiplyLongMask) == armMultiplyLongBits) { bool signedMul = lutIndex & 0b0000'0100'0000; bool accumulate = lutIndex & 0b0000'0010'0000; bool sBit = lutIndex & 0b0000'0001'0000; disassembledOpcode << (signedMul ? "S" : "U"); if (accumulate) { disassembledOpcode << "MLAL"; } else { disassembledOpcode << "MULL"; } disassembledOpcode << conditionCode << (sBit ? "S" : "") << " "; disassembledOpcode << getRegName((opcode >> 12) & 0xF) << ", " << getRegName((opcode >> 16) & 0xF) << ", " << getRegName(opcode & 0xF) << ", " << getRegName((opcode >> 8) & 0xF); if (accumulate) disassembledOpcode << ", " << getRegName((opcode >> 12) & 0xF); return disassembledOpcode.str(); } else if ((lutIndex & armSingleDataSwapMask) == armSingleDataSwapBits) { bool byteWord = lutIndex & 0b0000'0100'0000; disassembledOpcode << "SWP" << conditionCode << (byteWord ? "B " : " "); disassembledOpcode << getRegName((opcode >> 12) & 0xF) << ", " << getRegName(opcode & 0xF) << ", [" << getRegName((opcode >> 16) & 0xF) << "]"; return disassembledOpcode.str(); } else if ((lutIndex & armPsrLoadMask) == armPsrLoadBits) { bool targetPSR = lutIndex & 0b0000'0100'0000; disassembledOpcode << "MRS" << conditionCode << " "; disassembledOpcode << getRegName((opcode >> 12) & 0xF) << ", " << (targetPSR ? "SPSR" : "CPSR"); return disassembledOpcode.str(); } else if ((lutIndex & armPsrStoreRegMask) == armPsrStoreRegBits) { bool targetPSR = lutIndex & 0b0000'0100'0000; disassembledOpcode << "MSR" << conditionCode << " "; disassembledOpcode << (targetPSR ? "SPSR_" : "CPSR_"); disassembledOpcode << ((opcode & (1 << 19)) ? "f" : "") << ((opcode & (1 << 18)) ? "s" : "") << ((opcode & (1 << 17)) ? "x" : "") << ((opcode & (1 << 16)) ? "c" : "") << ", "; disassembledOpcode << getRegName(opcode & 0xF); return disassembledOpcode.str(); } else if ((lutIndex & armPsrStoreImmediateMask) == armPsrStoreImmediateBits) { bool targetPSR = lutIndex & 0b0000'0100'0000; disassembledOpcode << "MSR" << conditionCode << " "; disassembledOpcode << (targetPSR ? "SPSR_" : "CPSR_"); disassembledOpcode << ((opcode & (1 << 19)) ? "f" : "") << ((opcode & (1 << 18)) ? "s" : "") << ((opcode & (1 << 17)) ? "x" : "") << ((opcode & (1 << 16)) ? "c" : "") << ", #"; if (options.printOperandsHex) disassembledOpcode << "0x" << std::hex; u32 operand = opcode & 0xFF; u32 shiftAmount = (opcode & (0xF << 8)) >> 7; disassembledOpcode << (shiftAmount ? ((operand >> shiftAmount) | (operand << (32 - shiftAmount))) : operand); return disassembledOpcode.str(); } else if ((lutIndex & armBranchExchangeMask) == armBranchExchangeBits) { disassembledOpcode << "BX" << conditionCode << " " << getRegName(opcode & 0xF); return disassembledOpcode.str(); } else if ((lutIndex & armHalfwordDataTransferMask) == armHalfwordDataTransferBits) { bool prePostIndex = lutIndex & 0b0001'0000'0000; bool upDown = lutIndex & 0b0000'1000'0000; bool immediateOffset = lutIndex & 0b0000'0100'0000; bool writeBack = lutIndex & 0b0000'0010'0000; bool loadStore = lutIndex & 0b0000'0001'0000; int shBits = (lutIndex & 0b0000'0000'0110) >> 1; disassembledOpcode << (loadStore ? "LDR" : "STR") << conditionCode; switch (shBits) { case 0: return "Undefined"; case 1: disassembledOpcode << "H"; break; case 2: disassembledOpcode << "SB"; break; case 3: disassembledOpcode << "SH"; break; } disassembledOpcode << " r" << ((opcode >> 12) & 0xF) << ", [r" << ((opcode >> 16) & 0xF); u32 offset; if (immediateOffset) { offset = ((opcode & 0xF00) >> 4) | (opcode & 0xF); if (offset == 0) { disassembledOpcode << "]"; return disassembledOpcode.str(); } } if (!prePostIndex) disassembledOpcode << "]"; disassembledOpcode << ", "; if (immediateOffset) { disassembledOpcode << (upDown ? "#" : "#-") << offset; } else { disassembledOpcode << (upDown ? "+r" : "-r") << (opcode & 0xF); } if (prePostIndex) disassembledOpcode << "]" << (writeBack ? "!" : ""); return disassembledOpcode.str(); } else if ((lutIndex & armDataProcessingMask) == armDataProcessingBits) { auto operation = (lutIndex & 0b0001'1110'0000) >> 5; bool sBit = lutIndex & 0b0000'0001'0000; bool printRd = true; bool printRn = true; switch (operation) { case 0x0: disassembledOpcode << "AND"; break; case 0x1: disassembledOpcode << "EOR"; break; case 0x2: disassembledOpcode << "SUB"; break; case 0x3: disassembledOpcode << "RSB"; break; case 0x4: disassembledOpcode << "ADD"; break; case 0x5: disassembledOpcode << "ADC"; break; case 0x6: disassembledOpcode << "SBC"; break; case 0x7: disassembledOpcode << "RSC"; break; case 0x8: disassembledOpcode << "TST"; printRd = false; break; case 0x9: disassembledOpcode << "TEQ"; printRd = false; break; case 0xA: disassembledOpcode << "CMP"; printRd = false; break; case 0xB: disassembledOpcode << "CMN"; printRd = false; break; case 0xC: disassembledOpcode << "ORR"; break; case 0xD: disassembledOpcode << "MOV"; printRn = false; break; case 0xE: disassembledOpcode << "BIC"; break; case 0xF: disassembledOpcode << "MVN"; printRn = false; break; } if ((printRd && sBit) || options.alwaysShowSBit) disassembledOpcode << "S"; disassembledOpcode << conditionCode << " "; if (printRd) disassembledOpcode << "r" << (((0xF << 12) & opcode) >> 12) << ", "; if (printRn) disassembledOpcode << "r" << (((0xF << 16) & opcode) >> 16) << ", "; disassembledOpcode << disassembleShift(opcode, false); return disassembledOpcode.str(); } else if ((lutIndex & armUndefinedMask) == armUndefinedBits) { return "Undefined"; } else if ((lutIndex & armSingleDataTransferMask) == armSingleDataTransferBits) { bool immediateOffset = lutIndex & 0b0010'0000'0000; bool prePostIndex = lutIndex & 0b0001'0000'0000; bool byteWord = lutIndex & 0b0000'0100'0000; bool writeBack = lutIndex & 0b0000'0010'0000; bool loadStore = lutIndex & 0b0000'0001'0000; disassembledOpcode << (loadStore ? "LDR" : "STR") << conditionCode << (byteWord ? "B " : " "); disassembledOpcode << getRegName((opcode >> 12) & 0xF) << ", [" << getRegName((opcode >> 16) & 0xF); if (immediateOffset && ((opcode & 0xFFF) == 0)) { disassembledOpcode << "]"; return disassembledOpcode.str(); } if (!prePostIndex) { disassembledOpcode << "], "; } else { disassembledOpcode << ", "; } disassembledOpcode << disassembleShift(opcode, true); if (prePostIndex) disassembledOpcode << "]" << (writeBack ? "!" : ""); return disassembledOpcode.str(); } else if ((lutIndex & armBlockDataTransferMask) == armBlockDataTransferBits) { bool prePostIndex = lutIndex & 0b0001'0000'0000; bool upDown = lutIndex & 0b0000'1000'0000; bool sBit = lutIndex & 0b0000'0100'0000; bool writeBack = lutIndex & 0b0000'0010'0000; bool loadStore = lutIndex & 0b0000'0001'0000; auto baseRegister = (opcode >> 16) & 0xF; if (options.simplifyPushPop && (baseRegister == 13) && ((loadStore && !prePostIndex && upDown) || (!loadStore && prePostIndex && !upDown)) && writeBack && !sBit) { disassembledOpcode << (loadStore ? "POP" : "PUSH") << conditionCode << " {"; } else { disassembledOpcode << (loadStore ? "LDM" : "STM") << conditionCode; // Code based on Table 4-6: Addressing mode names if (options.ldmStmStackSuffixes) { switch ((loadStore << 2) | (prePostIndex << 1) | upDown) { case 7: disassembledOpcode << "ED"; break; case 5: disassembledOpcode << "FD"; break; case 6: disassembledOpcode << "EA"; break; case 4: disassembledOpcode << "FA"; break; case 3: disassembledOpcode << "FA"; break; case 1: disassembledOpcode << "EA"; break; case 2: disassembledOpcode << "FD"; break; case 0: disassembledOpcode << "ED"; break; } } else { switch ((loadStore << 2) | (prePostIndex << 1) | upDown) { case 7: disassembledOpcode << "IB"; break; case 5: disassembledOpcode << "IA"; break; case 6: disassembledOpcode << "DB"; break; case 4: disassembledOpcode << "DA"; break; case 3: disassembledOpcode << "IB"; break; case 1: disassembledOpcode << "IA"; break; case 2: disassembledOpcode << "DB"; break; case 0: disassembledOpcode << "DA"; break; } } disassembledOpcode << " " << getRegName(baseRegister) << (writeBack ? "!" : "") << ", {"; } // Print register list bool registerList[18] = {false}; for (int i = 0; i < 16; i++) registerList[i] = (opcode & (1 << i)); bool hasPrintedRegister = false; for (int i = 0; i < 16; i++) { if (registerList[i]) { disassembledOpcode << (hasPrintedRegister ? "," : "") << getRegName(i); hasPrintedRegister = true; if (registerList[i + 1] && registerList[i + 2]) { // Shorten group of registers disassembledOpcode << "-"; do { ++i; } while (registerList[i + 1]); disassembledOpcode << getRegName(i); } } } disassembledOpcode << "}"; if (sBit) disassembledOpcode << "^"; return disassembledOpcode.str(); } else if ((lutIndex & armBranchMask) == armBranchBits) { if (lutIndex & 0b0001'0000'0000) { disassembledOpcode << "BL"; } else { disassembledOpcode << "B"; } disassembledOpcode << conditionCode; u32 jumpLocation = address + (((i32)((opcode & 0x00FFFFFF) << 8)) >> 6) + 8; if (options.printAddressesHex) { disassembledOpcode << " #0x" << std::hex << jumpLocation; } else { disassembledOpcode << " #" << jumpLocation; } return disassembledOpcode.str(); } else if ((lutIndex & armSoftwareInterruptMask) == armSoftwareInterruptBits) { if (options.printAddressesHex) { disassembledOpcode << "SWI" << conditionCode << " #0x" << std::hex << (opcode & 0x00FFFFFF); } else { disassembledOpcode << "SWI" << conditionCode << " #" << (opcode & 0x00FFFFFF); } return disassembledOpcode.str(); } return "Undefined ARM"; } } std::string ARM7TDMIDisassembler::getRegName(unsigned int regNumber) { if (options.simplifyRegisterNames) { switch (regNumber) { case 13: return "sp"; case 14: return "lr"; case 15: return "pc"; } } return (std::string)"r" + std::to_string(regNumber); } std::string ARM7TDMIDisassembler::disassembleShift(u32 opcode, bool showUpDown) { std::stringstream returnValue; if (showUpDown && !((opcode >> 25) & 1)) { returnValue << ((showUpDown & !((opcode >> 23) & 1)) ? "#-" : "#"); if (options.printOperandsHex) { returnValue << "0x" << std::hex; } returnValue << (opcode & 0xFFF); return returnValue.str(); } else if (((opcode >> 25) & 1) && !showUpDown) { u32 shiftAmount = (opcode & (0xF << 8)) >> 7; u32 shiftInput = opcode & 0xFF; shiftInput = shiftAmount ? ((shiftInput >> shiftAmount) | (shiftInput << (32 - shiftAmount))) : shiftInput; if (options.printOperandsHex) { returnValue << "#0x" << std::hex << shiftInput; } else { returnValue << "#" << shiftInput; } } else { if (showUpDown) { returnValue << (((opcode >> 23) & 1) ? "r" : "-r") << (opcode & 0xF); } else { returnValue << getRegName(opcode & 0xF); } if ((opcode & 0xFF0) == 0) // LSL #0 return returnValue.str(); switch ((opcode >> 5) & 3) { case 0: returnValue << ", LSL "; break; case 1: returnValue << ", LSR "; break; case 2: returnValue << ", ASR "; break; case 3: if (!(opcode & (1 << 4)) && (((opcode & (0x1F << 7)) >> 7) == 0)) { returnValue << ", RRX"; return returnValue.str(); } else { returnValue << ", ROR "; } break; } if (opcode & (1 << 4)) { returnValue << "r" << ((opcode & (0xF << 8)) >> 8); } else { auto shiftAmount = ((opcode & (0x1F << 7)) >> 7); if ((shiftAmount == 0) && ((opcode & (3 << 5)) != 0)) shiftAmount = 32; returnValue << "#" << shiftAmount; } } return returnValue.str(); } void ARM7TDMIDisassembler::defaultSettings() { options.showALCondition = false; options.alwaysShowSBit = false; options.printOperandsHex = true; options.printAddressesHex = true; options.simplifyRegisterNames = false; options.simplifyPushPop = false; options.ldmStmStackSuffixes = false; } ARM7TDMIDisassembler disassembler;
37.538065
188
0.647498
KellanClark
4fe31d5cf1dc1f07d35028caae068d23ce061886
129
hpp
C++
deps/opencv/win/include/opencv2/xphoto/tonemap.hpp
YLiLarry/ggframe
ffb6a7d7d878c155d03830cf6fb6fb8f948084f0
[ "MIT" ]
null
null
null
deps/opencv/win/include/opencv2/xphoto/tonemap.hpp
YLiLarry/ggframe
ffb6a7d7d878c155d03830cf6fb6fb8f948084f0
[ "MIT" ]
null
null
null
deps/opencv/win/include/opencv2/xphoto/tonemap.hpp
YLiLarry/ggframe
ffb6a7d7d878c155d03830cf6fb6fb8f948084f0
[ "MIT" ]
null
null
null
version https://git-lfs.github.com/spec/v1 oid sha256:47ff9de6ff45a1c42bd6bdeb0c3013cc69dbf46ce5d5025bc3e920128f0ee5c2 size 2082
32.25
75
0.883721
YLiLarry
4fef86e35d345c50885e6ad6284ec9fc522ea862
2,441
cpp
C++
tests/test_tcpEchoServer.cpp
yangshaoguang/ZLToolKit
d3a1bd9d8a3162d0237954034d85f1313008cab2
[ "MIT" ]
null
null
null
tests/test_tcpEchoServer.cpp
yangshaoguang/ZLToolKit
d3a1bd9d8a3162d0237954034d85f1313008cab2
[ "MIT" ]
null
null
null
tests/test_tcpEchoServer.cpp
yangshaoguang/ZLToolKit
d3a1bd9d8a3162d0237954034d85f1313008cab2
[ "MIT" ]
1
2022-03-20T05:15:09.000Z
2022-03-20T05:15:09.000Z
/* * MIT License * * Copyright (c) 2016 xiongziliang <771730766@qq.com> * * 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 <signal.h> #include <iostream> #include "Util/logger.h" #include "Util/TimeTicker.h" #include "Network/TcpServer.h" #include "Network/TcpSession.h" using namespace std; using namespace toolkit; class EchoSession: public TcpSession { public: EchoSession(const Socket::Ptr &sock) : TcpSession(sock) { DebugL; } ~EchoSession() { DebugL; } virtual void onRecv(const Buffer::Ptr &buf) override{ //处理客户端发送过来的数据 TraceL << buf->data(); //把数据回显至客户端 *(this) << "recved " << buf->size() << ": " << buf; } virtual void onError(const SockException &err) override{ //客户端断开连接或其他原因导致该对象脱离TCPServer管理 WarnL << err.what(); } virtual void onManager() override{ //定时管理该对象,譬如会话超时检查 DebugL; if(_ticker.createdTime() > 5 * 1000){ shutdown(); } } private: Ticker _ticker; }; int main() { //退出程序事件处理 signal(SIGINT, [](int){EventPoller::Instance().shutdown();}); //初始化日志模块 Logger::Instance().add(std::make_shared<ConsoleChannel>("stdout", LTrace)); Logger::Instance().setWriter(std::make_shared<AsyncLogWriter>()); TcpServer::Ptr server(new TcpServer(nullptr, nullptr)); server->start<EchoSession>(9000);//监听9000端口 EventPoller::Instance().runLoop();//主线程事件轮询 server.reset();//销毁服务器 EventPoller::Destory(); Logger::Destory(); return 0; }
29.768293
81
0.721016
yangshaoguang
4feff197ef20e1b384e9879c4734db628ade5b22
6,444
cpp
C++
src/city_test.cpp
mheyman/daw_json_link_vcpkg_tests
efb56c122bec2f1a80d6a1843752510a2a8ca956
[ "BSL-1.0" ]
275
2019-04-28T18:53:01.000Z
2022-03-29T23:10:14.000Z
src/city_test.cpp
mheyman/daw_json_link_vcpkg_tests
efb56c122bec2f1a80d6a1843752510a2a8ca956
[ "BSL-1.0" ]
78
2019-11-15T16:20:11.000Z
2022-02-23T01:24:49.000Z
src/city_test.cpp
mheyman/daw_json_link_vcpkg_tests
efb56c122bec2f1a80d6a1843752510a2a8ca956
[ "BSL-1.0" ]
15
2019-06-20T10:28:47.000Z
2022-03-10T16:45:10.000Z
// Copyright (c) Darrell Wright // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/beached/daw_json_link // // This file highlights some of the ways of working with JSON array documents as // they can be reified into a container or iterated over. When using the // iterator/range interface we can use the std algorithms to do things like // count/accumulate them #include "defines.h" #include "daw/json/daw_json_iterator.h" #include "daw/json/daw_json_link.h" #include <daw/daw_benchmark.h> #include <daw/daw_read_file.h> #include <daw/iterator/daw_back_inserter.h> #include <fstream> #include <iostream> #include <streambuf> #include <string_view> #include <vector> #if not defined( DAW_NUM_RUNS ) #if not defined( DEBUG ) or defined( NDEBUG ) static inline constexpr std::size_t DAW_NUM_RUNS = 250; #else static inline constexpr std::size_t DAW_NUM_RUNS = 2; #endif #endif static_assert( DAW_NUM_RUNS > 0 ); struct City { std::string country; std::string name; float lat; float lng; }; namespace daw::json { template<> struct json_data_contract<City> { #ifdef __cpp_nontype_template_parameter_class using type = json_member_list<json_string<"country">, json_string<"name">, json_number<"lat", float, LiteralAsStringOpt::Always>, json_number<"lng", float, LiteralAsStringOpt::Always>>; #else static constexpr char const country[] = "country"; static constexpr char const name[] = "name"; static constexpr char const lat[] = "lat"; static constexpr char const lng[] = "lng"; using type = json_member_list<json_string<country>, json_string<name>, json_number<lat, float, LiteralAsStringOpt::Always>, json_number<lng, float, LiteralAsStringOpt::Always>>; #endif static inline auto to_json_data( City const &c ) { return std::forward_as_tuple( c.country, c.name, c.lat, c.lng ); } }; } // namespace daw::json int main( int argc, char **argv ) #ifdef DAW_USE_JSON_EXCEPTIONS try #endif { if( argc <= 1 ) { puts( "Must supply path to cities.json file\n" ); exit( EXIT_FAILURE ); } auto file_data = *daw::read_file( argv[1] ); auto const json_data = std::string_view( file_data.data( ), file_data.size( ) ); std::cout << "File size(B): " << json_data.size( ) << " " << daw::utility::to_bytes_per_second( json_data.size( ) ) << '\n'; auto count = *daw::bench_n_test_mbs<DAW_NUM_RUNS>( "cities parsing 1", json_data.size( ), []( auto sv ) { std::vector<City> data = daw::json::from_json_array<City>( sv ); daw::do_not_optimize( data ); return data.size( ); }, json_data ); std::cout << "element count: " << count << '\n'; using iterator_t = daw::json::json_array_iterator<City>; auto data = std::vector<City>( ); auto count2 = *daw::bench_n_test_mbs<DAW_NUM_RUNS>( "cities parsing 2", json_data.size( ), [&]( auto const &sv ) { data.clear( ); std::copy( iterator_t( sv ), iterator_t( ), daw::back_inserter( data ) ); daw::do_not_optimize( data ); return data.size( ); }, json_data ); std::cout << "element count 2: " << count2 << '\n'; auto count3 = *daw::bench_n_test_mbs<DAW_NUM_RUNS>( "cities parsing 3", json_data.size( ), []( auto const &sv ) { return static_cast<size_t>( std::distance( iterator_t( sv ), iterator_t( ) ) ); }, json_data ); std::cout << "element count 3: " << count3 << '\n'; auto has_toronto = *daw::bench_n_test_mbs<DAW_NUM_RUNS>( "Find Toronto", json_data.size( ), []( auto &&sv ) -> std::optional<City> { auto pos = std::find_if( iterator_t( sv ), iterator_t( ), []( City &&city ) { return city.name == "Toronto"; } ); if( pos != iterator_t( ) ) { return *pos; } return std::nullopt; }, json_data ); std::cout << "Toronto was " << ( has_toronto ? "" : "not" ); if( has_toronto ) { std::cout << " found at " << daw::json::to_json( *has_toronto ); } std::cout << '\n'; auto has_chitungwiza = *daw::bench_n_test_mbs<DAW_NUM_RUNS>( "Find Chitungwiza(last item)", json_data.size( ), []( auto &&sv ) -> std::optional<City> { auto pos = std::find_if( iterator_t( sv ), iterator_t( ), []( City &&city ) { return city.name == "Chitungwiza"; } ); if( pos != iterator_t( ) ) { return *pos; } return std::nullopt; }, json_data ); std::cout << "Chitungwiza was " << ( has_chitungwiza ? "" : "not" ) << " found at " << daw::json::to_json( *has_chitungwiza ) << '\n'; std::cout << ( *iterator_t( json_data ) ).name << '\n'; auto const city_ary = daw::json::from_json_array<City>( json_data ); auto const city_ary_str = daw::json::to_json_array( city_ary ); auto sv = std::string_view( city_ary_str ); std::cout << sv.substr( 0, 100 ) << "... " << sv.substr( sv.size( ) - 100 ) << '\n'; auto mid_lat = *daw::bench_n_test_mbs<DAW_NUM_RUNS>( "Calculate Middle Latitude", json_data.size( ), []( auto const &jstr ) -> float { uint32_t tot = 0; auto result = daw::algorithm::accumulate( iterator_t( jstr ), iterator_t( ), 0.0f, [&tot]( float cur, City &&city ) { ++tot; return cur + city.lat; } ); return result / static_cast<float>( tot ); }, json_data ); std::cout << "mid_lat of all is: " << mid_lat << '\n'; auto mid_lat2 = *daw::bench_n_test_mbs<DAW_NUM_RUNS>( "Calculate Middle Latitude2", json_data.size( ), []( auto const &jstr ) -> float { std::vector<float> lats{ }; daw::algorithm::transform( iterator_t( jstr ), iterator_t( ), daw::back_inserter( lats ), []( auto &&l ) { return l.lat; } ); auto result = daw::algorithm::accumulate( std::cbegin( lats ), std::cend( lats ), 0.0f ); return result / static_cast<float>( lats.size( ) ); }, json_data ); std::cout << "mid_lat2 of all is: " << mid_lat2 << '\n'; } #ifdef DAW_USE_JSON_EXCEPTIONS catch( daw::json::json_exception const &jex ) { std::cerr << "Exception thrown by parser: " << jex.reason( ) << std::endl; exit( 1 ); } #endif
31.90099
80
0.608007
mheyman
4ff347f2aa7e49d2322e4ed15c6d1dc2e623933c
187
cpp
C++
no_of_objects_created.cpp
rvgarg/oops_programs
f9b5e8b884dab27f5b0737f7aa6848fef870f04d
[ "Apache-2.0" ]
null
null
null
no_of_objects_created.cpp
rvgarg/oops_programs
f9b5e8b884dab27f5b0737f7aa6848fef870f04d
[ "Apache-2.0" ]
null
null
null
no_of_objects_created.cpp
rvgarg/oops_programs
f9b5e8b884dab27f5b0737f7aa6848fef870f04d
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; class foo { public: static int count; foo() { count++; } }; int foo::count = 0; int main() { foo a, b, c, d; cout << foo::count; }
13.357143
23
0.566845
rvgarg
4ff46761caa2700eb490f321a7ceabcc1446c9cc
5,503
cpp
C++
Source/CNormalShot.cpp
pbghogehoge/kog
7d45ba8ddc1b01987ccca416dbd7901a23f4412f
[ "MIT" ]
41
2019-02-08T09:10:30.000Z
2022-03-24T15:54:58.000Z
Source/CNormalShot.cpp
pbghogehoge/kog
7d45ba8ddc1b01987ccca416dbd7901a23f4412f
[ "MIT" ]
null
null
null
Source/CNormalShot.cpp
pbghogehoge/kog
7d45ba8ddc1b01987ccca416dbd7901a23f4412f
[ "MIT" ]
4
2019-02-08T09:26:59.000Z
2020-05-07T15:44:34.000Z
/* * CNormalShot.cpp : 自機の通常ショット * */ #include "CNormalShot.h" #include "Gian2001.h" #include "RndCtrl.h" /***** [プライベートな定数] *****/ #define NS_SPEED (12 * 256) // 通常ショットの移動速度 #define NS_MAXSIZE (16 * 256) // 通常ショットの最大サイズ #define NS_HITSIZE ( 8 * 256) // 通常ショットの当たり判定サイズ #define NS_MAX_TIME 24 // 通常ショットの自動連射時間 #define NS_AUTO_TIME 6 // 通常ショットの連射間隔 #define NS_DAMAGE 256 // 通常ショットのダメージ量 // コンストラクタ // CNormalShot::CNormalShot(RECT *rcTargetX256, int *pX, int *pY) { // Y方向の消去座標を確定する // m_YMin = rcTargetX256->top - NS_MAXSIZE; // ポインタを初期化 // m_pX = pX; // 発射元のX座標へのポインタ m_pY = pY; // 発射元のY座標へのポインタ m_Count = 0; // カウンタ m_Type = 0; // 形状 } // デストラクタ // CNormalShot::~CNormalShot() { // 特に何もしませんよ // } // 初期化する // FVOID CNormalShot::Initialize(CCharacterBase *pCharInfo) { // 各変数の初期化を行う // m_dx = pCharInfo->GetNShotDx(); // X座標をどれだけズラすか m_dy = pCharInfo->GetNShotDy(); // Y座標をどれだけズラすか m_Count = 0; // カウンタ // 弾の種類を確定する // switch(pCharInfo->GetCharID()){ case CHARACTER_VIVIT: m_Type = 0; break; // びびっと case CHARACTER_STG1: m_Type = 1; break; // ミリア case CHARACTER_STG2: m_Type = 2; break; // めい&まい case CHARACTER_STG3: m_Type = 3; break; // ゲイツ case CHARACTER_STG4: m_Type = 4; break; // マリー case CHARACTER_STG5: m_Type = 5; break; // エーリッヒ case CHARACTER_MORGAN: m_Type = 6; break; // モーガン case CHARACTER_MUSE: m_Type = 7; break; // ミューズ case CHARACTER_YUKA: m_Type = 8; break; // 幽香 } // リスト内のデータを解放する // DeleteAllData(); } // セットする // FVOID CNormalShot::Set(void) { // カウンタが非ゼロならば、セットできない // if(m_Count) return; // カウンタを初期化する // m_Count = NS_MAX_TIME; } // 1フレームだけ動かす // FVOID CNormalShot::Move(void) { NormalShot *pShot; Iterator it; int YMin; // 自動発射を行う場合 // if(m_Count){ // セットする // if(0 == (m_Count % NS_AUTO_TIME)){ pShot = InsertBack(NSHOT_NORMAL); // 前から挿入 pShot->x = (*m_pX) + m_dx; // 初期X座標 pShot->y = (*m_pY) + m_dy; // 初期Y座標 pShot->count = 0; // カウンタ } // カウンタをデクリメントする // m_Count--; } // 消去座標をローカル変数に移動 // YMin = m_YMin; // 通常動作中の弾 // ThisForEachFront(NSHOT_NORMAL, it){ pShot = it.GetPtr(); // イテレータ to ポインタ pShot->y -= NS_SPEED; // 上に進むのみ // 画面外にでていたら、消去する // if(pShot->y < YMin) ThisDelContinue(it); // カウンタをインクリメント pShot->count++; } // 消去中の弾 // ThisForEachFront(NSHOT_DELETE, it){ pShot = it.GetPtr(); // イテレータ to ポインタ pShot->x += CosL(pShot->d, (NS_SPEED/4)); // X方向の移動 pShot->y += SinL(pShot->d, (NS_SPEED/4)); // Y方向の移動 // 消去のタイミング // if(pShot->count >= 31) ThisDelContinue(it); // カウンタをインクリメント pShot->count++; } } // 描画する // FVOID CNormalShot::Draw(void) { NormalShot *pShot; Iterator it; int x, y, n; int tvx, tvy; int size; DWORD c; D3DVALUE u0, v0, u1, v1; D3DTLVERTEX tlv[NORMALSHOT_MAX * 6], *ptlv; // テクスチャ座標を確定する // tvx = ((m_Type & 7) << 5); tvy = -((m_Type >> 3) << 5); u0 = D3DVAL( 8 + tvx) / D3DVAL(256); // 左 u1 = D3DVAL( 32 + tvx) / D3DVAL(256); // 右 v0 = D3DVAL(224 + tvy) / D3DVAL(256); // 上 v1 = D3DVAL(248 + tvy) / D3DVAL(256); // 下 // レンダリングステート&テクスチャのセット // g_pGrp->SetTexture(TEXTURE_ID_TAMA); g_pGrp->SetRenderStateEx(GRPST_ALPHASTDCK); // 諸変数の初期化 // ptlv = tlv; // 挿入先 c = RGBA_MAKE(255, 255, 255, 235); // 色の指定 // 通常動作中の弾 // ThisForEachFront(NSHOT_NORMAL, it){ pShot = it.GetPtr(); // イテレータ to ポインタ x = (pShot->x) >> 8; // x座標中心 y = (pShot->y) >> 8; // y座標中心 Set2DPointC(ptlv+0, x-12, y-12, u0, v0, c); Set2DPointC(ptlv+5, x-12, y-12, u0, v0, c); Set2DPointC(ptlv+1, x+12, y-12, u1, v0, c); Set2DPointC(ptlv+2, x+12, y+12, u1, v1, c); Set2DPointC(ptlv+3, x+12, y+12, u1, v1, c); Set2DPointC(ptlv+4, x-12, y+12, u0, v1, c); ptlv += 6; } // 消去中の弾 // ThisForEachFront(NSHOT_DELETE, it){ pShot = it.GetPtr(); // イテレータ to ポインタ x = (pShot->x) >> 8; // x座標中心 y = (pShot->y) >> 8; // y座標中心 n = 255 - (pShot->count) * 8; // α値 c = RGBA_MAKE(255, 255, 255, n); // 色の指定 size = 12 - pShot->count/3; Set2DPointC(ptlv+0, x-size, y-size, u0, v0, c); Set2DPointC(ptlv+5, x-size, y-size, u0, v0, c); Set2DPointC(ptlv+1, x+size, y-size, u1, v0, c); Set2DPointC(ptlv+2, x+size, y+size, u1, v1, c); Set2DPointC(ptlv+3, x+size, y+size, u1, v1, c); Set2DPointC(ptlv+4, x-size, y+size, u0, v1, c); ptlv += 6; } n = ptlv - tlv; if(n){ g_pGrp->DrawPrimitive(D3DPT_TRIANGLELIST, tlv, n); } } // 当たり判定 // FDWORD CNormalShot::HitCheck(EnemyData *pEnemy) { Iterator it; NormalShot *pShot; DWORD Damage; DWORD Size; int x, y; // 当たり判定のサイズは、後で変更すること!! // x = pEnemy->x; // 敵のX座標 y = pEnemy->y; // 敵のY座標 Size = NS_HITSIZE + pEnemy->size; // 当たり判定 Damage = 0; // ダメージ総量の初期化 // 通常ショットはヒットした時点で消去状態に移行する // ThisForEachFront(NSHOT_NORMAL, it){ pShot = it.GetPtr(); // ヒットしていたら、その弾に消去エフェクトをかける // if(HitCheckFast(y, (pShot->y), Size) && HitCheckFast(x, (pShot->x), Size)){ Damage += NS_DAMAGE; // ダメージ増加 pShot = MoveFront(it, NSHOT_DELETE); // 先頭に挿入 pShot->count = 0; // カウンタをリセット pShot->d = 128+32 + RndEx() % 64; // 角度をランダムでセット continue; } } // ダメージを返す // return Damage; }
22.279352
63
0.567327
pbghogehoge
4ff76fb9174f86c896be42ba16d1f983877975e2
944
cpp
C++
ds-algo/search/src/search/InsertSearch.cpp
hebostary/Notes
32e0537ba6f2cb257cd2a202ba2504a7cf70a7ed
[ "Unlicense" ]
null
null
null
ds-algo/search/src/search/InsertSearch.cpp
hebostary/Notes
32e0537ba6f2cb257cd2a202ba2504a7cf70a7ed
[ "Unlicense" ]
null
null
null
ds-algo/search/src/search/InsertSearch.cpp
hebostary/Notes
32e0537ba6f2cb257cd2a202ba2504a7cf70a7ed
[ "Unlicense" ]
null
null
null
#include "Search.hpp" #include "../common/common.hpp" int insertsearch(int *a, int n, int key) { cout<<"***********[Begin]Insert Search**********"<<endl; int re = -1; int low, mid, high; low = 0; high = n - 1; int ite = 0; while(low <= high) { cout<<"Search counter: " << ite++ << endl; mid = low + (high - low) * (key - a[low]) / (a[high] - a[low]); if(key == a[mid]) { re = mid; break; } else if (key > a[mid]) { low = mid + 1; } else { high = mid -1; } } if(re == -1) { cout<<"Search failed"<<endl; } cout<<"***********[End]Insert Search**********"<<endl; return re; } void InsertSearchTest() { int length = 10000; int key = 1234; int *a = generateSortedArray(length); int re = insertsearch(a, length, key); cout<<"Search: ["<<key<<" ], found index is: "<<re<<endl; }
24.842105
71
0.456568
hebostary
4ff98e6878ff74331b5ab0e32d3817059bfc6a88
446
cpp
C++
src/main/cpp/cn/edu/SUSTech/YeCanming/Algs/lab11_network_flow/problemA.cpp
2catycm/P_Algorithm_Design_and_Analysis_cpp
d1678d4db6f59a11215a8c790c2852bf9ad852dd
[ "MulanPSL-1.0" ]
null
null
null
src/main/cpp/cn/edu/SUSTech/YeCanming/Algs/lab11_network_flow/problemA.cpp
2catycm/P_Algorithm_Design_and_Analysis_cpp
d1678d4db6f59a11215a8c790c2852bf9ad852dd
[ "MulanPSL-1.0" ]
null
null
null
src/main/cpp/cn/edu/SUSTech/YeCanming/Algs/lab11_network_flow/problemA.cpp
2catycm/P_Algorithm_Design_and_Analysis_cpp
d1678d4db6f59a11215a8c790c2852bf9ad852dd
[ "MulanPSL-1.0" ]
null
null
null
// // Created by 叶璨铭 on 2022/5/20. // #include <iostream> //#include "EdmondsKarpFlowNetwork.h" #include "DinicFlowNetwork.h" int main() { size_t N, M, S, T; std::cin >> N >> M >> S >> T; FlowNetwork<uint64_t> flowNetwork{N, M, S, T}; for (int i = 0; i < M; ++i) { int u, v, c; std::cin>>u>>v>>c; flowNetwork.addEdge(u, v, c); } std::cout<<flowNetwork.getMaximumFlow()<<std::endl; return 0; }
22.3
55
0.547085
2catycm
4ffa2bce1efd580677d71215b09713c5a1e860dc
5,491
hpp
C++
base/coeff_array.hpp
simonpp/2dRidgeletBTE
5d08cbb5c57fc276c7a528f128615d23c37ef6a0
[ "BSD-3-Clause" ]
1
2019-11-08T03:15:56.000Z
2019-11-08T03:15:56.000Z
base/coeff_array.hpp
simonpp/2dRidgeletBTE
5d08cbb5c57fc276c7a528f128615d23c37ef6a0
[ "BSD-3-Clause" ]
null
null
null
base/coeff_array.hpp
simonpp/2dRidgeletBTE
5d08cbb5c57fc276c7a528f128615d23c37ef6a0
[ "BSD-3-Clause" ]
1
2019-11-08T03:15:56.000Z
2019-11-08T03:15:56.000Z
#pragma once #include <Eigen/Dense> #include <type_traits> #include <vector> #ifdef USE_MPI #include <mpi.h> #endif #include "base/exceptions.hpp" #include "my_map.hpp" namespace _local { template <typename T> struct TransposeAdaptor { TransposeAdaptor(const T &t_) : t(t_){/* empty */}; const T &operator()() const { return t; } const T &t; }; } // _local /* * A collection of vectors, each of length `length`. */ template <typename NUMERIC_T = double> class CoeffArray { private: typedef CoeffArray<NUMERIC_T> this_type; public: typedef NUMERIC_T numeric_t; typedef Eigen::Array<NUMERIC_T, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> container_t; typedef Eigen::Array<NUMERIC_T, Eigen::Dynamic, 1, Eigen::ColMajor> vec_storage_t; typedef Eigen::Map<vec_storage_t> view_t; typedef Eigen::Map<const vec_storage_t> cview_t; typedef Map map_t; public: CoeffArray(const Map &map, unsigned int length) : map_(map) , length_(length) , storage_(length, map.lsize()) { /* empty */ } // @{ /// get data asssigned to index k (local index!) view_t get(int k); cview_t get(int k) const; // @} /// the number of coefficients per entry unsigned int length() const; CoeffArray<NUMERIC_T> &operator=(const _local::TransposeAdaptor<this_type> &wrapped_other); const Map &get_map() const; container_t &array(); const container_t &array() const; numeric_t *data(); const numeric_t *data() const; _local::TransposeAdaptor<this_type> transpose() const; template <typename DERIVED> void import_from_full_array(const Eigen::DenseBase<DERIVED> &src); protected: const Map &map_; const unsigned int length_; container_t storage_; }; template <typename NUMERIC_T> unsigned int CoeffArray<NUMERIC_T>::length() const { return length_; } template <typename NUMERIC_T> typename CoeffArray<NUMERIC_T>::view_t CoeffArray<NUMERIC_T>::get(int k) { return view_t(storage_.col(k).data(), length_); } template <typename NUMERIC_T> typename CoeffArray<NUMERIC_T>::cview_t CoeffArray<NUMERIC_T>::get(int k) const { return cview_t(storage_.col(k).data(), length_); } template <typename NUMERIC_T> typename CoeffArray<NUMERIC_T>::container_t & CoeffArray<NUMERIC_T>::array() { return storage_; } template <typename NUMERIC_T> const typename CoeffArray<NUMERIC_T>::container_t & CoeffArray<NUMERIC_T>::array() const { return storage_; } template <typename NUMERIC_T> _local::TransposeAdaptor<typename CoeffArray<NUMERIC_T>::this_type> CoeffArray<NUMERIC_T>::transpose() const { return _local::TransposeAdaptor<this_type>(*this); } template <typename NUMERIC_T> NUMERIC_T * CoeffArray<NUMERIC_T>::data() { return storage_.data(); } template <typename NUMERIC_T> const NUMERIC_T * CoeffArray<NUMERIC_T>::data() const { return storage_.data(); } template <typename NUMERIC_T> const Map & CoeffArray<NUMERIC_T>::get_map() const { return map_; } template <typename NUMERIC_T> CoeffArray<NUMERIC_T> & CoeffArray<NUMERIC_T>::operator=(const _local::TransposeAdaptor<this_type> &wrapped_other) { const auto &other = wrapped_other(); ASSERT(map_.size() == other.length_); ASSERT(length_ == other.map_.size()); static_assert(std::is_same<NUMERIC_T, double>::value); container_t tmp(other.length_, other.map_.size()); tmp = other.storage_.transpose(); int nprocs, pid; MPI_Comm_rank(map_.comm(), &pid); MPI_Comm_size(map_.comm(), &nprocs); // counts and offsets, units are no. of elements std::vector<int> sendcounts(nprocs); std::vector<int> recvcounts(nprocs); std::vector<int> sdispls(nprocs); std::vector<int> rdispls(nprocs); // assemble sendcounts and sdispls int soffset = 0; for (int i = 0; i < nprocs; ++i) { int sendcount = other.map_.lsize() * this->map_.lsize(i); sendcounts[i] = sendcount; sdispls[i] = soffset; soffset += sendcount * sizeof(numeric_t); } std::vector<MPI_Datatype> send_type(nprocs, MPI_DOUBLE); std::vector<MPI_Datatype> recv_type(nprocs); // prepare recv types for (int i = 0; i < nprocs; ++i) { MPI_Type_vector( this->map_.lsize(), other.map_.lsize(i), length_, MPI_DOUBLE, recv_type.data() + i); // MPI_Type_vector(this->map_.lsize(), other.map_.lsize(i), length_, // MPI_DOUBLE, // recv_type.data() + i); // (*) MPI_Type_commit(recv_type.data() + i); } // assemble recvcounts and rdispl for (int i = 0; i < nprocs; ++i) { int recvcount = this->map_.lsize(); // recvcounts[i] = recvcount; // (*) // it does not work with (*)! Why? (also see previous for-loop) recvcounts[i] = 1; rdispls[i] = other.map_.get_begin(i) * sizeof(numeric_t); } // TODO: make wrapper for MPI_Datatype! int err = MPI_Alltoallw(tmp.data(), sendcounts.data(), sdispls.data(), send_type.data(), storage_.data(), recvcounts.data(), rdispls.data(), recv_type.data(), this->map_.comm()); BOOST_ASSERT(err == 0); return *this; } template <typename NUMERIC_T> template <typename DERIVED> void CoeffArray<NUMERIC_T>::import_from_full_array(const Eigen::DenseBase<DERIVED> &src) { static_assert(std::is_same<typename DERIVED::Scalar, NUMERIC_T>::value); BOOST_VERIFY(src.rows() == length_); storage_ = src.middleCols(map_.begin(), map_.lsize()); }
24.734234
95
0.675105
simonpp
4ffac3b42ce4ce07c41cfbfc51af1cfecd1d0cc5
5,156
hpp
C++
host_buffer.hpp
Metalhead33/SharedBuffers
c152004f9e1a337671bf8aefc7b89cb0e6403ce2
[ "Apache-2.0" ]
null
null
null
host_buffer.hpp
Metalhead33/SharedBuffers
c152004f9e1a337671bf8aefc7b89cb0e6403ce2
[ "Apache-2.0" ]
null
null
null
host_buffer.hpp
Metalhead33/SharedBuffers
c152004f9e1a337671bf8aefc7b89cb0e6403ce2
[ "Apache-2.0" ]
null
null
null
#ifndef HOST_BUFFER_HPP #define HOST_BUFFER_HPP #include "abstract_buffer.hpp" #include <vector> #include <array> #include <cstring> #include <initializer_list> #include <iterator> template <typename T> class dynamic_host_buffer : public abstract_buffer<T> { public: typedef abstract_buffer<T> base_buffer; typedef std::initializer_list<T> initializer; typedef std::vector<T> buffType; typedef typename buffType::iterator iterator; typedef typename buffType::reverse_iterator reverse_iterator; typedef typename buffType::const_iterator const_iterator; typedef typename buffType::const_reverse_iterator const_reverse_iterator; private: buffType buff; public: // Implementations of inherited functions size_t size() const { return buff.size(); } void copy_from(const T* source, size_t quantity, bool force_resize=false, size_t to_offset=0) { if(force_resize) buff.resize(to_offset+quantity); memcpy(&buff[to_offset],source,sizeof(T)*std::min(buff.size()-to_offset,quantity)); } void copy_from(const base_buffer& source, size_t quantity, bool force_resize=false, size_t to_offset=0, size_t from_offset=0) { if(force_resize) buff.resize(to_offset+quantity); source.copy_to(&buff[to_offset],std::min(buff.size()-to_offset,quantity),from_offset); } void copy_to(T* output, size_t quantity, size_t offset=0) const { memcpy(output,&buff[offset],sizeof(T)*std::min(quantity,buff.size()-offset)); } // Iterators iterator begin() { return buff.begin(); } iterator end() { return buff.end(); } reverse_iterator rbegin() { return buff.rbegin(); } reverse_iterator rend() { return buff.rend(); } // Const iterators const_iterator begin() const { return buff.begin(); } const_iterator end() const { return buff.end(); } const_reverse_iterator rbegin() const { return buff.rbegin(); } const_reverse_iterator rend() const { return buff.rend(); } // Inherited for std::vector compatibility T& at(size_t offset) { return buff[offset]; } const T& at(size_t offset) const { return buff[offset]; } T& operator[](size_t offset) { return buff[offset]; } const T& operator[](size_t offset) const { return buff[offset]; } T* data() { return buff.data(); } const T* data() const { return buff.data(); } void resize(size_t quantity) { buff.resize(quantity); } // Constructors dynamic_host_buffer() { ; } dynamic_host_buffer(size_t quantity) : buff(quantity) { ; } dynamic_host_buffer(const base_buffer& cpy) : buff(cpy.size()) { cpy.copy_to(buff.data(),cpy.size()); } dynamic_host_buffer(const initializer& initialize) : buff(initialize) { ; } template< class InputIt > dynamic_host_buffer(InputIt first, InputIt last) : buff(first,last) { ; } }; template <typename T, size_t Q> class static_host_buffer : public abstract_buffer<T> { public: typedef abstract_buffer<T> base_buffer; typedef std::initializer_list<T> initializer; typedef std::array<T,Q> buffType; typedef typename buffType::iterator iterator; typedef typename buffType::reverse_iterator reverse_iterator; typedef typename buffType::const_iterator const_iterator; typedef typename buffType::const_reverse_iterator const_reverse_iterator; private: buffType buff; public: // Implementations of inherited functions size_t size() const { return buff.size(); } void copy_from(const T* source, size_t quantity, bool force_resize=false, size_t to_offset=0) { (void)(force_resize); // There is no resizing. Ever. This is static memcpy(&buff[to_offset],source,sizeof(T)*std::min(quantity,Q-to_offset)); } void copy_from(const base_buffer& source, size_t quantity, bool force_resize=false, size_t to_offset=0, size_t from_offset=0) { (void)(force_resize); // There is no resizing. Ever. This is static source.copy_to(&buff[to_offset],std::min(quantity,Q-to_offset),from_offset); } void copy_to(T* output, size_t quantity, size_t offset=0) const { memcpy(output,&buff[offset],sizeof(T)*std::min(quantity,buff.size()-offset)); } // Iterators iterator begin() { return buff.begin(); } iterator end() { return buff.end(); } reverse_iterator rbegin() { return buff.rbegin(); } reverse_iterator rend() { return buff.rend(); } // Const iterators const_iterator begin() const { return buff.begin(); } const_iterator end() const { return buff.end(); } const_reverse_iterator rbegin() const { return buff.rbegin(); } const_reverse_iterator rend() const { return buff.rend(); } // Inherited for std::array compatibility T& at(size_t offset) { return buff[offset]; } const T& at(size_t offset) const { return buff[offset]; } T& operator[](size_t offset) { return buff[offset]; } const T& operator[](size_t offset) const { return buff[offset]; } T* data() { return buff.data(); } const T* data() const { return buff.data(); } // Constructors static_host_buffer() { ; } static_host_buffer(const base_buffer& cpy) { cpy.copy_to(buff.data(),std::min(buff.size(),cpy.size())); } static_host_buffer(const initializer& initialize) { size_t added = 0; for(auto it = std::begin(initialize);added < Q && it != std::end(initialize);++added) { buff[added] = *it; } } }; #endif // HOST_BUFFER_HPP
34.145695
126
0.730411
Metalhead33
4ffb956b7d2774d75925ce73973e209c5d04f581
1,011
hpp
C++
api/includes/header/HeaderNormalizer.hpp
SaltTeam/ZiaAPI
fe8592cdfce0d05c09eeb82e42cd70a60e0427c3
[ "Unlicense" ]
1
2017-12-20T16:30:07.000Z
2017-12-20T16:30:07.000Z
api/includes/header/HeaderNormalizer.hpp
SaltTeam/ZiaAPI
fe8592cdfce0d05c09eeb82e42cd70a60e0427c3
[ "Unlicense" ]
11
2017-12-11T13:04:39.000Z
2018-02-13T09:11:15.000Z
api/includes/header/HeaderNormalizer.hpp
SaltTeam/ZiaAPI
fe8592cdfce0d05c09eeb82e42cd70a60e0427c3
[ "Unlicense" ]
null
null
null
/** * Zia Httpd Server API * * @authors SaltTeam * @date 10/11/2017 * @package Zia */ #pragma once #include <string> #include "Header.hpp" /** * @namespace Zia */ namespace Zia { namespace HeaderNormalizer { /** * Normalization Type for your header name. You should never have to use it. * * @enum HeaderNormalizationType */ enum HeaderNormalizationType : short { NONE = 0x0000, TRIM = 0x0001, DELIMITERS = 0x0010, CASE = 0x0100, CANONICAL = 0x1000, ALL = 0x1111 }; /** * Normalize the header with the given normalization type. * By default ALL is selected. * * @param key A header name * @param normalizationType The normalization to apply to the header name */ void normalize(std::string &key, HeaderNormalizationType normalizationType = HeaderNormalizationType::ALL); } }
21.0625
115
0.562809
SaltTeam
4ffb9e0b256dbcd110e861a58220f167dfca63fc
6,224
hpp
C++
Game/Xerces/src/xercesc/dom/DOMAttr.hpp
hackerlank/SourceCode
b702c9e0a9ca5d86933f3c827abb02a18ffc9a59
[ "MIT" ]
4
2021-07-31T13:56:01.000Z
2021-11-13T02:55:10.000Z
Game/Xerces/src/xercesc/dom/DOMAttr.hpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
null
null
null
Game/Xerces/src/xercesc/dom/DOMAttr.hpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
7
2021-08-31T14:34:23.000Z
2022-01-19T08:25:58.000Z
#ifndef DOMAttr_HEADER_GUARD_ #define DOMAttr_HEADER_GUARD_ /* * Copyright 2001-2002,2004 The Apache Software Foundation. * * 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. */ /* * $Id: DOMAttr.hpp 176280 2005-01-07 15:32:34Z amassari $ */ #include <xercesc/util/XercesDefs.hpp> #include <xercesc/dom/DOMNode.hpp> XERCES_CPP_NAMESPACE_BEGIN class DOMElement; class DOMTypeInfo; /** * The <code>DOMAttr</code> class refers to an attribute of an XML element. * * Typically the allowable values for the * attribute are defined in a documenttype definition. * <p><code>DOMAttr</code> objects inherit the <code>DOMNode</code> interface, but * since attributes are not actually child nodes of the elements they are associated with, the * DOM does not consider them part of the document tree. Thus, the * <code>DOMNode</code> attributes <code>parentNode</code>, * <code>previousSibling</code>, and <code>nextSibling</code> have a null * value for <code>DOMAttr</code> objects. The DOM takes the view that * attributes are properties of elements rather than having a separate * identity from the elements they are associated with; this should make it * more efficient to implement such features as default attributes associated * with all elements of a given type. Furthermore, attribute nodes * may not be immediate children of a <code>DOMDocumentFragment</code>. However, * they can be associated with <code>DOMElement</code> nodes contained within a * <code>DOMDocumentFragment</code>. In short, users of the DOM * need to be aware that <code>DOMAttr</code> nodes have some things in common * with other objects inheriting the <code>DOMNode</code> interface, but they * also are quite distinct. * * @since DOM Level 1 */ class CDOM_EXPORT DOMAttr: public DOMNode { protected: // ----------------------------------------------------------------------- // Hidden constructors // ----------------------------------------------------------------------- /** @name Hidden constructors */ //@{ DOMAttr() {} DOMAttr(const DOMAttr &other) : DOMNode(other) {} //@} private: // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- /** @name Unimplemented operators */ //@{ DOMAttr & operator = (const DOMAttr &); //@} public: // ----------------------------------------------------------------------- // All constructors are hidden, just the destructor is available // ----------------------------------------------------------------------- /** @name Destructor */ //@{ /** * Destructor * */ virtual ~DOMAttr() {}; //@} // ----------------------------------------------------------------------- // Virtual DOMAttr interface // ----------------------------------------------------------------------- /** @name Functions introduced in DOM Level 1 */ //@{ // ----------------------------------------------------------------------- // Getter methods // ----------------------------------------------------------------------- /** * Returns the name of this attribute. * @since DOM Level 1 */ virtual const XMLCh * getName() const = 0; /** * * Returns true if the attribute received its value explicitly in the * XML document, or if a value was assigned programatically with * the setValue function. Returns false if the attribute value * came from the default value declared in the document's DTD. * @since DOM Level 1 */ virtual bool getSpecified() const = 0; /** * Returns the value of the attribute. * * The value of the attribute is returned as a string. * Character and general entity references are replaced with their values. * @since DOM Level 1 */ virtual const XMLCh * getValue() const = 0; // ----------------------------------------------------------------------- // Setter methods // ----------------------------------------------------------------------- /** * Sets the value of the attribute. A text node with the unparsed contents * of the string will be created. * * @param value The value of the DOM attribute to be set * @since DOM Level 1 */ virtual void setValue(const XMLCh *value) = 0; //@} /** @name Functions introduced in DOM Level 2. */ //@{ /** * The <code>DOMElement</code> node this attribute is attached to or * <code>null</code> if this attribute is not in use. * * @since DOM Level 2 */ virtual DOMElement *getOwnerElement() const = 0; //@} /** @name Functions introduced in DOM Level 3. */ //@{ /** * Returns whether this attribute is known to be of type ID or not. * When it is and its value is unique, the ownerElement of this attribute * can be retrieved using getElementById on Document. * * <p><b>"Experimental - subject to change"</b></p> * * @return <code>bool</code> stating if this <code>DOMAttr</code> is an ID * @since DOM level 3 */ virtual bool isId() const = 0; /** * Returns the type information associated with this attribute. * * <p><b>"Experimental - subject to change"</b></p> * * @return the <code>DOMTypeInfo</code> associated with this attribute * @since DOM level 3 */ virtual const DOMTypeInfo * getTypeInfo() const = 0; //@} }; XERCES_CPP_NAMESPACE_END #endif
34.38674
94
0.558162
hackerlank
4ffc0b4031e408357f95de33dcff38badaf422ac
205
cpp
C++
acm/shuoj/contest/20160409/5.cpp
xiaohuihuigh/cpp
c28bdb79ecb86f44a92971ac259910546dba29a7
[ "MIT" ]
17
2016-01-01T12:57:25.000Z
2022-02-06T09:55:12.000Z
acm/shuoj/contest/20160409/5.cpp
xiaohuihuigh/cpp
c28bdb79ecb86f44a92971ac259910546dba29a7
[ "MIT" ]
null
null
null
acm/shuoj/contest/20160409/5.cpp
xiaohuihuigh/cpp
c28bdb79ecb86f44a92971ac259910546dba29a7
[ "MIT" ]
8
2018-12-27T01:31:49.000Z
2022-02-06T09:55:12.000Z
#include<bits/stdc++.h> using namespace std; int a[100]; int main(){ int t; cin>>t; while(t--){ int n; cin>>n; int ans = 0; while(n){ if(n&1)ans++; n>>=1; } cout<<(1<<ans)<<endl; } }
11.388889
23
0.502439
xiaohuihuigh
4ffda9d2d20ab8a27fd0285c13371c3be2883be6
5,780
cpp
C++
Source/SystemQOR/MSWindows/WinQL/System/Security/WinQLImpersonation.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
9
2016-05-27T01:00:39.000Z
2021-04-01T08:54:46.000Z
Source/SystemQOR/MSWindows/WinQL/System/Security/WinQLImpersonation.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
1
2016-03-03T22:54:08.000Z
2016-03-03T22:54:08.000Z
Source/SystemQOR/MSWindows/WinQL/System/Security/WinQLImpersonation.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
4
2016-05-27T01:00:43.000Z
2018-08-19T08:47:49.000Z
//WinQLImpersonation.cpp // Copyright Querysoft Limited 2013 // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #include "WinQL/Application/ErrorSystem/WinQLError.h" #include "WinQL/System/Security/WinQLImpersonation.h" #include "WinQL/Application/Threading/WinQLThread.h" #include "WinQAPI/AdvAPI32.h" using namespace nsWinQAPI; //-------------------------------------------------------------------------------- namespace nsWin32 { __QOR_IMPLEMENT_OCLASS_LUID( CImpersonationSession ); //-------------------------------------------------------------------------------- CImpersonationSession::CImpersonationSession() : m_AdvAPI32Library( CAdvAPI32::Instance() ) { _WINQ_FCONTEXT( "CImpersonationSession::CImpersonationSession" ); m_bInSession = false; } //-------------------------------------------------------------------------------- CImpersonationSession::~CImpersonationSession() { _WINQ_FCONTEXT( "CImpersonationSession::~CImpersonationSession" ); if( m_bInSession ) { __QOR_PROTECT { m_AdvAPI32Library.RevertToSelf(); }__QOR_ENDPROTECT } } //--Self Impersonation Session---------------------------------------------------- __QOR_IMPLEMENT_OCLASS_LUID( CSelfImpersonationSession ); //-------------------------------------------------------------------------------- CSelfImpersonationSession::CSelfImpersonationSession( nsWin32::SECURITY_IMPERSONATION_LEVEL ImpersonationLevel ) : CImpersonationSession() { _WINQ_FCONTEXT( "CSelfImpersonationSession::CSelfImpersonationSession" ); __QOR_PROTECT { m_bInSession = m_AdvAPI32Library.ImpersonateSelf( static_cast< ::SECURITY_IMPERSONATION_LEVEL >( ImpersonationLevel ) ) ? true : false; }__QOR_ENDPROTECT } //-------------------------------------------------------------------------------- CSelfImpersonationSession::~CSelfImpersonationSession() { _WINQ_FCONTEXT( "CSelfImpersonationSession::~CSelfImpersonationSession" ); } //--Named Pipe Client Impersonation Session--------------------------------------- __QOR_IMPLEMENT_OCLASS_LUID( CNamedPipeClientImpersonationSession ); //-------------------------------------------------------------------------------- CNamedPipeClientImpersonationSession::CNamedPipeClientImpersonationSession( void* hNamedPipe ) : CImpersonationSession() { _WINQ_FCONTEXT( "CNamedPipeClientImpersonationSession::CNamedPipeClientImpersonationSession" ); __QOR_PROTECT { m_bInSession = m_AdvAPI32Library.ImpersonateNamedPipeClient( hNamedPipe ) ? true : false; }__QOR_ENDPROTECT } //-------------------------------------------------------------------------------- CNamedPipeClientImpersonationSession::~CNamedPipeClientImpersonationSession() { _WINQ_FCONTEXT( "CNamedPipeClientImpersonationSession::~CNamedPipeClientImpersonationSession" ); } //--Logged On User Impersonation Session--------------------------------------- __QOR_IMPLEMENT_OCLASS_LUID( CLoggedOnUserImpersonationSession ); //-------------------------------------------------------------------------------- CLoggedOnUserImpersonationSession::CLoggedOnUserImpersonationSession( CHandle& hToken ) : CImpersonationSession() { _WINQ_FCONTEXT( "CLoggedOnUserImpersonationSession::CLoggedOnUserImpersonationSession" ); __QOR_PROTECT { m_bInSession = m_AdvAPI32Library.ImpersonateLoggedOnUser( hToken.Use() ) ? true : false; }__QOR_ENDPROTECT } //-------------------------------------------------------------------------------- CLoggedOnUserImpersonationSession::~CLoggedOnUserImpersonationSession() { _WINQ_FCONTEXT( "CLoggedOnUserImpersonationSession::~CLoggedOnUserImpersonationSession" ); } //--Anonymous Impersonation Session--------------------------------------- __QOR_IMPLEMENT_OCLASS_LUID( CAnonymousImpersonationSession ); //-------------------------------------------------------------------------------- CAnonymousImpersonationSession::CAnonymousImpersonationSession( CThread& Thread ) : CImpersonationSession() { _WINQ_FCONTEXT( "CAnonymousImpersonationSession::CAnonymousImpersonationSession" ); __QOR_PROTECT { m_bInSession = m_AdvAPI32Library.ImpersonateAnonymousToken( Thread.Handle()->Use() ) ? true : false; }__QOR_ENDPROTECT } //-------------------------------------------------------------------------------- CAnonymousImpersonationSession::~CAnonymousImpersonationSession() { _WINQ_FCONTEXT( "CAnonymousImpersonationSession::~CAnonymousImpersonationSession" ); } }//nsWin32
40.138889
139
0.646886
mfaithfull
4ffee2b3a369b100f68f89d7f96fb913762669c9
8,630
cpp
C++
src/fn_miscs.cpp
brindhavenkatesan92/libsass
1b372e4e23fab20bd3db4fe05efa65adcba6a2cb
[ "MIT" ]
null
null
null
src/fn_miscs.cpp
brindhavenkatesan92/libsass
1b372e4e23fab20bd3db4fe05efa65adcba6a2cb
[ "MIT" ]
null
null
null
src/fn_miscs.cpp
brindhavenkatesan92/libsass
1b372e4e23fab20bd3db4fe05efa65adcba6a2cb
[ "MIT" ]
null
null
null
#include "ast.hpp" #include "expand.hpp" #include "fn_utils.hpp" #include "fn_miscs.hpp" namespace Sass { namespace Functions { // features static std::set<std::string> features { "global-variable-shadowing", "extend-selector-pseudoclass", "at-error", "units-level-3", "custom-property" }; ////////////////////////// // INTROSPECTION FUNCTIONS ////////////////////////// Signature type_of_sig = "type-of($value)"; BUILT_IN(type_of) { Expression_Ptr v = ARG("$value", Expression); return SASS_MEMORY_NEW(String_Quoted, pstate, v->type()); } Signature variable_exists_sig = "variable-exists($name)"; BUILT_IN(variable_exists) { std::string s = Util::normalize_underscores(unquote(ARG("$name", String_Constant)->value())); if(d_env.has("$"+s)) { return SASS_MEMORY_NEW(Boolean, pstate, true); } else { return SASS_MEMORY_NEW(Boolean, pstate, false); } } Signature global_variable_exists_sig = "global-variable-exists($name)"; BUILT_IN(global_variable_exists) { std::string s = Util::normalize_underscores(unquote(ARG("$name", String_Constant)->value())); if(d_env.has_global("$"+s)) { return SASS_MEMORY_NEW(Boolean, pstate, true); } else { return SASS_MEMORY_NEW(Boolean, pstate, false); } } Signature function_exists_sig = "function-exists($name)"; BUILT_IN(function_exists) { String_Constant_Ptr ss = Cast<String_Constant>(env["$name"]); if (!ss) { error("$name: " + (env["$name"]->to_string()) + " is not a string for `function-exists'", pstate, traces); } std::string name = Util::normalize_underscores(unquote(ss->value())); if(d_env.has_global(name+"[f]")) { return SASS_MEMORY_NEW(Boolean, pstate, true); } else { return SASS_MEMORY_NEW(Boolean, pstate, false); } } Signature mixin_exists_sig = "mixin-exists($name)"; BUILT_IN(mixin_exists) { std::string s = Util::normalize_underscores(unquote(ARG("$name", String_Constant)->value())); if(d_env.has_global(s+"[m]")) { return SASS_MEMORY_NEW(Boolean, pstate, true); } else { return SASS_MEMORY_NEW(Boolean, pstate, false); } } Signature feature_exists_sig = "feature-exists($name)"; BUILT_IN(feature_exists) { std::string s = unquote(ARG("$name", String_Constant)->value()); if(features.find(s) == features.end()) { return SASS_MEMORY_NEW(Boolean, pstate, false); } else { return SASS_MEMORY_NEW(Boolean, pstate, true); } } Signature call_sig = "call($name, $args...)"; BUILT_IN(call) { std::string name; Function_Ptr ff = Cast<Function>(env["$name"]); String_Constant_Ptr ss = Cast<String_Constant>(env["$name"]); if (ss) { name = Util::normalize_underscores(unquote(ss->value())); std::cerr << "DEPRECATION WARNING: "; std::cerr << "Passing a string to call() is deprecated and will be illegal" << std::endl; std::cerr << "in Sass 4.0. Use call(get-function(" + quote(name) + ")) instead." << std::endl; std::cerr << std::endl; } else if (ff) { name = ff->name(); } List_Obj arglist = SASS_MEMORY_COPY(ARG("$args", List)); Arguments_Obj args = SASS_MEMORY_NEW(Arguments, pstate); // std::string full_name(name + "[f]"); // Definition_Ptr def = d_env.has(full_name) ? Cast<Definition>((d_env)[full_name]) : 0; // Parameters_Ptr params = def ? def->parameters() : 0; // size_t param_size = params ? params->length() : 0; for (size_t i = 0, L = arglist->length(); i < L; ++i) { Expression_Obj expr = arglist->value_at_index(i); // if (params && params->has_rest_parameter()) { // Parameter_Obj p = param_size > i ? (*params)[i] : 0; // List_Ptr list = Cast<List>(expr); // if (list && p && !p->is_rest_parameter()) expr = (*list)[0]; // } if (arglist->is_arglist()) { Expression_Obj obj = arglist->at(i); Argument_Obj arg = (Argument_Ptr) obj.ptr(); // XXX args->append(SASS_MEMORY_NEW(Argument, pstate, expr, arg ? arg->name() : "", arg ? arg->is_rest_argument() : false, arg ? arg->is_keyword_argument() : false)); } else { args->append(SASS_MEMORY_NEW(Argument, pstate, expr)); } } Function_Call_Obj func = SASS_MEMORY_NEW(Function_Call, pstate, name, args); Expand expand(ctx, &d_env, &selector_stack); func->via_call(true); // calc invoke is allowed if (ff) func->func(ff); return Cast<PreValue>(func->perform(&expand.eval)); } //////////////////// // BOOLEAN FUNCTIONS //////////////////// Signature not_sig = "not($value)"; BUILT_IN(sass_not) { return SASS_MEMORY_NEW(Boolean, pstate, ARG("$value", Expression)->is_false()); } Signature if_sig = "if($condition, $if-true, $if-false)"; // BUILT_IN(sass_if) // { return ARG("$condition", Expression)->is_false() ? ARG("$if-false", Expression) : ARG("$if-true", Expression); } BUILT_IN(sass_if) { Expand expand(ctx, &d_env, &selector_stack); Expression_Obj cond = ARG("$condition", Expression)->perform(&expand.eval); bool is_true = !cond->is_false(); Expression_Obj res = ARG(is_true ? "$if-true" : "$if-false", Expression); Value_Obj qwe = Cast<Value>(res->perform(&expand.eval)); // res = res->perform(&expand.eval.val_eval); qwe->set_delayed(false); // clone? return qwe.detach(); } ////////////////////////// // MISCELLANEOUS FUNCTIONS ////////////////////////// // value.check_deprecated_interp if value.is_a?(Sass::Script::Value::String) // unquoted_string(value.to_sass) Signature inspect_sig = "inspect($value)"; BUILT_IN(inspect) { Expression_Ptr v = ARG("$value", Expression); if (v->concrete_type() == Expression::NULL_VAL) { return SASS_MEMORY_NEW(String_Quoted, pstate, "null"); } else if (v->concrete_type() == Expression::BOOLEAN && v->is_false()) { return SASS_MEMORY_NEW(String_Quoted, pstate, "false"); } else if (v->concrete_type() == Expression::STRING) { return Cast<String>(v); } else { // ToDo: fix to_sass for nested parentheses Sass_Output_Style old_style; old_style = ctx.c_options.output_style; ctx.c_options.output_style = TO_SASS; Emitter emitter(ctx.c_options); Inspect i(emitter); i.in_declaration = false; v->perform(&i); ctx.c_options.output_style = old_style; return SASS_MEMORY_NEW(String_Quoted, pstate, i.get_buffer()); } // return v; } Signature content_exists_sig = "content-exists()"; BUILT_IN(content_exists) { if (!d_env.has_global("is_in_mixin")) { error("Cannot call content-exists() except within a mixin.", pstate, traces); } return SASS_MEMORY_NEW(Boolean, pstate, d_env.has_lexical("@content[m]")); } Signature get_function_sig = "get-function($name, $css: false)"; BUILT_IN(get_function) { String_Constant_Ptr ss = Cast<String_Constant>(env["$name"]); if (!ss) { error("$name: " + (env["$name"]->to_string()) + " is not a string for `get-function'", pstate, traces); } std::string name = Util::normalize_underscores(unquote(ss->value())); std::string full_name = name + "[f]"; Boolean_Obj css = ARG("$css", Boolean); if (!css->is_false()) { Definition_Ptr def = SASS_MEMORY_NEW(Definition, pstate, name, SASS_MEMORY_NEW(Parameters, pstate), SASS_MEMORY_NEW(Block, pstate, 0, false), Definition::FUNCTION); return SASS_MEMORY_NEW(Function, pstate, def, true); } if (!d_env.has_global(full_name)) { error("Function not found: " + name, pstate, traces); } Definition_Ptr def = Cast<Definition>(d_env[full_name]); return SASS_MEMORY_NEW(Function, pstate, def, false); } } }
34.52
121
0.569525
brindhavenkatesan92
4fff47e2fd682f57073d9dbfbebe846d18d64c02
9,548
cpp
C++
libraries/model/src/model/Stage.cpp
DaveDubUK/hifi
1ceed98ca2f43f9accef2a174a16ab4228093144
[ "Apache-2.0" ]
null
null
null
libraries/model/src/model/Stage.cpp
DaveDubUK/hifi
1ceed98ca2f43f9accef2a174a16ab4228093144
[ "Apache-2.0" ]
null
null
null
libraries/model/src/model/Stage.cpp
DaveDubUK/hifi
1ceed98ca2f43f9accef2a174a16ab4228093144
[ "Apache-2.0" ]
null
null
null
// // Stage.cpp // libraries/model/src/model // // Created by Sam Gateau on 2/24/2015. // Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "Stage.h" #include <glm/gtx/transform.hpp> #include <math.h> #include <qcompilerdetection.h> using namespace model; void EarthSunModel::updateAll() const { updateWorldToSurface(); updateSurfaceToEye(); updateSun(); } Mat4d EarthSunModel::evalWorldToGeoLocationMat(double longitude, double latitude, double absAltitude, double scale) { // Longitude is along Z axis but - from east to west Mat4d rotLon = glm::rotate(glm::radians(longitude), Vec3d(0.0, 0.0, 1.0)); // latitude is along X axis + from south to north Mat4d rotLat = glm::rotate(-glm::radians(latitude), Vec3d(1.0, 0.0, 0.0)); // translation is movin to the earth surface + altiture at the radius along Y axis Mat4d surfaceT = glm::translate(Vec3d(0.0, -absAltitude, 0.0)); // Mat4d worldScale = glm::scale(Vec3d(scale)); Mat4d worldToGeoLocMat = surfaceT * rotLat * rotLon; return worldToGeoLocMat; } void EarthSunModel::updateWorldToSurface() const { // Check if the final position is too close to the earth center ? float absAltitude = _earthRadius + _altitude; if ( absAltitude < 0.01f) { absAltitude = 0.01f; } // Final world to local Frame _worldToSurfaceMat = evalWorldToGeoLocationMat(_longitude, _latitude, absAltitude, _scale); // and the inverse _surfaceToWorldMat = glm::inverse(_worldToSurfaceMat); _surfacePos = Vec3d(_surfaceToWorldMat * Vec4d(0.0, 0.0, 0.0, 1.0)); } void EarthSunModel::updateSurfaceToEye() const { _surfaceToEyeMat = glm::inverse(_eyeToSurfaceMat); _worldToEyeMat = _surfaceToEyeMat * _worldToSurfaceMat; _eyeToWorldMat = _surfaceToWorldMat * _eyeToSurfaceMat; _eyePos = Vec3d(_eyeToWorldMat * Vec4d(0.0, 0.0, 0.0, 1.0) ); _eyeDir = Vec3d(_eyeToWorldMat * Vec4d(0.0, 0.0, -1.0, 0.0) ); } void EarthSunModel::updateSun() const { // Longitude is along Y axis but - from east to west Mat4d rotSunLon; Mat4d rotSun = evalWorldToGeoLocationMat(_sunLongitude, _sunLatitude, _earthRadius, _scale); rotSun = glm::inverse(rotSun); _sunDir = Vec3d(rotSun * Vec4d(0.0, 1.0, 0.0, 0.0)); // sun direction is looking up toward Y axis at the specified sun lat, long Vec3d lssd = Vec3d(_worldToSurfaceMat * Vec4d(_sunDir.x, _sunDir.y, _sunDir.z, 0.0)); // apply surface rotation offset glm::dquat dSurfOrient(_surfaceOrientation); lssd = glm::rotate(dSurfOrient, lssd); _surfaceSunDir = glm::normalize(Vec3(lssd.x, lssd.y, lssd.z)); } void EarthSunModel::setSurfaceOrientation(const Quat& orientation) { _surfaceOrientation = orientation; invalidate(); } double moduloRange(double val, double minVal, double maxVal) { double range = maxVal - minVal; double rval = (val - minVal) / range; rval = rval - floor(rval); return rval * range + minVal; } const float MAX_LONGITUDE = 180.0f; const float MAX_LATITUDE = 90.0f; float validateLongitude(float lon) { return moduloRange(lon, -MAX_LONGITUDE, MAX_LONGITUDE); } float validateLatitude(float lat) { return moduloRange(lat, -MAX_LATITUDE, MAX_LATITUDE); } float validateAltitude(float altitude) { const float MIN_ALTITUDE = -1000.0f; const float MAX_ALTITUDE = 100000.0f; return std::min(std::max(altitude, MIN_ALTITUDE), MAX_ALTITUDE); } void EarthSunModel::setLatitude(float lat) { _latitude = validateLatitude(lat); invalidate(); } void EarthSunModel::setLongitude(float lon) { _longitude = validateLongitude(lon); invalidate(); } void EarthSunModel::setAltitude(float altitude) { _altitude = validateAltitude(altitude); invalidate(); } void EarthSunModel::setSunLatitude(float lat) { _sunLatitude = validateLatitude(lat); invalidate(); } void EarthSunModel::setSunLongitude(float lon) { _sunLongitude = validateLongitude(lon); invalidate(); } Atmosphere::Atmosphere() { // only if created from nothing shall we create the Buffer to store the properties Data data; _dataBuffer = gpu::BufferView(new gpu::Buffer(sizeof(Data), (const gpu::Byte*) &data)); setScatteringWavelength(_scatteringWavelength); setRayleighScattering(_rayleighScattering); setInnerOuterRadiuses(getInnerRadius(), getOuterRadius()); } void Atmosphere::setScatteringWavelength(Vec3 wavelength) { _scatteringWavelength = wavelength; Data& data = editData(); data._invWaveLength = Vec4(1.0f / powf(wavelength.x, 4.0f), 1.0f / powf(wavelength.y, 4.0f), 1.0f / powf(wavelength.z, 4.0f), 0.0f); } void Atmosphere::setRayleighScattering(float scattering) { _rayleighScattering = scattering; updateScattering(); } void Atmosphere::setMieScattering(float scattering) { _mieScattering = scattering; updateScattering(); } void Atmosphere::setSunBrightness(float brightness) { _sunBrightness = brightness; updateScattering(); } void Atmosphere::updateScattering() { Data& data = editData(); data._scatterings.x = getRayleighScattering() * getSunBrightness(); data._scatterings.y = getMieScattering() * getSunBrightness(); data._scatterings.z = getRayleighScattering() * 4.0f * glm::pi<float>(); data._scatterings.w = getMieScattering() * 4.0f * glm::pi<float>(); } void Atmosphere::setInnerOuterRadiuses(float inner, float outer) { Data& data = editData(); data._radiuses.x = inner; data._radiuses.y = outer; data._scales.x = 1.0f / (outer - inner); data._scales.z = data._scales.x / data._scales.y; } const int NUM_DAYS_PER_YEAR = 365; const float NUM_HOURS_PER_DAY = 24.0f; const float NUM_HOURS_PER_HALF_DAY = NUM_HOURS_PER_DAY * 0.5f; SunSkyStage::SunSkyStage() : _sunLight(new Light()), _skybox(new Skybox()) { _sunLight->setType(Light::SUN); setSunIntensity(1.0f); setSunAmbientIntensity(0.5f); setSunColor(Vec3(1.0f, 1.0f, 1.0f)); // Default origin location is a special place in the world... setOriginLocation(122.407f, 37.777f, 0.03f); // Noun setDayTime(12.0f); // Begining of march setYearTime(60.0f); _skybox.reset(new Skybox()); _skybox->setColor(Color(1.0f, 0.0f, 0.0f)); } SunSkyStage::~SunSkyStage() { } void SunSkyStage::setDayTime(float hour) { _dayTime = moduloRange(hour, 0.f, NUM_HOURS_PER_DAY); invalidate(); } void SunSkyStage::setYearTime(unsigned int day) { _yearTime = day % NUM_DAYS_PER_YEAR; invalidate(); } void SunSkyStage::setOriginOrientation(const Quat& orientation) { _earthSunModel.setSurfaceOrientation(orientation); invalidate(); } void SunSkyStage::setOriginLocation(float longitude, float latitude, float altitude) { _earthSunModel.setLongitude(longitude); _earthSunModel.setLatitude(latitude); _earthSunModel.setAltitude(altitude); invalidate(); } void SunSkyStage::setSunModelEnable(bool isEnabled) { _sunModelEnable = isEnabled; invalidate(); } void SunSkyStage::setSunColor(const Vec3& color) { _sunLight->setColor(color); } void SunSkyStage::setSunIntensity(float intensity) { _sunLight->setIntensity(intensity); } void SunSkyStage::setSunAmbientIntensity(float intensity) { _sunLight->setAmbientIntensity(intensity); } void SunSkyStage::setSunDirection(const Vec3& direction) { if (!isSunModelEnabled()) { _sunLight->setDirection(direction); } } // THe sun declinaison calculus is taken from https://en.wikipedia.org/wiki/Position_of_the_Sun double evalSunDeclinaison(double dayNumber) { return -(23.0 + 44.0/60.0)*cos(glm::radians((360.0/365.0)*(dayNumber + 10.0))); } void SunSkyStage::updateGraphicsObject() const { // Always update the sunLongitude based on the current dayTime and the current origin // The day time is supposed to be local at the origin float signedNormalizedDayTime = (_dayTime - NUM_HOURS_PER_HALF_DAY) / NUM_HOURS_PER_HALF_DAY; float sunLongitude = _earthSunModel.getLongitude() + (MAX_LONGITUDE * signedNormalizedDayTime); _earthSunModel.setSunLongitude(sunLongitude); // And update the sunLAtitude as the declinaison depending of the time of the year _earthSunModel.setSunLatitude(evalSunDeclinaison(_yearTime)); if (isSunModelEnabled()) { Vec3d sunLightDir = -_earthSunModel.getSurfaceSunDir(); _sunLight->setDirection(Vec3(sunLightDir.x, sunLightDir.y, sunLightDir.z)); double originAlt = _earthSunModel.getAltitude(); _sunLight->setPosition(Vec3(0.0f, originAlt, 0.0f)); } // Background switch (getBackgroundMode()) { case NO_BACKGROUND: { break; } case SKY_DOME: { break; } case SKY_BOX: { break; } case NUM_BACKGROUND_MODES: Q_UNREACHABLE(); }; } void SunSkyStage::setBackgroundMode(BackgroundMode mode) { _backgroundMode = mode; invalidate(); } void SunSkyStage::setSkybox(const SkyboxPointer& skybox) { _skybox = skybox; invalidate(); }
31.202614
137
0.681295
DaveDubUK
8b006b13212ae5f01646607126ba7397e691e26a
6,997
cpp
C++
lectures/23-GraphsII/code/Kruskal/src/kruskal.cpp
tofergregg/cs106X-website-spring-2017
1c1f4bab672248a77bdb881e818dee49b48c0070
[ "MIT" ]
2
2018-02-21T07:10:58.000Z
2019-07-26T03:54:43.000Z
lectures/23-GraphsII/code/Kruskal/src/kruskal.cpp
tofergregg/cs106X-website-spring-2017
1c1f4bab672248a77bdb881e818dee49b48c0070
[ "MIT" ]
null
null
null
lectures/23-GraphsII/code/Kruskal/src/kruskal.cpp
tofergregg/cs106X-website-spring-2017
1c1f4bab672248a77bdb881e818dee49b48c0070
[ "MIT" ]
6
2017-01-04T03:17:03.000Z
2020-11-16T06:28:30.000Z
#include <iostream> #include "console.h" #include "basicgraph.h" #include "simpio.h" #include "set.h" #include "priorityqueue.h" #include "gwindow.h" #include "gobjects.h" #include "random.h" #include "map.h" #include <cmath> using namespace std; const bool GRID_GRAPH = true; void kruskal(BasicGraph &graph, BasicGraph &mst); void drawGraph(GWindow &gw, BasicGraph &graph, string title); void adjustWindows(GWindow &gw1,GWindow &gw2); void populateGraph(BasicGraph &graph,bool randomVerts = false); int main() { // create two windows and stack them horizontally GWindow gwOrig,gwMst; // adjust the windows to make them look nice adjustWindows(gwOrig,gwMst); BasicGraph graph; string response = getLine("Do you want a random graph? (y/n)"); if (response.size() > 0 && response[0] == 'y') { populateGraph(graph,true); } else { populateGraph(graph,false); } drawGraph(gwOrig,graph,"Original"); BasicGraph mst; kruskal(graph,mst); drawGraph(gwMst, mst, "Minimum Spanning Tree"); return 0; } void kruskal(BasicGraph& graph, BasicGraph &mst) { // first, copy the graph and remove the edges // This is so we can populate it later with the mst edges mst = graph; mst.clearEdges(); // put each vertex into a 'cluster', initially containing only itself Map<Vertex*, Set<Vertex*>* > clusters; Set<Vertex*> allVertices = graph.getVertexSet(); Vector<Set<Vertex*>* > allSets; // for freeing later for (Vertex* v : allVertices) { Set<Vertex*>* set = new Set<Vertex*>(); set->add(v); clusters[v] = set; allSets.add(set); } // put all edges into a priority queue, sorted by weight PriorityQueue<Edge*> pq; Set<Edge*> allEdges = graph.getEdgeSet(); for (Edge* edge : allEdges) { pq.enqueue(edge, edge->cost); } // repeatedly pull min-weight edge out of PQ and add it to MST if its // endpoints are not already connected Set<Edge*> mstEdges; while (!pq.isEmpty()) { Edge* e = pq.dequeue(); Set<Vertex*>* set1 = clusters[e->start]; Set<Vertex*>* set2 = clusters[e->finish]; if (set1 != set2) { mstEdges.add(e); // merge the two sets set1->addAll(*set2); for (Vertex* v : *set1) { Set<Vertex*>* setv = clusters[v]; if (setv != set1) { clusters[v] = set1; } } } } for (Set<Vertex*>* set : allSets) { delete set; } // populate the graph with the edges // We can't add the edge pointers directly // because that would cause trouble freeing later for (Edge *edge : mstEdges) { mst.addEdge(edge->start->name,edge->end->name,edge->cost,false); } } void drawGraph(GWindow &gw, BasicGraph &graph,string title) { // always start with the same random seed // so we always get the same drawing for the same // vertices if (!GRID_GRAPH) { setRandomSeed(1234); } // place the title there gw.setTitle(title); Map<Vertex*,GPoint> vertexLocations; int vertCount = 0; // for the grid for (Vertex *vert : graph.getVertexSet()) { int x,y; if (!GRID_GRAPH) { // randomly locate vertex on graph x = randomInteger(5,gw.getWidth()-6); y = randomInteger(5,gw.getHeight()-6); } else { // put in a staggerd grid const int NUMCOLS = 3; int widthApart = gw.getWidth() / (NUMCOLS + 1) - 10; // make a bit smaller for screen size int heightApart = gw.getHeight() / 6; // could fix this x = (widthApart + ((vertCount % NUMCOLS) + (vertCount / NUMCOLS)) * widthApart); y = ((vertCount / NUMCOLS + 1 + vertCount) * heightApart); } GPoint p(x,y); vertexLocations.add(vert,p); // place a dot there gw.fillOval(x,y,10,10); // place a label GLabel *gl = new GLabel(vert->name); gl->setFont("SansSerif-28"); gw.add(gl,p.getX(),p.getY()); vertCount++; } Set<Set<string>>seenAlready; for (Edge *edge : graph.getEdgeSet()) { Set<string>sortedEdgeSet; sortedEdgeSet.add(edge->start->name); sortedEdgeSet.add(edge->end->name); if (!seenAlready.contains(sortedEdgeSet)) { GPoint startPoint = vertexLocations[edge->start]; GPoint endPoint = vertexLocations[edge->end]; gw.drawLine(startPoint,endPoint); // find the 1/3 point of the line (midpoint would have many // overlapping points for the grid) int avgX = abs((startPoint.getX()*2 + endPoint.getX())/3.0); int avgY = abs((startPoint.getY()*2 + endPoint.getY())/3.0); GLabel *gl = new GLabel(doubleToString(edge->cost)); gl->setFont("SansSerif-28"); gw.add(gl,avgX,avgY); // add an unambiguous edge to seenAlready // so we don't put same undirected edge in twice seenAlready.add(sortedEdgeSet); } } } void adjustWindows(GWindow &gw1,GWindow &gw2) { gw1.setSize(600,700); gw2.setSize(600,700); gw1.repaint(); gw2.setLocation(gw1.getLocation().getX()+gw1.getCanvasWidth(), gw1.getLocation().getY()); } void populateGraph(BasicGraph &graph, bool randomVerts) { if (!randomVerts) { // add some vertices and edges for (int i=0; i < 5; i++) { Vertex *v = new Vertex("" + charToString(i+'a')); graph.addVertex(v); } // add some edges with weights graph.addEdge("a","b",9,false); graph.addEdge("a","c",75,false); graph.addEdge("b","c",95,false); graph.addEdge("b","d",19,false); graph.addEdge("b","e",42,false); graph.addEdge("c","d",51,false); graph.addEdge("d","e",31,false); } else { // add 10 vertices for (int i=0; i < 10; i++) { Vertex *v = new Vertex("" + charToString(i+'a')); graph.addVertex(v); } // for each vertex, add up to three random edges Vector<Vertex *> allVerts; for (Vertex *v : graph.getVertexSet()) { allVerts.add(v); } for (Vertex *v : graph.getVertexSet()) { Set<Vertex *>usedAlready; usedAlready.add(v); // don't use yourself for (int i=0;i<3;i++) { int vertIndex = randomInteger(0,graph.size()-1); if (usedAlready.contains(allVerts[vertIndex])) { continue; // ignore } Vertex *second = allVerts[vertIndex]; // get a random cost int cost = randomInteger(1,100); // create an edge graph.addEdge(v,second,cost); usedAlready.add(second); } } } }
31.949772
102
0.566671
tofergregg
8b0183892fd7736ee1e8e337e08ff31d6b5d799c
421
cpp
C++
leet_code/arrays/specialArr.cpp
sahilduhan/codeforces
a8042d52c12806e026fd7027e35e97ed8b4eeed6
[ "MIT" ]
null
null
null
leet_code/arrays/specialArr.cpp
sahilduhan/codeforces
a8042d52c12806e026fd7027e35e97ed8b4eeed6
[ "MIT" ]
null
null
null
leet_code/arrays/specialArr.cpp
sahilduhan/codeforces
a8042d52c12806e026fd7027e35e97ed8b4eeed6
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; class Solution { public: int specialArray(vector<int>& nums) { int n = nums.size(); while (n > 0){ int count = 0; for (int i = 0; i < nums.size(); i++){ if (nums[i] >= n) count++; } if (count == n) return n; n--; } return -1; } }; int main(){ return 0; }
20.047619
50
0.418052
sahilduhan
8b025e8f2089450547be4357391b502e3c43fbde
543
cpp
C++
cli/util/to_http.cpp
Bytecube-Packages/Bytecube
ae4b09d593a8f2487798283d7d1f25c76c1da4a3
[ "Apache-2.0" ]
5
2021-08-04T21:05:41.000Z
2021-09-18T12:55:40.000Z
cli/util/to_http.cpp
Bytecube-Packages/Bytecube
ae4b09d593a8f2487798283d7d1f25c76c1da4a3
[ "Apache-2.0" ]
1
2021-08-12T17:44:35.000Z
2021-08-12T17:44:35.000Z
cli/util/to_http.cpp
Bytecube-Packages/Bytecube
ae4b09d593a8f2487798283d7d1f25c76c1da4a3
[ "Apache-2.0" ]
null
null
null
#include <sstream> #include <string> #include <map> #include "url_encode.cpp" using namespace std; namespace Util{ string to_http(map<string, string> object, bool encode = true) { stringstream ss; for (map<string, string>::iterator it = object.begin(); it != object.end(); ++it) { string seperator = it == object.begin() ? "?" : "&"; string key = it->first; string value = it->second; if (encode) value = url_encode(value); ss << seperator << key << "=" << value; } return ss.str(); } }
21.72
87
0.593002
Bytecube-Packages
8b063f989bc6486c5caec353714fb03a74039411
730
cpp
C++
src/db/db_drc.cpp
liulixinkerry/ripple
330522a61bcf1cf290c100ce4686ed62dcdc5cab
[ "Unlicense" ]
7
2021-01-25T04:28:38.000Z
2021-11-20T04:14:14.000Z
src/db/db_drc.cpp
Xingquan-Li/ripple
330522a61bcf1cf290c100ce4686ed62dcdc5cab
[ "Unlicense" ]
3
2021-02-25T08:13:41.000Z
2022-02-25T16:37:16.000Z
src/db/db_drc.cpp
Xingquan-Li/ripple
330522a61bcf1cf290c100ce4686ed62dcdc5cab
[ "Unlicense" ]
8
2021-02-27T13:52:25.000Z
2021-11-15T08:01:02.000Z
#include "db.h" using namespace db; #include "../ut/utils.h" /***** EdgeTypes *****/ int EdgeTypes::getEdgeType(const string& name) const { unsigned numTypes = types.size(); for (unsigned i = 0; i != numTypes; ++i) { if (types[i] == name) { return i; } } return -1; } int EdgeTypes::getEdgeSpace(const int edge1, const int edge2) const { if (!distTable.size()) { return 0; } #ifdef DEBUG if (edge1 < 0 || edge1 >= (int)types.size()) { printlog(LOG_ERROR, "invalid edge ID: %d", edge1); } if (edge2 < 0 || edge2 >= (int)types.size()) { printlog(LOG_ERROR, "invalid edge ID: %d", edge2); } #endif return distTable[edge1][edge2]; }
20.857143
67
0.556164
liulixinkerry
8b072ba900eb2e86b13bcd019acffe41f316d053
2,097
cpp
C++
src/sleek/node/billboard/sprite.cpp
Phirxian/sleek-engine
741d55c8daad67ddf631e8b8fbdced59402d7bda
[ "BSD-2-Clause" ]
null
null
null
src/sleek/node/billboard/sprite.cpp
Phirxian/sleek-engine
741d55c8daad67ddf631e8b8fbdced59402d7bda
[ "BSD-2-Clause" ]
null
null
null
src/sleek/node/billboard/sprite.cpp
Phirxian/sleek-engine
741d55c8daad67ddf631e8b8fbdced59402d7bda
[ "BSD-2-Clause" ]
null
null
null
#include "../scene.h" #include "sprite.h" namespace sleek { namespace scene3d { namespace billboard { Sprite::Sprite(Scene *smgr) noexcept : Billboard(smgr) { mat->Texture.push_back(nullptr); timespec = 100; current = 0; } Sprite::Sprite(Scene *smgr, std::vector<driver::texture*> i) noexcept : Billboard(smgr) { mat->Texture.push_back(nullptr); timespec = 100; current = 0; } /** ************************* **/ void Sprite::setTimer(const u32 i) noexcept { timespec = i; } void Sprite::setArray(std::vector<driver::texture*> i) noexcept { anim = i; current = 0; } void Sprite::setTexture(driver::texture *i) noexcept { anim.push_back(i); } /** ************************* **/ std::vector<driver::texture*> Sprite::getArray() const noexcept { return anim; } driver::texture *Sprite::getTexture() const noexcept { return anim[current]; } u32 Sprite::getTimer() const noexcept { return timespec; } /** ************************* **/ void Sprite::render() noexcept { if(!enabled) return; time_stamp.update(); if(time_stamp.getTimeMsec() > timespec) { current += time_stamp.getTimeMsec()/timespec; // sync ( ex: time_stamp = 500, timespec = 100; 500/100 = 5; frame += 5 so frame skipped = 5 mat->Texture[0] = anim[current % anim.size()]->getIdentifier().get(); time_stamp.reset(); } Billboard::render(); } } } }
26.884615
158
0.406295
Phirxian
8b07cd1eb7ecf75585e8dc7650332eee0fc25e42
1,464
cpp
C++
examples/misc/context.cpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
5
2015-09-15T16:24:14.000Z
2021-08-12T11:05:55.000Z
examples/misc/context.cpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
null
null
null
examples/misc/context.cpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
3
2016-11-17T04:38:38.000Z
2021-04-10T17:23:52.000Z
// Copyright (c) 2005-2007 Andre Merzky <andre@merzky.net> // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE file or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <saga/saga.hpp> #define COUNT 100 void dump_context (saga::context c) { std::vector <std::string> attribs = c.list_attributes (); std::cout << " ------------------------------ " << std::endl; for ( unsigned int i = 0; i < attribs.size (); i++ ) { std::cout << " " << attribs[i] << " \t: "; if ( c.attribute_is_vector (attribs[i]) ) { std::vector <std::string> vals = c.get_vector_attribute (attribs[i]); for ( unsigned int j = 0; j < vals.size (); j++ ) { std::cout << vals[j] << " "; } } else { std::string val = c.get_attribute (attribs[i]); std::cout << val << " "; } std::cout << std::endl; } std::cout << " ------------------------------ " << std::endl; } /////////////////////////////////////////////////////////////////////////////// int main (int argc, char* argv[]) { std::string type = "ssh"; if ( argc > 1 ) { type = argv[1]; } try { saga::context c (type); // c.set_attribute ("UserID", "root"); dump_context (c); saga::session s; s.add_context (c); dump_context (c); } catch ( const saga::exception & e ) { std::cerr << e.what () << std::endl; } return 0; }
19.783784
79
0.485656
saga-project
8b08fd30de6621fa4a7d48a27d38f5d26ac1f1ab
10,610
cpp
C++
src/fasc/fascDGP.cpp
rlinxy/fcore
652288940bd27ecbad69c0366bba20ad0f7515b6
[ "MIT" ]
1
2021-04-29T16:38:46.000Z
2021-04-29T16:38:46.000Z
src/fasc/fascDGP.cpp
rlinxy/fcore
652288940bd27ecbad69c0366bba20ad0f7515b6
[ "MIT" ]
null
null
null
src/fasc/fascDGP.cpp
rlinxy/fcore
652288940bd27ecbad69c0366bba20ad0f7515b6
[ "MIT" ]
1
2019-10-22T08:16:36.000Z
2019-10-22T08:16:36.000Z
#include <fasc/fascDGP.h> void FascDGP::initDataEIP158() { std::vector<uint32_t> tempData = {dev::eth::EIP158Schedule.tierStepGas[0], dev::eth::EIP158Schedule.tierStepGas[1], dev::eth::EIP158Schedule.tierStepGas[2], dev::eth::EIP158Schedule.tierStepGas[3], dev::eth::EIP158Schedule.tierStepGas[4], dev::eth::EIP158Schedule.tierStepGas[5], dev::eth::EIP158Schedule.tierStepGas[6], dev::eth::EIP158Schedule.tierStepGas[7], dev::eth::EIP158Schedule.expGas, dev::eth::EIP158Schedule.expByteGas, dev::eth::EIP158Schedule.sha3Gas, dev::eth::EIP158Schedule.sha3WordGas, dev::eth::EIP158Schedule.sloadGas, dev::eth::EIP158Schedule.sstoreSetGas, dev::eth::EIP158Schedule.sstoreResetGas, dev::eth::EIP158Schedule.sstoreRefundGas, dev::eth::EIP158Schedule.jumpdestGas, dev::eth::EIP158Schedule.logGas, dev::eth::EIP158Schedule.logDataGas, dev::eth::EIP158Schedule.logTopicGas, dev::eth::EIP158Schedule.createGas, dev::eth::EIP158Schedule.callGas, dev::eth::EIP158Schedule.callStipend, dev::eth::EIP158Schedule.callValueTransferGas, dev::eth::EIP158Schedule.callNewAccountGas, dev::eth::EIP158Schedule.suicideRefundGas, dev::eth::EIP158Schedule.memoryGas, dev::eth::EIP158Schedule.quadCoeffDiv, dev::eth::EIP158Schedule.createDataGas, dev::eth::EIP158Schedule.txGas, dev::eth::EIP158Schedule.txCreateGas, dev::eth::EIP158Schedule.txDataZeroGas, dev::eth::EIP158Schedule.txDataNonZeroGas, dev::eth::EIP158Schedule.copyGas, dev::eth::EIP158Schedule.extcodesizeGas, dev::eth::EIP158Schedule.extcodecopyGas, dev::eth::EIP158Schedule.balanceGas, dev::eth::EIP158Schedule.suicideGas, dev::eth::EIP158Schedule.maxCodeSize }; dataEIP158Schedule = tempData; } bool FascDGP::checkLimitSchedule(const std::vector<uint32_t>& defaultData, const std::vector<uint32_t>& checkData) { if(defaultData.size() == 39 && checkData.size() == 39) { for(size_t i = 0; i < defaultData.size(); i++) { uint32_t max = defaultData[i] * 1000 > 0 ? defaultData[i] * 1000 : 1 * 1000; uint32_t min = defaultData[i] / 100 > 0 ? defaultData[i] / 100 : 1; if(checkData[i] > max || checkData[i] < min) { return false; } } return true; } return false; } dev::eth::EVMSchedule FascDGP::getGasSchedule(unsigned int blockHeight) { clear(); dev::eth::EVMSchedule schedule = dev::eth::EIP158Schedule; if(initStorages(GasScheduleDGP, blockHeight, ParseHex("26fadbe2"))) { schedule = createEVMSchedule(); } return schedule; } uint64_t FascDGP::getUint64FromDGP(unsigned int blockHeight, const dev::Address& contract, std::vector<unsigned char> data) { uint64_t value = 0; if(initStorages(contract, blockHeight, data)) { if(!dgpevm) { parseStorageOneUint64(value); } else { parseDataOneUint64(value); } } return value; } uint32_t FascDGP::getBlockSize(unsigned int blockHeight) { clear(); uint32_t result = DEFAULT_BLOCK_SIZE_DGP; uint32_t blockSize = getUint64FromDGP(blockHeight, BlockSizeDGP, ParseHex("92ac3c62")); if(blockSize <= MAX_BLOCK_SIZE_DGP && blockSize >= MIN_BLOCK_SIZE_DGP) { result = blockSize; } return result; } uint64_t FascDGP::getMinGasPrice(unsigned int blockHeight) { clear(); uint64_t result = DEFAULT_MIN_GAS_PRICE_DGP; uint64_t minGasPrice = getUint64FromDGP(blockHeight, GasPriceDGP, ParseHex("3fb58819")); if(minGasPrice <= MAX_MIN_GAS_PRICE_DGP && minGasPrice >= MIN_MIN_GAS_PRICE_DGP) { result = minGasPrice; } return result; } uint64_t FascDGP::getBlockGasLimit(unsigned int blockHeight) { clear(); uint64_t result = DEFAULT_BLOCK_GAS_LIMIT_DGP; auto phex = ParseHex("2cc8377d"); uint64_t blockGasLimit = getUint64FromDGP(blockHeight, BlockGasLimitDGP, phex); if(blockGasLimit <= MAX_BLOCK_GAS_LIMIT_DGP && blockGasLimit >= MIN_BLOCK_GAS_LIMIT_DGP) { result = blockGasLimit; } return result; } bool FascDGP::initStorages(const dev::Address& addr, unsigned int blockHeight, std::vector<unsigned char> data) { initStorageDGP(addr); createParamsInstance(); dev::Address address = getAddressForBlock(blockHeight); if(address != dev::Address()) { if(!dgpevm) { initStorageTemplate(address); } else { initDataTemplate(address, data); } return true; } return false; } void FascDGP::initStorageDGP(const dev::Address& addr) { storageDGP = state->storage(addr); } void FascDGP::initStorageTemplate(const dev::Address& addr) { storageTemplate = state->storage(addr); } void FascDGP::initDataTemplate(const dev::Address& addr, std::vector<unsigned char>& data) { dataTemplate = CallContract(addr, data)[0].execRes.output; } void FascDGP::createParamsInstance() { dev::h256 paramsInstanceHash = sha3(dev::h256("0000000000000000000000000000000000000000000000000000000000000000")); if(storageDGP.count(paramsInstanceHash)) { dev::u256 paramsInstanceSize = storageDGP.find(paramsInstanceHash)->second.second; for(size_t i = 0; i < size_t(paramsInstanceSize); i++) { std::pair<unsigned int, dev::Address> params; params.first = dev::toUint64(storageDGP.find(sha3(paramsInstanceHash))->second.second); ++paramsInstanceHash; params.second = dev::right160(dev::h256(storageDGP.find(sha3(paramsInstanceHash))->second.second)); ++paramsInstanceHash; paramsInstance.push_back(params); } } } dev::Address FascDGP::getAddressForBlock(unsigned int blockHeight) { for(auto i = paramsInstance.rbegin(); i != paramsInstance.rend(); i++) { if(i->first <= blockHeight) return i->second; } return dev::Address(); } static inline bool sortPairs(const std::pair<dev::u256, dev::u256>& a, const std::pair<dev::u256, dev::u256>& b) { return a.first < b.first; } void FascDGP::parseStorageScheduleContract(std::vector<uint32_t>& uint32Values) { std::vector<std::pair<dev::u256, dev::u256>> data; for(size_t i = 0; i < 5; i++) { dev::h256 gasScheduleHash = sha3(dev::h256(dev::u256(i))); if(storageTemplate.count(gasScheduleHash)) { dev::u256 key = storageTemplate.find(gasScheduleHash)->second.first; dev::u256 value = storageTemplate.find(gasScheduleHash)->second.second; data.push_back(std::make_pair(key, value)); } } std::sort(data.begin(), data.end(), sortPairs); for(std::pair<dev::u256, dev::u256> d : data) { dev::u256 value = d.second; for(size_t i = 0; i < 4; i++) { uint64_t uint64Value = dev::toUint64(value); value = value >> 64; uint32Values.push_back(uint32_t(uint64Value)); uint64Value = uint64Value >> 32; uint32Values.push_back(uint32_t(uint64Value)); } } } void FascDGP::parseDataScheduleContract(std::vector<uint32_t>& uint32Values) { size_t size = dataTemplate.size() / 32; for(size_t i = 0; i < size; i++) { std::vector<unsigned char> value = std::vector<unsigned char>(dataTemplate.begin() + (i * 32), dataTemplate.begin() + ((i+1) * 32)); dev::h256 valueTemp(value); uint32Values.push_back(dev::toUint64(dev::u256(valueTemp))); } } void FascDGP::parseStorageOneUint64(uint64_t& value) { dev::h256 blockSizeHash = sha3(dev::h256(dev::u256(0))); if(storageTemplate.count(blockSizeHash)) { value = dev::toUint64(storageTemplate.find(blockSizeHash)->second.second); } } void FascDGP::parseDataOneUint64(uint64_t& value) { if(dataTemplate.size() == 32) { value = dev::toUint64(dev::u256(dev::h256(dataTemplate))); } } dev::eth::EVMSchedule FascDGP::createEVMSchedule() { dev::eth::EVMSchedule schedule = dev::eth::EIP158Schedule; std::vector<uint32_t> uint32Values; if(!dgpevm) { parseStorageScheduleContract(uint32Values); } else { parseDataScheduleContract(uint32Values); } if(!checkLimitSchedule(dataEIP158Schedule, uint32Values)) return schedule; if(uint32Values.size() >= 39) { schedule.tierStepGas = {{ uint32Values[0], uint32Values[1], uint32Values[2], uint32Values[3], uint32Values[4], uint32Values[5], uint32Values[6], uint32Values[7] } }; schedule.expGas = uint32Values[8]; schedule.expByteGas = uint32Values[9]; schedule.sha3Gas = uint32Values[10]; schedule.sha3WordGas = uint32Values[11]; schedule.sloadGas = uint32Values[12]; schedule.sstoreSetGas = uint32Values[13]; schedule.sstoreResetGas = uint32Values[14]; schedule.sstoreRefundGas = uint32Values[15]; schedule.jumpdestGas = uint32Values[16]; schedule.logGas = uint32Values[17]; schedule.logDataGas = uint32Values[18]; schedule.logTopicGas = uint32Values[19]; schedule.createGas = uint32Values[20]; schedule.callGas = uint32Values[21]; schedule.callStipend = uint32Values[22]; schedule.callValueTransferGas = uint32Values[23]; schedule.callNewAccountGas = uint32Values[24]; schedule.suicideRefundGas = uint32Values[25]; schedule.memoryGas = uint32Values[26]; schedule.quadCoeffDiv = uint32Values[27]; schedule.createDataGas = uint32Values[28]; schedule.txGas = uint32Values[29]; schedule.txCreateGas = uint32Values[30]; schedule.txDataZeroGas = uint32Values[31]; schedule.txDataNonZeroGas = uint32Values[32]; schedule.copyGas = uint32Values[33]; schedule.extcodesizeGas = uint32Values[34]; schedule.extcodecopyGas = uint32Values[35]; schedule.balanceGas = uint32Values[36]; schedule.suicideGas = uint32Values[37]; schedule.maxCodeSize = uint32Values[38]; } return schedule; } void FascDGP::clear() { templateContract = dev::Address(); storageDGP.clear(); storageTemplate.clear(); paramsInstance.clear(); }
42.610442
160
0.645806
rlinxy
8b09bbac7453dc478a96ed96d6bd9e8adfe8b1d4
2,649
cpp
C++
samples/vision/sample_vision_featureMatching.cpp
no33fewi/saiga
edc873e34cd59eaf8c4a12dc7f909b4dd5e5fb68
[ "MIT" ]
114
2017-08-13T22:37:32.000Z
2022-03-25T12:28:39.000Z
samples/vision/sample_vision_featureMatching.cpp
no33fewi/saiga
edc873e34cd59eaf8c4a12dc7f909b4dd5e5fb68
[ "MIT" ]
7
2019-10-14T18:19:11.000Z
2021-06-11T09:41:52.000Z
samples/vision/sample_vision_featureMatching.cpp
no33fewi/saiga
edc873e34cd59eaf8c4a12dc7f909b4dd5e5fb68
[ "MIT" ]
18
2017-08-14T01:22:05.000Z
2022-03-12T12:35:07.000Z
/** * Copyright (c) 2021 Darius Rückert * Licensed under the MIT License. * See LICENSE file for more information. */ #include "saiga/core/framework/framework.h" #include "saiga/core/image/image.h" #include "saiga/core/math/Eigen_Compile_Checker.h" #include "saiga/core/math/random.h" #include "saiga/core/time/all.h" #include "saiga/core/util/BinaryFile.h" #include "saiga/core/util/fileChecker.h" #include "saiga/vision/VisionIncludes.h" #include "saiga/vision/reconstruction/EightPoint.h" #include "saiga/vision/features/Features.h" #include <numeric> using namespace Saiga; using FeatureDescriptor = DescriptorORB; std::vector<DescriptorORB> randomDescriptors(int n) { std::vector<DescriptorORB> des(n); for (auto& d : des) { for (auto& dd : d) dd = Random::urand64(); } return des; } int main(int, char**) { initSaigaSampleNoWindow(); Saiga::EigenHelper::checkEigenCompabitilty<15357>(); Saiga::Random::setSeed(45786045); std::vector<KeyPoint<double>> keys1, keys2; std::vector<FeatureDescriptor> des1, des2; if (0) { des1 = randomDescriptors(1500); des2 = randomDescriptors(1000); } else { auto p1 = SearchPathes::data("vision/0.features"); auto p2 = SearchPathes::data("vision/10.features"); SAIGA_ASSERT(!p1.empty() && !p2.empty()); { BinaryFile bf(p1, std::ios_base::in); bf >> keys1 >> des1; } { BinaryFile bf(p2, std::ios_base::in); bf >> keys2 >> des2; } // BinaryFile bf(tmpDir + "/" + to_string(image.frameId) + ".features", std::ios_base::in); // SAIGA_ASSERT(bf.strm.is_open()); // bf >> features.mvKeys >> features.descriptors; } int n = des1.size(); int m = des2.size(); std::vector<int> d_matchMatrix(n * m); ImageView<int> matchMatrix(n, m, d_matchMatrix.data()); std::cout << "Bruteforce matching " << n << "x" << m << " ORB Descriptors..." << std::endl; { SAIGA_BLOCK_TIMER("Matching"); for (auto i : Range(0, n)) { for (auto j : Range(0, m)) { matchMatrix(i, j) = distance(des1[i], des2[j]); } } } auto sum = std::accumulate(d_matchMatrix.begin(), d_matchMatrix.end(), 0); std::cout << "distance sum: " << sum << " avg: " << double(sum) / (n * m) << std::endl; BruteForceMatcher<DescriptorORB> matcher; matcher.match(des1.begin(), n, des2.begin(), m); matcher.matchKnn2(des1, des2); matcher.filterMatches(50, 0.6); return 0; }
27.309278
106
0.593431
no33fewi
8b09caea1fc582d9ef0c66af01b76041e91f4937
1,646
cpp
C++
designer/NumericTablePlugin.cpp
ZgblKylin/NumericTable
778dacc7aa56d246086b8b32c8f79eddb3cb5ac4
[ "MIT" ]
3
2020-02-14T06:46:08.000Z
2020-08-08T16:13:17.000Z
designer/NumericTablePlugin.cpp
ZgblKylin/NumericTable
778dacc7aa56d246086b8b32c8f79eddb3cb5ac4
[ "MIT" ]
null
null
null
designer/NumericTablePlugin.cpp
ZgblKylin/NumericTable
778dacc7aa56d246086b8b32c8f79eddb3cb5ac4
[ "MIT" ]
null
null
null
#include "NumericTablePlugin.h" #include <NumericTable> #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(NumericTablePlugin, NumericTablePlugin) #endif // QT_VERSION < 0x050000 NumericTablePlugin::NumericTablePlugin(QObject* parent) : QObject(parent) { widgets.append(new NumericTablePluginInterface(this)); } QList<QDesignerCustomWidgetInterface*> NumericTablePlugin::customWidgets() const { return widgets; } NumericTablePluginInterface::NumericTablePluginInterface(QObject* parent) : QObject(parent) { } QString NumericTablePluginInterface::name() const { return QStringLiteral("NumericTable"); } QString NumericTablePluginInterface::group() const { return QString(); } QString NumericTablePluginInterface::toolTip() const { return QStringLiteral("Table view used to display huge amount of numeric values"); } QString NumericTablePluginInterface::whatsThis() const { return QStringLiteral("Table view used to display huge amount of numeric values"); } QString NumericTablePluginInterface::includeFile() const { return QStringLiteral("NumericTable"); } QIcon NumericTablePluginInterface::icon() const { return QIcon(); } bool NumericTablePluginInterface::isContainer() const { return false; } QWidget* NumericTablePluginInterface::createWidget(QWidget* parent) { return new NumericTable(parent); } bool NumericTablePluginInterface::isInitialized() const { return initialized; } void NumericTablePluginInterface::initialize(QDesignerFormEditorInterface* /*core*/) { if (initialized) { return; } // Add extension registrations, etc. here initialized = true; }
20.835443
86
0.763062
ZgblKylin
8b0c212cb883e4546f00622149ebe2f2796dd603
2,880
cpp
C++
src/013_roman_to_integer.cpp
llife09/leetcode
f5bd6bc7819628b9921441d8362f62123ab881b7
[ "MIT" ]
1
2019-09-01T22:54:39.000Z
2019-09-01T22:54:39.000Z
src/013_roman_to_integer.cpp
llife09/leetcode
f5bd6bc7819628b9921441d8362f62123ab881b7
[ "MIT" ]
6
2019-07-19T07:16:42.000Z
2019-07-26T08:21:31.000Z
src/013_roman_to_integer.cpp
llife09/leetcode
f5bd6bc7819628b9921441d8362f62123ab881b7
[ "MIT" ]
null
null
null
/* Roman to Integer URL: https://leetcode.com/problems/roman-to-integer Tags: ['math', 'string'] ___ Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example, two is written as `II` in Roman numeral, just two one's added together. Twelve is written as, `XII`, which is simply `X` \+ `II`. The number twenty seven is written as `XXVII`, which is `XX` \+ `V` \+ `II`. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as `IX`. There are six instances where subtraction is used: * `I` can be placed before `V` (5) and `X` (10) to make 4 and 9. * `X` can be placed before `L` (50) and `C` (100) to make 40 and 90. * `C` can be placed before `D` (500) and `M` (1000) to make 400 and 900. Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. Example 1: Input: "III" Output: 3 Example 2: Input: "IV" Output: 4 Example 3: Input: "IX" Output: 9 Example 4: Input: "LVIII" Output: 58 Explanation: L = 50, V= 5, III = 3. Example 5: Input: "MCMXCIV" Output: 1994 Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. */ #include "test.h" using std::string; using std::vector; namespace roman_to_integer { inline namespace v1 { class Solution { public: int romanToInt(string s) { static const vector<string> arrC = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; static const vector<int> arrI = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; int result = 0; string::size_type head = 0; for (int i = 0; i < arrC.size() && head < s.size();) { if (s.compare(head, arrC[i].size(), arrC[i]) == 0) { result += arrI[i]; head += arrC[i].size(); } else { i++; } } return result; } }; } // namespace v1 TEST_CASE("Roman to Integer") { TEST_SOLUTION(romanToInt, v1) { CHECK(romanToInt("III") == 3); CHECK(romanToInt("IV") == 4); CHECK(romanToInt("IX") == 9); CHECK(romanToInt("LVIII") == 58); CHECK(romanToInt("MCMXCIV") == 1994); BENCHMARK("") { return romanToInt("MCMXCIV"); }; }; } } // namespace roman_to_integer
25.486726
78
0.532986
llife09
8b0c60ec0a49eef971777209e55f663f3614e9bc
4,171
cpp
C++
export/release/windows/obj/src/__ASSET__OPENFL__flixel_fonts_monsterrat_ttf.cpp
bobisdabbing/Vs-The-United-Lands-stable
0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5
[ "MIT" ]
null
null
null
export/release/windows/obj/src/__ASSET__OPENFL__flixel_fonts_monsterrat_ttf.cpp
bobisdabbing/Vs-The-United-Lands-stable
0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5
[ "MIT" ]
null
null
null
export/release/windows/obj/src/__ASSET__OPENFL__flixel_fonts_monsterrat_ttf.cpp
bobisdabbing/Vs-The-United-Lands-stable
0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5
[ "MIT" ]
null
null
null
// Generated by Haxe 4.1.5 #include <hxcpp.h> #ifndef INCLUDED___ASSET__OPENFL__flixel_fonts_monsterrat_ttf #include <__ASSET__OPENFL__flixel_fonts_monsterrat_ttf.h> #endif #ifndef INCLUDED___ASSET__flixel_fonts_monsterrat_ttf #include <__ASSET__flixel_fonts_monsterrat_ttf.h> #endif #ifndef INCLUDED_lime_text_Font #include <lime/text/Font.h> #endif #ifndef INCLUDED_openfl_text_Font #include <openfl/text/Font.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_aa3eaf4dd720a73e_726_new,"__ASSET__OPENFL__flixel_fonts_monsterrat_ttf","new",0x4d419742,"__ASSET__OPENFL__flixel_fonts_monsterrat_ttf.new","ManifestResources.hx",726,0xf77aa668) void __ASSET__OPENFL__flixel_fonts_monsterrat_ttf_obj::__construct(){ HX_GC_STACKFRAME(&_hx_pos_aa3eaf4dd720a73e_726_new) HXDLIN( 726) this->_hx___fromLimeFont( ::__ASSET__flixel_fonts_monsterrat_ttf_obj::__alloc( HX_CTX )); HXDLIN( 726) super::__construct(null()); } Dynamic __ASSET__OPENFL__flixel_fonts_monsterrat_ttf_obj::__CreateEmpty() { return new __ASSET__OPENFL__flixel_fonts_monsterrat_ttf_obj; } void *__ASSET__OPENFL__flixel_fonts_monsterrat_ttf_obj::_hx_vtable = 0; Dynamic __ASSET__OPENFL__flixel_fonts_monsterrat_ttf_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< __ASSET__OPENFL__flixel_fonts_monsterrat_ttf_obj > _hx_result = new __ASSET__OPENFL__flixel_fonts_monsterrat_ttf_obj(); _hx_result->__construct(); return _hx_result; } bool __ASSET__OPENFL__flixel_fonts_monsterrat_ttf_obj::_hx_isInstanceOf(int inClassId) { if (inClassId<=(int)0x40cee131) { if (inClassId<=(int)0x12d0aa2c) { return inClassId==(int)0x00000001 || inClassId==(int)0x12d0aa2c; } else { return inClassId==(int)0x40cee131; } } else { return inClassId==(int)0x79231394; } } ::hx::ObjectPtr< __ASSET__OPENFL__flixel_fonts_monsterrat_ttf_obj > __ASSET__OPENFL__flixel_fonts_monsterrat_ttf_obj::__new() { ::hx::ObjectPtr< __ASSET__OPENFL__flixel_fonts_monsterrat_ttf_obj > __this = new __ASSET__OPENFL__flixel_fonts_monsterrat_ttf_obj(); __this->__construct(); return __this; } ::hx::ObjectPtr< __ASSET__OPENFL__flixel_fonts_monsterrat_ttf_obj > __ASSET__OPENFL__flixel_fonts_monsterrat_ttf_obj::__alloc(::hx::Ctx *_hx_ctx) { __ASSET__OPENFL__flixel_fonts_monsterrat_ttf_obj *__this = (__ASSET__OPENFL__flixel_fonts_monsterrat_ttf_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(__ASSET__OPENFL__flixel_fonts_monsterrat_ttf_obj), true, "__ASSET__OPENFL__flixel_fonts_monsterrat_ttf")); *(void **)__this = __ASSET__OPENFL__flixel_fonts_monsterrat_ttf_obj::_hx_vtable; __this->__construct(); return __this; } __ASSET__OPENFL__flixel_fonts_monsterrat_ttf_obj::__ASSET__OPENFL__flixel_fonts_monsterrat_ttf_obj() { } #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo *__ASSET__OPENFL__flixel_fonts_monsterrat_ttf_obj_sMemberStorageInfo = 0; static ::hx::StaticInfo *__ASSET__OPENFL__flixel_fonts_monsterrat_ttf_obj_sStaticStorageInfo = 0; #endif ::hx::Class __ASSET__OPENFL__flixel_fonts_monsterrat_ttf_obj::__mClass; void __ASSET__OPENFL__flixel_fonts_monsterrat_ttf_obj::__register() { __ASSET__OPENFL__flixel_fonts_monsterrat_ttf_obj _hx_dummy; __ASSET__OPENFL__flixel_fonts_monsterrat_ttf_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("__ASSET__OPENFL__flixel_fonts_monsterrat_ttf",50,8e,18,4c); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = ::hx::Class_obj::dupFunctions(0 /* sMemberFields */); __mClass->mCanCast = ::hx::TCanCast< __ASSET__OPENFL__flixel_fonts_monsterrat_ttf_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = __ASSET__OPENFL__flixel_fonts_monsterrat_ttf_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = __ASSET__OPENFL__flixel_fonts_monsterrat_ttf_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); }
43.447917
251
0.825462
bobisdabbing
8b14cf768275f12f15b35d36cd0b505e58e0a849
6,697
cpp
C++
Source/Core/RenderAPI/VulkanAPI/VulkanCommandListPool.cpp
Cube219/CubeEngine_old2
d251d540a4fdbc993ec5c9183eb30ac4dc81d5be
[ "MIT" ]
null
null
null
Source/Core/RenderAPI/VulkanAPI/VulkanCommandListPool.cpp
Cube219/CubeEngine_old2
d251d540a4fdbc993ec5c9183eb30ac4dc81d5be
[ "MIT" ]
null
null
null
Source/Core/RenderAPI/VulkanAPI/VulkanCommandListPool.cpp
Cube219/CubeEngine_old2
d251d540a4fdbc993ec5c9183eb30ac4dc81d5be
[ "MIT" ]
null
null
null
#include "VulkanCommandListPool.h" #include "VulkanDebug.h" #include "VulkanUtility.h" #include "VulkanLogicalDevice.h" #include "VulkanQueueManager.h" #include "EngineCore/Assertion.h" namespace cube { namespace render { VulkanCommandListPool::VulkanCommandListPool(SPtr<VulkanLogicalDevice>& device, VulkanQueueManager& queueManager) : mDevice(device) { VkResult res; VkCommandPoolCreateInfo info; info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; info.pNext = nullptr; // Graphics command pool info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; mGraphicsQueueFamilyIndex = queueManager.GetGraphicsQueueFamilyIndex(); info.queueFamilyIndex = mGraphicsQueueFamilyIndex; for(Uint32 i = 0; i < maxThreadNum; i++) { res = vkCreateCommandPool(mDevice->GetHandle(), &info, nullptr, &mGraphicsCommandPools[i]); CHECK_VK(res, "Failed to create graphics command pool."); VulkanDebug::SetObjectName(mDevice->GetHandle(), mGraphicsCommandPools[i], fmt::format("GraphicsCommandPool[{0}]", i).c_str()); } // Transfer command pool info.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT; mTransferImmediateQueueFamilyIndex = queueManager.GetTransferImmediateQueueFamilyIndex(); info.queueFamilyIndex = mTransferImmediateQueueFamilyIndex; for(Uint32 i = 0; i < maxThreadNum; i++) { res = vkCreateCommandPool(mDevice->GetHandle(), &info, nullptr, &mTransferImmediateCommandPools[i]); CHECK_VK(res, "Failed to create transfer immediate command pool."); VulkanDebug::SetObjectName(mDevice->GetHandle(), mTransferImmediateCommandPools[i], fmt::format("TransferImmediateCommandPool[{0}]", i).c_str()); } info.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT; mTransferDeferredQueueFamilyIndex = queueManager.GetTransferDeferredFamilyIndex(); info.queueFamilyIndex = mTransferDeferredQueueFamilyIndex; for(Uint32 i = 0; i < maxThreadNum; i++) { res = vkCreateCommandPool(mDevice->GetHandle(), &info, nullptr, &mTransferDeferredCommandPools[i]); CHECK_VK(res, "Failed to create transfer deferred command pool."); VulkanDebug::SetObjectName(mDevice->GetHandle(), mTransferDeferredCommandPools[i], fmt::format("TransferDeferredCommandPool[{0}]", i).c_str()); } // Compute command pool info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; mComputeQueueFamilyIndex = queueManager.GetComputeQueueFamilyIndex(); info.queueFamilyIndex = mComputeQueueFamilyIndex; for(Uint32 i = 0; i < maxThreadNum; i++) { res = vkCreateCommandPool(mDevice->GetHandle(), &info, nullptr, &mComputeCommandPools[i]); CHECK_VK(res, "Failed to create compute command pool."); VulkanDebug::SetObjectName(mDevice->GetHandle(), mComputeCommandPools[i], fmt::format("ComputeCommandPool[{0}]", i).c_str()); } } VulkanCommandListPool::~VulkanCommandListPool() { for(Uint32 i = 0; i < maxThreadNum; i++) { vkDestroyCommandPool(mDevice->GetHandle(), mGraphicsCommandPools[i], nullptr); vkDestroyCommandPool(mDevice->GetHandle(), mTransferImmediateCommandPools[i], nullptr); vkDestroyCommandPool(mDevice->GetHandle(), mTransferDeferredCommandPools[i], nullptr); vkDestroyCommandPool(mDevice->GetHandle(), mComputeCommandPools[i], nullptr); } } SPtr<CommandListVk> VulkanCommandListPool::Allocate(const CommandListAttribute& attr) { VkCommandBufferAllocateInfo info; info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; info.pNext = nullptr; if(attr.isSub == false) info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; else info.level = VK_COMMAND_BUFFER_LEVEL_SECONDARY; info.commandBufferCount = 1; SPtr<CommandListVk> cmd; VkCommandBuffer cmdBuf; switch(attr.usage) { case CommandListUsage::Graphics: { info.commandPool = mGraphicsCommandPools[attr.threadIndex]; Lock lock(mGraphicsCommandPoolMutexes[attr.threadIndex]); vkAllocateCommandBuffers(mDevice->GetHandle(), &info, &cmdBuf); lock.unlock(); cmd = std::make_shared<CommandListVk>(*this, attr, cmdBuf, mGraphicsQueueFamilyIndex); break; } case CommandListUsage::TransferImmediate: { info.commandPool = mTransferImmediateCommandPools[attr.threadIndex]; Lock lock(mTransferImmediateCommandPoolMutexes[attr.threadIndex]); vkAllocateCommandBuffers(mDevice->GetHandle(), &info, &cmdBuf); lock.unlock(); cmd = std::make_shared<CommandListVk>(*this, attr, cmdBuf, mTransferImmediateQueueFamilyIndex); break; } case CommandListUsage::TransferDeferred: { info.commandPool = mTransferDeferredCommandPools[attr.threadIndex]; Lock lock(mTransferDeferredCommandPoolMutexes[attr.threadIndex]); vkAllocateCommandBuffers(mDevice->GetHandle(), &info, &cmdBuf); lock.unlock(); cmd = std::make_shared<CommandListVk>(*this, attr, cmdBuf, mTransferDeferredQueueFamilyIndex); break; } case CommandListUsage::Compute: { info.commandPool = mComputeCommandPools[attr.threadIndex]; Lock lock(mComputeCommandPoolMutexes[attr.threadIndex]); vkAllocateCommandBuffers(mDevice->GetHandle(), &info, &cmdBuf); lock.unlock(); cmd = std::make_shared<CommandListVk>(*this, attr, cmdBuf, mComputeQueueFamilyIndex); break; } default: ASSERTION_FAILED("Unknown CommandListUsage({0}).", (Uint32)attr.usage); } return cmd; } void VulkanCommandListPool::Free(CommandListVk& commandList) { VkCommandBuffer cmdBuf = commandList.GetHandle(); Uint32 index = commandList.GetAllocatedCommandPoolIndex(); switch(commandList.GetUsage()) { case CommandListUsage::Graphics: { Lock lock(mGraphicsCommandPoolMutexes[index]); vkFreeCommandBuffers(mDevice->GetHandle(), mGraphicsCommandPools[index], 1, &cmdBuf); break; } case CommandListUsage::TransferImmediate: { Lock lock(mTransferImmediateCommandPoolMutexes[index]); vkFreeCommandBuffers(mDevice->GetHandle(), mTransferImmediateCommandPools[index], 1, &cmdBuf); break; } case CommandListUsage::TransferDeferred: { Lock lock(mTransferDeferredCommandPoolMutexes[index]); vkFreeCommandBuffers(mDevice->GetHandle(), mTransferDeferredCommandPools[index], 1, &cmdBuf); break; } case CommandListUsage::Compute: { Lock lock(mComputeCommandPoolMutexes[index]); vkFreeCommandBuffers(mDevice->GetHandle(), mComputeCommandPools[index], 1, &cmdBuf); break; } default: ASSERTION_FAILED("Unknown CommandListUsage({0}).", (Uint32)commandList.GetUsage()); } } } // namespace render } // namespace cube
34.520619
117
0.734359
Cube219
8b19d5200d578b89a2a96e12d448b00cd11ec26e
2,508
hpp
C++
Sisyphe/cppbase/src/debugErrorInfoPredicate.hpp
tedi21/SisypheReview
f7c05bad1ccc036f45870535149d9685e1120c2c
[ "Unlicense" ]
null
null
null
Sisyphe/cppbase/src/debugErrorInfoPredicate.hpp
tedi21/SisypheReview
f7c05bad1ccc036f45870535149d9685e1120c2c
[ "Unlicense" ]
null
null
null
Sisyphe/cppbase/src/debugErrorInfoPredicate.hpp
tedi21/SisypheReview
f7c05bad1ccc036f45870535149d9685e1120c2c
[ "Unlicense" ]
null
null
null
/* * debugErrorInfoPredicate.hpp * * * @date 14-07-2020 * @author Teddy DIDE * @version 1.00 * cppBase generated by gensources. */ #ifndef _DEBUGERRORINFO_PREDICATE_HPP_ #define _DEBUGERRORINFO_PREDICATE_HPP_ NAMESPACE_BEGIN(entity) /// Represents a comparaison class for DebugErrorInfo object. /// This class is used to find an object with the same ID. template<class EncodingT> class _DebugErrorInfo<EncodingT>::DebugErrorInfoIDEquality { private : long long m_identifier; public : /** Creates a new functor allowing to find DebugErrorInfo object. @param identifier */ DebugErrorInfoIDEquality(long long identifier) : m_identifier(identifier) { } DebugErrorInfoIDEquality(const _DebugErrorInfo<EncodingT>& elem) : m_identifier(elem.getIdentifier()) { } bool operator()(boost::shared_ptr< _DebugErrorInfo<EncodingT> > other) const { return (other != NULL && m_identifier==other->getIdentifier()); } }; /// Represents a comparaison class for DebugErrorInfo object. /// This class is used to find an object with the same element <i>callStack</i>. template<class EncodingT> class _DebugErrorInfo<EncodingT>::CallStackEquality { private : typename EncodingT::string_t m_callStack; public : /** Creates a new functor allowing to find DebugErrorInfo object. @param callStack */ CallStackEquality(const typename EncodingT::string_t& callStack) : m_callStack(callStack) { } bool operator()(boost::shared_ptr< _DebugErrorInfo<EncodingT> > other) const { return (other != NULL && m_callStack==other->getCallStack()); } }; /// Represents a comparaison class for DebugErrorInfo object. /// This class is used to sort objects by <i>callStack</i>. template<class EncodingT> class _DebugErrorInfo<EncodingT>::CallStackInferior { private : public : bool operator()(boost::shared_ptr< _DebugErrorInfo<EncodingT> > elem1, boost::shared_ptr< _DebugErrorInfo<EncodingT> > elem2) const { return (elem1 != NULL && elem2 != NULL && elem1->getCallStack() < elem2->getCallStack()); } }; /// Represents a comparaison class for DebugErrorInfo object. /// This class is used to sort objects by <i>callStack</i>. template<class EncodingT> class _DebugErrorInfo<EncodingT>::CallStackSuperior { private : public : bool operator()(boost::shared_ptr< _DebugErrorInfo<EncodingT> > elem1, boost::shared_ptr< _DebugErrorInfo<EncodingT> > elem2) const { return (elem1 != NULL && elem2 != NULL && elem1->getCallStack() > elem2->getCallStack()); } }; NAMESPACE_END #endif
26.680851
133
0.744019
tedi21
8b1c795ac95d5865d280efe773521ff86f1bc2e7
3,065
hpp
C++
src/NumericalAlgorithms/Interpolation/SendPointsToInterpolator.hpp
marissawalker/spectre
afc8205e2f697de5e8e4f05e881499e05c9fd8a0
[ "MIT" ]
null
null
null
src/NumericalAlgorithms/Interpolation/SendPointsToInterpolator.hpp
marissawalker/spectre
afc8205e2f697de5e8e4f05e881499e05c9fd8a0
[ "MIT" ]
null
null
null
src/NumericalAlgorithms/Interpolation/SendPointsToInterpolator.hpp
marissawalker/spectre
afc8205e2f697de5e8e4f05e881499e05c9fd8a0
[ "MIT" ]
null
null
null
// Distributed under the MIT License. // See LICENSE.txt for details. #pragma once #include <algorithm> #include "DataStructures/DataBox/DataBox.hpp" #include "DataStructures/DataBox/DataBoxTag.hpp" #include "DataStructures/Variables.hpp" #include "Domain/BlockLogicalCoordinates.hpp" #include "Domain/Tags.hpp" #include "NumericalAlgorithms/Interpolation/Tags.hpp" #include "Parallel/ConstGlobalCache.hpp" #include "Parallel/Invoke.hpp" /// \cond namespace intrp { template <typename Metavariables, size_t VolumeDim> struct Interpolator; namespace Actions { template <typename InterpolationTargetTag> struct ReceivePoints; } // namespace Actions } // namespace intrp /// \endcond namespace intrp { /// Sends to all the Interpolators a list of all the points that need /// to be interpolated onto. Also clears information about data that /// has already been interpolated, since calling this function triggers /// a new interpolation. /// /// Called by InterpolationTargetTag::compute_target_points. This is not an /// Action, but rather a helper function that is called by every /// Action (LineSegment, Strahlkorper, etc.) that specifies a /// particular set of points. template <typename InterpolationTargetTag, typename DbTags, typename Metavariables, size_t VolumeDim, typename Frame> void send_points_to_interpolator( db::DataBox<DbTags>& box, Parallel::ConstGlobalCache<Metavariables>& cache, const tnsr::I<DataVector, VolumeDim, Frame>& target_points, const typename Metavariables::temporal_id& temporal_id) noexcept { const auto& domain = db::get<::Tags::Domain<VolumeDim, Frame>>(box); auto coords = block_logical_coordinates(domain, target_points); db::mutate< Tags::IndicesOfFilledInterpPoints, ::Tags::Variables< typename InterpolationTargetTag::vars_to_interpolate_to_target>>( make_not_null(&box), [&coords]( const gsl::not_null<db::item_type<Tags::IndicesOfFilledInterpPoints>*> indices_of_filled, const gsl::not_null<db::item_type<::Tags::Variables< typename InterpolationTargetTag::vars_to_interpolate_to_target>>*> vars_dest) noexcept { // Because we are sending new points to the interpolator, // we know that none of these points have been interpolated to, // so clear the list. indices_of_filled->clear(); // We will be filling vars_dest with interpolated data. // Here we make sure it is allocated to the correct size. if (vars_dest->number_of_grid_points() != coords.size()) { *vars_dest = db::item_type<::Tags::Variables< typename InterpolationTargetTag::vars_to_interpolate_to_target>>( coords.size()); } }); auto& receiver_proxy = Parallel::get_parallel_component<Interpolator<Metavariables, VolumeDim>>( cache); Parallel::simple_action< Actions::ReceivePoints<InterpolationTargetTag>>( receiver_proxy, temporal_id, std::move(coords)); } } // namespace intrp
37.378049
80
0.717781
marissawalker
8b1cc42169c51859260c36e11fd8b82ffadf7f02
6,420
cpp
C++
Synergy/src/Synergy/Renderer/Renderer2D.cpp
nmrsmn/synergy
7f77c70c131debe66d2e91e00827fd30e736cf81
[ "MIT" ]
null
null
null
Synergy/src/Synergy/Renderer/Renderer2D.cpp
nmrsmn/synergy
7f77c70c131debe66d2e91e00827fd30e736cf81
[ "MIT" ]
25
2020-04-05T11:05:08.000Z
2020-06-07T12:48:58.000Z
Synergy/src/Synergy/Renderer/Renderer2D.cpp
nmrsmn/synergy
7f77c70c131debe66d2e91e00827fd30e736cf81
[ "MIT" ]
null
null
null
// Created by Niels Marsman on 21-04-2020. // Copyright © 2020 Niels Marsman. All rights reserved. #include <glad/glad.h> #include <glm/gtc/matrix_transform.hpp> #include "Synergy/Renderer/Renderer2D.h" #include "Synergy/Renderer/Shader.h" #include "Synergy/Renderer/Shaders.h" #include "Synergy/Renderer/Texture.h" #include "Synergy/Renderer/VertexArray.h" #include "Synergy/Renderer/VertexBuffer.h" #include "Synergy/Renderer/IndexBuffer.h" namespace Synergy::Renderer { struct Vertex { glm::vec3 position; glm::vec4 color; glm::vec2 uv; float texture; }; struct Data { static const uint32_t quads = 20000; static const uint32_t vertices = quads * 4; static const uint32_t indices = quads * 6; static const uint32_t textures = 16; Ref<Shader> shader; Ref<VertexArray> vertexArray; Ref<VertexBuffer> vertexBuffer; Ref<IndexBuffer> indexBuffer; Ref<Texture> whiteTexture; uint32_t indexCount = 0; Vertex* vertexBufferStart = nullptr; Vertex* vertexBufferCurrent = nullptr; std::array<Ref<Texture>, Data::textures> slots; uint32_t slotIndex = 1; glm::vec4 positions[4]; }; static Data data; Renderer2D& Renderer2D::Instance() { static Renderer2D instance; return instance; } void Renderer2D::Initialize() { data.vertexArray = api->CreateVertexArray(); data.vertexBuffer = api->CreateVertexBuffer(Data::vertices * sizeof(Vertex)); data.vertexBuffer->SetLayout({ { Shader::DataType::VEC3, "a_position" }, { Shader::DataType::VEC4, "a_color" }, { Shader::DataType::VEC2, "a_uv" }, { Shader::DataType::FLOAT, "a_texture_index" } }); data.vertexArray->AddVertexBuffer(data.vertexBuffer); data.vertexBufferStart = new Vertex[Data::vertices]; uint32_t* indices = new uint32_t[Data::indices]; uint32_t offset = 0; for (uint32_t index = 0; index < Data::indices; index += 6) { indices[index + 0] = offset + 0; indices[index + 1] = offset + 1; indices[index + 2] = offset + 2; indices[index + 3] = offset + 2; indices[index + 4] = offset + 3; indices[index + 5] = offset + 0; offset += 4; } data.indexBuffer = api->CreateIndexBuffer(indices, Data::indices); data.vertexArray->SetIndexBuffer(data.indexBuffer); delete[] indices; uint32_t textureData = 0xffffffff; data.whiteTexture = Synergy::Texture::Create(1, 1); data.whiteTexture->SetData(&textureData, sizeof(textureData)); int32_t samplers[Data::textures]; for (int32_t index = 0; index < Data::textures; index++) samplers[index] = index; data.shader = Synergy::Shaders::Load("BatchRenderer.shader"); data.shader->Bind(); data.shader->SetIntArray("u_textures", samplers, Data::textures); data.slots[0] = data.whiteTexture; data.positions[0] = { -0.5f, -0.5f, -1.0f, 1.0f }; data.positions[1] = { 0.5f, -0.5f, -1.0f, 1.0f }; data.positions[2] = { 0.5f, 0.5f, -1.0f, 1.0f }; data.positions[3] = { -0.5f, 0.5f, -1.0f, 1.0f }; } void Renderer2D::Initialize(RendererAPI* api) { Instance().api = api; Instance().Initialize(); } void Renderer2D::BeginScene(const Synergy::Camera::Camera& camera) { data.vertexArray->Bind(); data.shader->Bind(); data.shader->SetMat4("u_view_projection", camera.GetViewProjectionMatrix()); data.indexCount = 0; data.vertexBufferCurrent = data.vertexBufferStart; data.slotIndex = 1; } void Renderer2D::EndScene() { uint32_t size = (uint8_t*) data.vertexBufferCurrent - (uint8_t*) data.vertexBufferStart; data.vertexBuffer->SetData(data.vertexBufferStart, size); Flush(); } void Renderer2D::Flush() { for (uint32_t index = 0; index < data.slotIndex; index++) { data.slots[index]->Activate(index); data.slots[index]->Bind(); } Instance().api->DrawIndexed(data.vertexArray, data.indexCount); } void Renderer2D::FlushAndReset() { Renderer2D::EndScene(); data.indexCount = 0; data.vertexBufferCurrent = data.vertexBufferStart; data.slotIndex = 1; } void Renderer2D::SubmitRenderable(Renderable2D renderable) { if (data.indexCount >= Data::indices) FlushAndReset(); float textureIndex = 0.0f; if (renderable.texture != nullptr) { for (uint32_t index = 0; index < data.slotIndex; index++) if (*data.slots[index].get() == *renderable.texture.get()) textureIndex = index; if (textureIndex == 0.0f) { if (data.slotIndex >= Data::textures) { FlushAndReset(); } textureIndex = (float) data.slotIndex; data.slots[textureIndex] = renderable.texture; data.slotIndex++; } } const glm::vec2* uvs = renderable.texture != nullptr ? renderable.texture->GetUVs() : data.whiteTexture->GetUVs(); glm::mat4 transform = glm::translate(glm::mat4(1.0f), renderable.position) * glm::scale(glm::mat4(1.0f), { renderable.size.x, renderable.size.y, 1.0f }); for (size_t offset = 0; offset < 4; offset++) { data.vertexBufferCurrent->position = transform * data.positions[offset]; data.vertexBufferCurrent->color = renderable.color; data.vertexBufferCurrent->uv = uvs[offset]; data.vertexBufferCurrent->texture = textureIndex; data.vertexBufferCurrent++; } data.indexCount += 6; } void Renderer2D::SubmitText(Text text) { } }
30.283019
122
0.556386
nmrsmn
8b2214da4901c7108c5d038b847517e443f93943
9,712
hh
C++
source/base/KBRun.hh
sh-lim/kebi-1
c5cfcf4c26db0dff0067fa3911e1dbcc193c77e9
[ "MIT" ]
null
null
null
source/base/KBRun.hh
sh-lim/kebi-1
c5cfcf4c26db0dff0067fa3911e1dbcc193c77e9
[ "MIT" ]
null
null
null
source/base/KBRun.hh
sh-lim/kebi-1
c5cfcf4c26db0dff0067fa3911e1dbcc193c77e9
[ "MIT" ]
1
2020-08-11T01:39:16.000Z
2020-08-11T01:39:16.000Z
#ifndef KBRUN_HH #define KBRUN_HH #include "KBCompiled.h" #include "KBTask.hh" #include "KBParameterContainer.hh" #include "KBDetectorSystem.hh" #include "KBDetector.hh" #include "KBTpc.hh" #include "KBPadPlane.hh" #include "KBMCTrack.hh" #include "TDatabasePDG.h" #include "TError.h" #include "TH1D.h" #include "TGraph.h" #include "TFile.h" #include "TTree.h" #include "TChain.h" #include "TObject.h" #include "TClonesArray.h" #include "TCanvas.h" #ifdef ACTIVATE_EVE #include "TEveEventManager.h" #include "TEveEventManager.h" #endif #include <map> #include <vector> #include <fstream> #include <stdlib.h> using namespace std; #include "TSysEvtHandler.h" class InterruptHandler; class KBRun : public KBTask { public: static KBRun* GetRun(); ///< Get KBRun static pointer. KBRun(); ///< Do not use this constructor. Use GetRun() only. virtual ~KBRun() {}; static TString GetKEBIVersion(); ///< Compiled KEBI version static TString GetGETDecoderVersion(); ///< Compiled GETDecoder version static TString GetKEBIHostName(); ///< KEBI Host name static TString GetKEBIUserName(); ///< KEBI User name static TString GetKEBIPath(); ///< Compiled KEBI path static void PrintKEBI(); ///< Print compiled KEBI information /** * @param option * - "all" : Print all. Same as "cpdio". (Default) * - "c" : Print compiled info. * - "p" : Print parameter container * - "d" : Print detector * - "i" : Print input * - "o" : Print output */ virtual void Print(Option_t *option="all") const; void SetRunName(TString name, Int_t id=-999); TString GetRunName() const; void SetRunID(Int_t id); Int_t GetRunID() const; void SetDataPath(TString path); ///< Set data directory path. Default directory : path/to/KEBI/data TString GetDataPath(); void SetInputFile(TString fileName, TString treeName = "event"); ///< Set input file and tree name void AddInputFile(TString fileName, TString treeName = "event"); ///< Add file to input file void AddFriend(TString fileName); ///< Add file to input file void SetInputTreeName(TString treeName); ///< Set input tree name TFile *GetInputFile(); TTree *GetInputTree() const; TChain *GetInputChain() const; TChain *GetFriendChain(Int_t iFriend) const; void SetOutputFile(TString name); ///< Set output file name TFile *GetOutputFile(); TTree *GetOutputTree(); void SetTag(TString tag); void SetSplit(Int_t split, Long64_t numSplitEntries); void SetIOFile(TString inputName, TString outputName, TString treeName = "event"); bool Init(); ///< Initailize KBRun. Init() must be done before Run(). KBParameterContainer *GetProcessTable() const; KBParameterContainer *GetSDTable() const; KBParameterContainer *GetVolumeTable() const; void CreateParameterFile(TString name); virtual void AddParameterContainer(KBParameterContainer *par); virtual void AddParameterContainer(TString fname); /** * Register obj as a output branch with given name. * obj will not be registered if same name already exist in the branch list and return fail. * If persistent is true, branch will write it's data to output tree. */ bool RegisterBranch(TString name, TObject *obj, bool persistent); TObject *GetBranch(TString name); ///< Get branch by name. TClonesArray *GetBranchA(TString name); ///< Get TClonesArray branch by name. void AddDetector(KBDetector *detector); ///< Set detector KBDetector *GetDetector(Int_t idx=0) const; KBDetectorSystem *GetDetectorSystem() const; void SetGeoManager(TGeoManager *gm); TGeoManager *GetGeoManager() const; void SetGeoTransparency(Int_t transparency); ///< Set transparency of geometry. Will show in eve. void SetEntries(Long64_t num); ///< Set total number of entries. Use only input do not exist. Long64_t GetEntries() const; ///< Get total number of entries Long64_t GetNumEvents() const; Int_t GetEntry(Long64_t entry = 0, Int_t getall = 0); ///< GetEntry from input tree Int_t GetEvent(Long64_t entry); bool GetNextEvent(); Long64_t GetStartEventID() const; ///< Get starting eventID Long64_t GetEndEventID() const; ///< Get ending eventID Long64_t GetCurrentEventID() const; ///< Get current eventID /// Get eventID count; event_count = current_eventID - start_eventID Long64_t GetEventCount() const; bool Event(Long64_t eventID); bool NextEvent(); void Run(Long64_t endEventID = -1); ///< Run all events void RunSingle(Long64_t eventID); ///< Run single event given eventID void RunInRange(Long64_t startID, Long64_t endID); ///< Run in range from startID to endID void RunInEventRange(Long64_t startID, Long64_t endID); ///< @todo Write this method void SignalEndOfRun(); void SignalInterrupt(); /// Run eventdisplay of given eveEventID. /// option is used to activate following displays: /// - e : display 3D eventdisplay /// - p : display detector planes void RunEve(Long64_t eveEventID=0, TString option=""); //void SelectEveBranches(TString option); void SetEveScale(Double_t scale); //Color_t GetColor(); #ifdef ACTIVATE_EVE void AddEveElementToEvent(KBContainer *eveObj, bool permanent = true); void AddEveElementToEvent(TEveElement *element, bool permanent = true); #endif void WriteCvsDetectorPlanes(TString format = "pdf"); static void ClickSelectedPadPlane(); void DrawPadByPosition(Double_t x, Double_t y); void SetLogFile(TString name = ""); TString GetLogFile(); //std::ofstream &GetLogFileStream(); void SetAutoTermination(Bool_t val); void Terminate(TObject *obj, TString message = ""); TString GetFileVersion(TString name); static TString ConfigureDataPath(TString name, bool search = false, TString dataPath="", bool isRootFile=true); static TString ConfigureEnv(TString name); static bool CheckFileExistence(TString fileName); TDatabasePDG *GetDatabasePDG(); TParticlePDG *GetParticle(Int_t pdgCode); TParticlePDG *GetParticle(const char *name); void PrintMCTrack(KBMCTrack *track, Option_t *); private: #ifdef ACTIVATE_EVE void ConfigureEventDisplay(); #endif void DrawEve3D(); void ConfigureDetectorPlanes(); void DrawDetectorPlanes(); void SetEveLineAtt(TEveElement *el, TString branchName); void SetEveMarkerAtt(TEveElement *el, TString branchName); bool SelectTrack(KBTracklet *track); bool SelectHit(KBHit *hit); void CheckIn(); void CheckOut(); private: TString fRunName = ""; Int_t fRunID = -1; bool fInitialized = false; TString fDataPath = ""; TString fInputVersion = ""; TString fInputFileName = ""; TString fInputTreeName = ""; TFile *fInputFile = nullptr; TChain *fInputTree = nullptr; KBParameterContainer fTempPar; Int_t fNumFriends = 0; TObjArray *fFriendTrees = nullptr; vector<TString> fInputFileNameArray; vector<TString> fFriendFileNameArray; TString fOutputVersion = ""; TString fOutputFileName = ""; TString fTag = ""; Int_t fSplit = -1; Long64_t fNumSplitEntries = -1; TFile *fOutputFile = nullptr; TTree *fOutputTree = nullptr; TObjArray *fPersistentBranchArray = nullptr; TObjArray *fTemporaryBranchArray = nullptr; Int_t fNumBranches = 0; TObject **fBranchPtr; std::vector<TString> fBranchNames; std::map<TString, TObject*> fBranchPtrMap; Long64_t fNumEntries = 0; Long64_t fIdxEntry = 0; Long64_t fStartEventID = -1; Long64_t fEndEventID = -1; Long64_t fCurrentEventID = 0; Long64_t fEventCount = 0; bool fSignalEndOfRun = false; bool fCheckIn = false; KBParameterContainer *fRunHeader = nullptr; KBParameterContainer *fProcessTable = nullptr; KBParameterContainer *fSDTable = nullptr; KBParameterContainer *fVolumeTable = nullptr; KBDetectorSystem *fDetectorSystem = nullptr; std::vector<TString> fListOfGitBranches; std::vector<int> fListOfNumTagsInGitBranches; std::vector<TString> fListOfGitHashTags; std::vector<TString> fListOfVersionMarks; #ifdef ACTIVATE_EVE TObjArray *fEveEventManagerArray = nullptr; TEveEventManager *fEveEventManager = nullptr; std::vector<TEveElement *> fEveElementList; std::vector<TEveElement *> fPermanentEveElementList; Double_t fEveScale = 1; #endif //TString fEveBranches; TString fEveOption; vector<Int_t> fSelTrkIDs; vector<Int_t> fIgnTrkIDs; vector<Int_t> fSelPntIDs; vector<Int_t> fIgnPntIDs; vector<Int_t> fSelPDGs; vector<Int_t> fIgnPDGs; vector<Int_t> fSelMCIDs; vector<Int_t> fIgnMCIDs; vector<Int_t> fSelHitPntIDs; vector<Int_t> fIgnHitPntIDs; vector<TString> fSelBranchNames; int fNumSelectedBranches; TObjArray *fCvsDetectorPlaneArray = nullptr; TCanvas *fCvsChannelBuffer = nullptr; TH1D *fHistChannelBuffer = nullptr; TGraph *fGraphChannelBoundary = nullptr; TGraph *fGraphChannelBoundaryNb[20] = {0}; TString fRunLogFileName; std::ofstream fRunLogFileStream; TString fKBLogFileName; TString fHash; Bool_t fAutoTerminate = true; InterruptHandler *fInterruptHandler = nullptr; private: static KBRun *fInstance; ClassDef(KBRun, 1) }; class InterruptHandler : public TSignalHandler { public: InterruptHandler() : TSignalHandler(kSigInterrupt, kFALSE) { } virtual Bool_t Notify() { KBRun::GetRun() -> SignalInterrupt(); return kTRUE; } }; #endif
30.734177
115
0.699238
sh-lim
8b24a3648905c1fba1fb37c0ad38375505760254
101,819
cpp
C++
_studio/shared/umc/codec/h264_dec/src/umc_h264_dec_bitstream_headers.cpp
wangyan42164/MediaSDK
bc98489e124b52c435a99eb85eef497d871be989
[ "MIT" ]
4
2021-03-03T10:18:53.000Z
2022-03-31T03:04:34.000Z
_studio/shared/umc/codec/h264_dec/src/umc_h264_dec_bitstream_headers.cpp
wangyan42164/MediaSDK
bc98489e124b52c435a99eb85eef497d871be989
[ "MIT" ]
1
2021-01-21T12:27:39.000Z
2021-01-21T12:27:39.000Z
_studio/shared/umc/codec/h264_dec/src/umc_h264_dec_bitstream_headers.cpp
wangyan42164/MediaSDK
bc98489e124b52c435a99eb85eef497d871be989
[ "MIT" ]
1
2022-02-10T03:24:51.000Z
2022-02-10T03:24:51.000Z
// Copyright (c) 2017-2019 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. #include "umc_defs.h" #if defined (MFX_ENABLE_H264_VIDEO_DECODE) #include "umc_h264_dec.h" #include "umc_h264_bitstream_headers.h" #include "umc_h264_headers.h" #include <limits.h> #define SCLFLAT16 0 #define SCLDEFAULT 1 #define SCLREDEFINED 2 #define PeakNextBits(current_data, bp, nbits, data) \ { \ uint32_t x; \ \ VM_ASSERT((nbits) > 0 && (nbits) <= 32); \ VM_ASSERT(nbits >= 0 && nbits <= 31); \ \ int32_t offset = bp - (nbits); \ \ if (offset >= 0) \ { \ x = current_data[0] >> (offset + 1); \ } \ else \ { \ offset += 32; \ \ x = current_data[1] >> (offset); \ x >>= 1; \ x += current_data[0] << (31 - offset); \ } \ \ VM_ASSERT(offset >= 0 && offset <= 31); \ \ (data) = x & bits_data[nbits]; \ } using namespace UMC_H264_DECODER; namespace UMC { static const int32_t pre_norm_adjust_index4x4[16] = {// 0 1 2 3 0,2,0,2,//0 2,1,2,1,//1 0,2,0,2,//2 2,1,2,1 //3 }; static const int32_t pre_norm_adjust4x4[6][3] = { {10,16,13}, {11,18,14}, {13,20,16}, {14,23,18}, {16,25,20}, {18,29,23} }; static const int32_t pre_norm_adjust8x8[6][6] = { {20, 18, 32, 19, 25, 24}, {22, 19, 35, 21, 28, 26}, {26, 23, 42, 24, 33, 31}, {28, 25, 45, 26, 35, 33}, {32, 28, 51, 30, 40, 38}, {36, 32, 58, 34, 46, 43} }; static const int32_t pre_norm_adjust_index8x8[64] = {// 0 1 2 3 4 5 6 7 0,3,4,3,0,3,4,3,//0 3,1,5,1,3,1,5,1,//1 4,5,2,5,4,5,2,5,//2 3,1,5,1,3,1,5,1,//3 0,3,4,3,0,3,4,3,//4 3,1,5,1,3,1,5,1,//5 4,5,2,5,4,5,2,5,//6 3,1,5,1,3,1,5,1 //7 }; const int32_t mp_scan4x4[2][16] = { { 0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15 }, { 0, 4, 1, 8, 12, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15 } }; const int32_t hp_scan8x8[2][64] = { //8x8 zigzag scan { 0, 1, 8,16, 9, 2, 3,10, 17,24,32,25,18,11, 4, 5, 12,19,26,33,40,48,41,34, 27,20,13, 6, 7,14,21,28, 35,42,49,56,57,50,43,36, 29,22,15,23,30,37,44,51, 58,59,52,45,38,31,39,46, 53,60,61,54,47,55,62,63 }, //8x8 field scan { 0, 8,16, 1, 9,24,32,17, 2,25,40,48,56,33,10, 3, 18,41,49,57,26,11, 4,19, 34,42,50,58,27,12, 5,20, 35,43,51,59,28,13, 6,21, 36,44,52,60,29,14,22,37, 45,53,61,30, 7,15,38,46, 54,62,23,31,39,47,55,63 } }; const uint32_t bits_data[] = { (((uint32_t)0x01 << (0)) - 1), (((uint32_t)0x01 << (1)) - 1), (((uint32_t)0x01 << (2)) - 1), (((uint32_t)0x01 << (3)) - 1), (((uint32_t)0x01 << (4)) - 1), (((uint32_t)0x01 << (5)) - 1), (((uint32_t)0x01 << (6)) - 1), (((uint32_t)0x01 << (7)) - 1), (((uint32_t)0x01 << (8)) - 1), (((uint32_t)0x01 << (9)) - 1), (((uint32_t)0x01 << (10)) - 1), (((uint32_t)0x01 << (11)) - 1), (((uint32_t)0x01 << (12)) - 1), (((uint32_t)0x01 << (13)) - 1), (((uint32_t)0x01 << (14)) - 1), (((uint32_t)0x01 << (15)) - 1), (((uint32_t)0x01 << (16)) - 1), (((uint32_t)0x01 << (17)) - 1), (((uint32_t)0x01 << (18)) - 1), (((uint32_t)0x01 << (19)) - 1), (((uint32_t)0x01 << (20)) - 1), (((uint32_t)0x01 << (21)) - 1), (((uint32_t)0x01 << (22)) - 1), (((uint32_t)0x01 << (23)) - 1), (((uint32_t)0x01 << (24)) - 1), (((uint32_t)0x01 << (25)) - 1), (((uint32_t)0x01 << (26)) - 1), (((uint32_t)0x01 << (27)) - 1), (((uint32_t)0x01 << (28)) - 1), (((uint32_t)0x01 << (29)) - 1), (((uint32_t)0x01 << (30)) - 1), (((uint32_t)0x01 << (31)) - 1), ((uint32_t)0xFFFFFFFF), }; const uint16_t SAspectRatio[17][2] = { { 0, 0}, { 1, 1}, {12, 11}, {10, 11}, {16, 11}, {40, 33}, { 24, 11}, {20, 11}, {32, 11}, {80, 33}, {18, 11}, {15, 11}, {64, 33}, {160, 99}, {4, 3}, {3, 2}, {2, 1} }; const uint32_t SubWidthC[4] = { 1, 2, 2, 1 }; const uint32_t SubHeightC[4] = { 1, 2, 1, 1 }; const uint8_t default_intra_scaling_list4x4[16]= { 6, 13, 20, 28, 13, 20, 28, 32, 20, 28, 32, 37, 28, 32, 37, 42 }; const uint8_t default_inter_scaling_list4x4[16]= { 10, 14, 20, 24, 14, 20, 24, 27, 20, 24, 27, 30, 24, 27, 30, 34 }; const uint8_t default_intra_scaling_list8x8[64]= { 6, 10, 13, 16, 18, 23, 25, 27, 10, 11, 16, 18, 23, 25, 27, 29, 13, 16, 18, 23, 25, 27, 29, 31, 16, 18, 23, 25, 27, 29, 31, 33, 18, 23, 25, 27, 29, 31, 33, 36, 23, 25, 27, 29, 31, 33, 36, 38, 25, 27, 29, 31, 33, 36, 38, 40, 27, 29, 31, 33, 36, 38, 40, 42 }; const uint8_t default_inter_scaling_list8x8[64]= { 9, 13, 15, 17, 19, 21, 22, 24, 13, 13, 17, 19, 21, 22, 24, 25, 15, 17, 19, 21, 22, 24, 25, 27, 17, 19, 21, 22, 24, 25, 27, 28, 19, 21, 22, 24, 25, 27, 28, 30, 21, 22, 24, 25, 27, 28, 30, 32, 22, 24, 25, 27, 28, 30, 32, 33, 24, 25, 27, 28, 30, 32, 33, 35 }; H264BaseBitstream::H264BaseBitstream() { Reset(0, 0); } H264BaseBitstream::H264BaseBitstream(uint8_t * const pb, const uint32_t maxsize) { Reset(pb, maxsize); } H264BaseBitstream::~H264BaseBitstream() { } void H264BaseBitstream::Reset(uint8_t * const pb, const uint32_t maxsize) { m_pbs = (uint32_t*)pb; m_pbsBase = (uint32_t*)pb; m_bitOffset = 31; m_maxBsSize = maxsize; } // void Reset(uint8_t * const pb, const uint32_t maxsize) void H264BaseBitstream::Reset(uint8_t * const pb, int32_t offset, const uint32_t maxsize) { m_pbs = (uint32_t*)pb; m_pbsBase = (uint32_t*)pb; m_bitOffset = offset; m_maxBsSize = maxsize; } // void Reset(uint8_t * const pb, int32_t offset, const uint32_t maxsize) bool H264BaseBitstream::More_RBSP_Data() { int32_t code, tmp; uint32_t* ptr_state = m_pbs; int32_t bit_state = m_bitOffset; VM_ASSERT(m_bitOffset >= 0 && m_bitOffset <= 31); int32_t remaining_bytes = (int32_t)BytesLeft(); if (remaining_bytes <= 0) return false; // get top bit, it can be "rbsp stop" bit h264GetBits(m_pbs, m_bitOffset, 1, code); // get remain bits, which is less then byte tmp = (m_bitOffset + 1) % 8; if(tmp) { h264GetBits(m_pbs, m_bitOffset, tmp, code); if ((code << (8 - tmp)) & 0x7f) // most sig bit could be rbsp stop bit { m_pbs = ptr_state; m_bitOffset = bit_state; // there are more data return true; } } remaining_bytes = (int32_t)BytesLeft(); // run through remain bytes while (0 < remaining_bytes) { h264GetBits(m_pbs, m_bitOffset, 8, code); if (code) { m_pbs = ptr_state; m_bitOffset = bit_state; // there are more data return true; } remaining_bytes -= 1; } return false; } void H264BaseBitstream::GetOrg(uint32_t **pbs, uint32_t *size) { *pbs = m_pbsBase; *size = m_maxBsSize; } void H264BaseBitstream::GetState(uint32_t** pbs,uint32_t* bitOffset) { *pbs = m_pbs; *bitOffset = m_bitOffset; } void H264BaseBitstream::SetState(uint32_t* pbs,uint32_t bitOffset) { m_pbs = pbs; m_bitOffset = bitOffset; } void H264BaseBitstream::SetDecodedBytes(size_t nBytes) { m_pbs = m_pbsBase + (nBytes / 4); m_bitOffset = 31 - ((int32_t) ((nBytes % sizeof(uint32_t)) * 8)); } H264HeadersBitstream::H264HeadersBitstream() : H264BaseBitstream() { } H264HeadersBitstream::H264HeadersBitstream(uint8_t * const pb, const uint32_t maxsize) : H264BaseBitstream(pb, maxsize) { } inline bool CheckLevel(uint8_t level_idc) { switch(level_idc) { case H264VideoDecoderParams::H264_LEVEL_1: case H264VideoDecoderParams::H264_LEVEL_11: case H264VideoDecoderParams::H264_LEVEL_12: case H264VideoDecoderParams::H264_LEVEL_13: case H264VideoDecoderParams::H264_LEVEL_2: case H264VideoDecoderParams::H264_LEVEL_21: case H264VideoDecoderParams::H264_LEVEL_22: case H264VideoDecoderParams::H264_LEVEL_3: case H264VideoDecoderParams::H264_LEVEL_31: case H264VideoDecoderParams::H264_LEVEL_32: case H264VideoDecoderParams::H264_LEVEL_4: case H264VideoDecoderParams::H264_LEVEL_41: case H264VideoDecoderParams::H264_LEVEL_42: case H264VideoDecoderParams::H264_LEVEL_5: case H264VideoDecoderParams::H264_LEVEL_51: case H264VideoDecoderParams::H264_LEVEL_52: case H264VideoDecoderParams::H264_LEVEL_9: return true; default: return false; } } // --------------------------------------------------------------------------- // H264Bitstream::GetSequenceParamSet() // Read sequence parameter set data from bitstream. // --------------------------------------------------------------------------- Status H264HeadersBitstream::GetSequenceParamSet(H264SeqParamSet *sps) { // Not all members of the seq param set structure are contained in all // seq param sets. So start by init all to zero. Status ps = UMC_OK; sps->Reset(); // profile // TBD: add rejection of unsupported profile sps->profile_idc = (uint8_t)GetBits(8); switch (sps->profile_idc) { case H264VideoDecoderParams::H264_PROFILE_BASELINE: case H264VideoDecoderParams::H264_PROFILE_MAIN: case H264VideoDecoderParams::H264_PROFILE_SCALABLE_BASELINE: case H264VideoDecoderParams::H264_PROFILE_SCALABLE_HIGH: case H264VideoDecoderParams::H264_PROFILE_EXTENDED: case H264VideoDecoderParams::H264_PROFILE_HIGH: case H264VideoDecoderParams::H264_PROFILE_HIGH10: case H264VideoDecoderParams::H264_PROFILE_MULTIVIEW_HIGH: case H264VideoDecoderParams::H264_PROFILE_HIGH422: case H264VideoDecoderParams::H264_PROFILE_STEREO_HIGH: case H264VideoDecoderParams::H264_PROFILE_HIGH444: case H264VideoDecoderParams::H264_PROFILE_ADVANCED444_INTRA: case H264VideoDecoderParams::H264_PROFILE_ADVANCED444: case H264VideoDecoderParams::H264_PROFILE_HIGH444_PRED: case H264VideoDecoderParams::H264_PROFILE_CAVLC444_INTRA: break; default: return UMC_ERR_INVALID_STREAM; } sps->constraint_set0_flag = Get1Bit(); sps->constraint_set1_flag = Get1Bit(); sps->constraint_set2_flag = Get1Bit(); sps->constraint_set3_flag = Get1Bit(); sps->constraint_set4_flag = Get1Bit(); sps->constraint_set5_flag = Get1Bit(); // skip 2 zero bits GetBits(2); sps->level_idc = (uint8_t)GetBits(8); if (sps->level_idc == H264VideoDecoderParams::H264_LEVEL_UNKNOWN) sps->level_idc = H264VideoDecoderParams::H264_LEVEL_52; MFX_CHECK(CheckLevel(sps->level_idc), UMC_ERR_INVALID_STREAM); if (sps->level_idc == H264VideoDecoderParams::H264_LEVEL_9 && sps->profile_idc != H264VideoDecoderParams::H264_PROFILE_BASELINE && sps->profile_idc != H264VideoDecoderParams::H264_PROFILE_MAIN && sps->profile_idc != H264VideoDecoderParams::H264_PROFILE_EXTENDED) { sps->level_idc = H264VideoDecoderParams::H264_LEVEL_1b; } // id int32_t sps_id = GetVLCElement(false); if (sps_id > (int32_t)(MAX_NUM_SEQ_PARAM_SETS - 1)) { return UMC_ERR_INVALID_STREAM; } sps->seq_parameter_set_id = (uint8_t)sps_id; // see 7.3.2.1.1 "Sequence parameter set data syntax" // chapter of H264 standard for full list of profiles with chrominance if ((H264VideoDecoderParams::H264_PROFILE_SCALABLE_BASELINE == sps->profile_idc) || (H264VideoDecoderParams::H264_PROFILE_SCALABLE_HIGH == sps->profile_idc) || (H264VideoDecoderParams::H264_PROFILE_HIGH == sps->profile_idc) || (H264VideoDecoderParams::H264_PROFILE_HIGH10 == sps->profile_idc) || (H264VideoDecoderParams::H264_PROFILE_HIGH422 == sps->profile_idc) || (H264VideoDecoderParams::H264_PROFILE_MULTIVIEW_HIGH == sps->profile_idc) || (H264VideoDecoderParams::H264_PROFILE_STEREO_HIGH == sps->profile_idc) || /* what're these profiles ??? */ (H264VideoDecoderParams::H264_PROFILE_HIGH444 == sps->profile_idc) || (H264VideoDecoderParams::H264_PROFILE_HIGH444_PRED == sps->profile_idc) || (H264VideoDecoderParams::H264_PROFILE_CAVLC444_INTRA == sps->profile_idc)) { uint32_t chroma_format_idc = GetVLCElement(false); if (chroma_format_idc > 3) return UMC_ERR_INVALID_STREAM; sps->chroma_format_idc = (uint8_t)chroma_format_idc; if (sps->chroma_format_idc==3) { sps->residual_colour_transform_flag = Get1Bit(); } uint32_t bit_depth_luma = GetVLCElement(false) + 8; uint32_t bit_depth_chroma = GetVLCElement(false) + 8; if (bit_depth_luma > 16 || bit_depth_chroma > 16) return UMC_ERR_INVALID_STREAM; sps->bit_depth_luma = (uint8_t)bit_depth_luma; sps->bit_depth_chroma = (uint8_t)bit_depth_chroma; if (!chroma_format_idc) sps->bit_depth_chroma = sps->bit_depth_luma; VM_ASSERT(!sps->residual_colour_transform_flag); if (sps->residual_colour_transform_flag == 1) { return UMC_ERR_INVALID_STREAM; } sps->qpprime_y_zero_transform_bypass_flag = Get1Bit(); sps->seq_scaling_matrix_present_flag = Get1Bit(); if(sps->seq_scaling_matrix_present_flag) { // 0 if(Get1Bit()) { GetScalingList4x4(&sps->ScalingLists4x4[0],(uint8_t*)default_intra_scaling_list4x4,&sps->type_of_scaling_list_used[0]); } else { FillScalingList4x4(&sps->ScalingLists4x4[0],(uint8_t*) default_intra_scaling_list4x4); sps->type_of_scaling_list_used[0] = SCLDEFAULT; } // 1 if(Get1Bit()) { GetScalingList4x4(&sps->ScalingLists4x4[1],(uint8_t*) default_intra_scaling_list4x4,&sps->type_of_scaling_list_used[1]); } else { FillScalingList4x4(&sps->ScalingLists4x4[1],(uint8_t*) sps->ScalingLists4x4[0].ScalingListCoeffs); sps->type_of_scaling_list_used[1] = SCLDEFAULT; } // 2 if(Get1Bit()) { GetScalingList4x4(&sps->ScalingLists4x4[2],(uint8_t*) default_intra_scaling_list4x4,&sps->type_of_scaling_list_used[2]); } else { FillScalingList4x4(&sps->ScalingLists4x4[2],(uint8_t*) sps->ScalingLists4x4[1].ScalingListCoeffs); sps->type_of_scaling_list_used[2] = SCLDEFAULT; } // 3 if(Get1Bit()) { GetScalingList4x4(&sps->ScalingLists4x4[3],(uint8_t*)default_inter_scaling_list4x4,&sps->type_of_scaling_list_used[3]); } else { FillScalingList4x4(&sps->ScalingLists4x4[3],(uint8_t*) default_inter_scaling_list4x4); sps->type_of_scaling_list_used[3] = SCLDEFAULT; } // 4 if(Get1Bit()) { GetScalingList4x4(&sps->ScalingLists4x4[4],(uint8_t*) default_inter_scaling_list4x4,&sps->type_of_scaling_list_used[4]); } else { FillScalingList4x4(&sps->ScalingLists4x4[4],(uint8_t*) sps->ScalingLists4x4[3].ScalingListCoeffs); sps->type_of_scaling_list_used[4] = SCLDEFAULT; } // 5 if(Get1Bit()) { GetScalingList4x4(&sps->ScalingLists4x4[5],(uint8_t*) default_inter_scaling_list4x4,&sps->type_of_scaling_list_used[5]); } else { FillScalingList4x4(&sps->ScalingLists4x4[5],(uint8_t*) sps->ScalingLists4x4[4].ScalingListCoeffs); sps->type_of_scaling_list_used[5] = SCLDEFAULT; } // 0 if(Get1Bit()) { GetScalingList8x8(&sps->ScalingLists8x8[0],(uint8_t*)default_intra_scaling_list8x8,&sps->type_of_scaling_list_used[6]); } else { FillScalingList8x8(&sps->ScalingLists8x8[0],(uint8_t*) default_intra_scaling_list8x8); sps->type_of_scaling_list_used[6] = SCLDEFAULT; } // 1 if(Get1Bit()) { GetScalingList8x8(&sps->ScalingLists8x8[1],(uint8_t*) default_inter_scaling_list8x8,&sps->type_of_scaling_list_used[7]); } else { FillScalingList8x8(&sps->ScalingLists8x8[1],(uint8_t*) default_inter_scaling_list8x8); sps->type_of_scaling_list_used[7] = SCLDEFAULT; } } else { int32_t i; for (i = 0; i < 6; i += 1) { FillFlatScalingList4x4(&sps->ScalingLists4x4[i]); } for (i = 0; i < 2; i += 1) { FillFlatScalingList8x8(&sps->ScalingLists8x8[i]); } } } else { sps->chroma_format_idc = 1; sps->bit_depth_luma = 8; sps->bit_depth_chroma = 8; SetDefaultScalingLists(sps); } // log2 max frame num (bitstream contains value - 4) uint32_t log2_max_frame_num = GetVLCElement(false) + 4; sps->log2_max_frame_num = (uint8_t)log2_max_frame_num; if (log2_max_frame_num > 16 || log2_max_frame_num < 4) return UMC_ERR_INVALID_STREAM; // pic order cnt type (0..2) uint32_t pic_order_cnt_type = GetVLCElement(false); sps->pic_order_cnt_type = (uint8_t)pic_order_cnt_type; if (pic_order_cnt_type > 2) { return UMC_ERR_INVALID_STREAM; } if (sps->pic_order_cnt_type == 0) { // log2 max pic order count lsb (bitstream contains value - 4) uint32_t log2_max_pic_order_cnt_lsb = GetVLCElement(false) + 4; sps->log2_max_pic_order_cnt_lsb = (uint8_t)log2_max_pic_order_cnt_lsb; if (log2_max_pic_order_cnt_lsb > 16 || log2_max_pic_order_cnt_lsb < 4) return UMC_ERR_INVALID_STREAM; sps->MaxPicOrderCntLsb = (1 << sps->log2_max_pic_order_cnt_lsb); } else if (sps->pic_order_cnt_type == 1) { sps->delta_pic_order_always_zero_flag = Get1Bit(); sps->offset_for_non_ref_pic = GetVLCElement(true); sps->offset_for_top_to_bottom_field = GetVLCElement(true); sps->num_ref_frames_in_pic_order_cnt_cycle = GetVLCElement(false); if (sps->num_ref_frames_in_pic_order_cnt_cycle > 255) return UMC_ERR_INVALID_STREAM; // get offsets for (uint32_t i = 0; i < sps->num_ref_frames_in_pic_order_cnt_cycle; i++) { sps->poffset_for_ref_frame[i] = GetVLCElement(true); } } // pic order count type 1 // num ref frames sps->num_ref_frames = GetVLCElement(false); if (sps->num_ref_frames > 16) return UMC_ERR_INVALID_STREAM; sps->gaps_in_frame_num_value_allowed_flag = Get1Bit(); // picture width in MBs (bitstream contains value - 1) sps->frame_width_in_mbs = GetVLCElement(false) + 1; // picture height in MBs (bitstream contains value - 1) sps->frame_height_in_mbs = GetVLCElement(false) + 1; if (!(sps->frame_width_in_mbs * 16 < USHRT_MAX) || !(sps->frame_height_in_mbs * 16 < USHRT_MAX)) return UMC_ERR_INVALID_STREAM; sps->frame_mbs_only_flag = Get1Bit(); sps->frame_height_in_mbs = (2-sps->frame_mbs_only_flag)*sps->frame_height_in_mbs; if (sps->frame_mbs_only_flag == 0) { sps->mb_adaptive_frame_field_flag = Get1Bit(); } sps->direct_8x8_inference_flag = Get1Bit(); if (sps->frame_mbs_only_flag==0) { sps->direct_8x8_inference_flag = 1; } sps->frame_cropping_flag = Get1Bit(); if (sps->frame_cropping_flag) { sps->frame_cropping_rect_left_offset = GetVLCElement(false); sps->frame_cropping_rect_right_offset = GetVLCElement(false); sps->frame_cropping_rect_top_offset = GetVLCElement(false); sps->frame_cropping_rect_bottom_offset = GetVLCElement(false); // check cropping parameters int32_t cropX = SubWidthC[sps->chroma_format_idc] * sps->frame_cropping_rect_left_offset; int32_t cropY = SubHeightC[sps->chroma_format_idc] * sps->frame_cropping_rect_top_offset * (2 - sps->frame_mbs_only_flag); int32_t cropH = sps->frame_height_in_mbs * 16 - SubHeightC[sps->chroma_format_idc]*(2 - sps->frame_mbs_only_flag) * (sps->frame_cropping_rect_top_offset + sps->frame_cropping_rect_bottom_offset); int32_t cropW = sps->frame_width_in_mbs * 16 - SubWidthC[sps->chroma_format_idc] * (sps->frame_cropping_rect_left_offset + sps->frame_cropping_rect_right_offset); if (cropX < 0 || cropY < 0 || cropW < 0 || cropH < 0) return UMC_ERR_INVALID_STREAM; if (cropX > (int32_t)sps->frame_width_in_mbs * 16) return UMC_ERR_INVALID_STREAM; if (cropY > (int32_t)sps->frame_height_in_mbs * 16) return UMC_ERR_INVALID_STREAM; if (cropX + cropW > (int32_t)sps->frame_width_in_mbs * 16) return UMC_ERR_INVALID_STREAM; if (cropY + cropH > (int32_t)sps->frame_height_in_mbs * 16) return UMC_ERR_INVALID_STREAM; } // don't need else because we zeroid structure CheckBSLeft(); sps->vui_parameters_present_flag = Get1Bit(); if (sps->vui_parameters_present_flag) { H264VUI vui; Status vui_ps = GetVUIParam(sps, &vui); if (vui_ps == UMC_OK && IsBSLeft()) { sps->vui = vui; } } return ps; } // GetSequenceParamSet Status H264HeadersBitstream::GetVUIParam(H264SeqParamSet *sps, H264VUI *vui) { Status ps = UMC_OK; vui->Reset(); vui->aspect_ratio_info_present_flag = Get1Bit(); vui->sar_width = 1; // default values vui->sar_height = 1; if (vui->aspect_ratio_info_present_flag) { vui->aspect_ratio_idc = (uint8_t) GetBits(8); if (vui->aspect_ratio_idc == 255) { vui->sar_width = (uint16_t) GetBits(16); vui->sar_height = (uint16_t) GetBits(16); } else { if (!vui->aspect_ratio_idc || vui->aspect_ratio_idc >= sizeof(SAspectRatio)/sizeof(SAspectRatio[0])) { vui->aspect_ratio_info_present_flag = 0; } else { vui->sar_width = SAspectRatio[vui->aspect_ratio_idc][0]; vui->sar_height = SAspectRatio[vui->aspect_ratio_idc][1]; } } } vui->overscan_info_present_flag = Get1Bit(); if (vui->overscan_info_present_flag) vui->overscan_appropriate_flag = Get1Bit(); vui->video_signal_type_present_flag = Get1Bit(); if( vui->video_signal_type_present_flag ) { vui->video_format = (uint8_t) GetBits(3); vui->video_full_range_flag = Get1Bit(); vui->colour_description_present_flag = Get1Bit(); if( vui->colour_description_present_flag ) { vui->colour_primaries = (uint8_t) GetBits(8); vui->transfer_characteristics = (uint8_t) GetBits(8); vui->matrix_coefficients = (uint8_t) GetBits(8); } } vui->chroma_loc_info_present_flag = Get1Bit(); if( vui->chroma_loc_info_present_flag ) { vui->chroma_sample_loc_type_top_field = (uint8_t) GetVLCElement(false); vui->chroma_sample_loc_type_bottom_field = (uint8_t) GetVLCElement(false); } vui->timing_info_present_flag = Get1Bit(); if (vui->timing_info_present_flag) { vui->num_units_in_tick = GetBits(32); vui->time_scale = GetBits(32); vui->fixed_frame_rate_flag = Get1Bit(); if (!vui->num_units_in_tick || !vui->time_scale) vui->timing_info_present_flag = 0; } vui->nal_hrd_parameters_present_flag = Get1Bit(); if( vui->nal_hrd_parameters_present_flag ) ps=GetHRDParam(sps, vui); vui->vcl_hrd_parameters_present_flag = Get1Bit(); if( vui->vcl_hrd_parameters_present_flag ) ps=GetHRDParam(sps, vui); if( vui->nal_hrd_parameters_present_flag || vui->vcl_hrd_parameters_present_flag ) vui->low_delay_hrd_flag = Get1Bit(); vui->pic_struct_present_flag = Get1Bit(); vui->bitstream_restriction_flag = Get1Bit(); if( vui->bitstream_restriction_flag ) { vui->motion_vectors_over_pic_boundaries_flag = Get1Bit(); vui->max_bytes_per_pic_denom = (uint8_t) GetVLCElement(false); vui->max_bits_per_mb_denom = (uint8_t) GetVLCElement(false); vui->log2_max_mv_length_horizontal = (uint8_t) GetVLCElement(false); vui->log2_max_mv_length_vertical = (uint8_t) GetVLCElement(false); vui->num_reorder_frames = (uint8_t) GetVLCElement(false); int32_t value = GetVLCElement(false); if (value < (int32_t)sps->num_ref_frames || value < 0) { return UMC_ERR_INVALID_STREAM; } vui->max_dec_frame_buffering = (uint8_t)value; if (vui->max_dec_frame_buffering > 16) { return UMC_ERR_INVALID_STREAM; } } return ps; } Status H264HeadersBitstream::GetHRDParam(H264SeqParamSet *, H264VUI *vui) { uint32_t cpb_cnt = (uint32_t) (GetVLCElement(false) + 1); if (cpb_cnt >= 32) { return UMC_ERR_INVALID_STREAM; } vui->cpb_cnt = (uint8_t)cpb_cnt; vui->bit_rate_scale = (uint8_t) GetBits(4); vui->cpb_size_scale = (uint8_t) GetBits(4); for( int32_t idx= 0; idx < vui->cpb_cnt; idx++ ) { vui->bit_rate_value[ idx ] = (uint32_t) (GetVLCElement(false)+1); vui->cpb_size_value[ idx ] = (uint32_t) ((GetVLCElement(false)+1)); vui->cbr_flag[ idx ] = Get1Bit(); } vui->initial_cpb_removal_delay_length = (uint8_t)(GetBits(5)+1); vui->cpb_removal_delay_length = (uint8_t)(GetBits(5)+1); vui->dpb_output_delay_length = (uint8_t) (GetBits(5)+1); vui->time_offset_length = (uint8_t) GetBits(5); return UMC_OK; } // --------------------------------------------------------------------------- // Read sequence parameter set extension data from bitstream. // --------------------------------------------------------------------------- Status H264HeadersBitstream::GetSequenceParamSetExtension(H264SeqParamSetExtension *sps_ex) { sps_ex->Reset(); uint32_t seq_parameter_set_id = GetVLCElement(false); sps_ex->seq_parameter_set_id = (uint8_t)seq_parameter_set_id; if (seq_parameter_set_id > MAX_NUM_SEQ_PARAM_SETS-1) { return UMC_ERR_INVALID_STREAM; } uint32_t aux_format_idc = GetVLCElement(false); sps_ex->aux_format_idc = (uint8_t)aux_format_idc; if (aux_format_idc > 3) { return UMC_ERR_INVALID_STREAM; } if (sps_ex->aux_format_idc != 1 && sps_ex->aux_format_idc != 2) sps_ex->aux_format_idc = 0; if (sps_ex->aux_format_idc) { uint32_t bit_depth_aux = GetVLCElement(false) + 8; sps_ex->bit_depth_aux = (uint8_t)bit_depth_aux; if (bit_depth_aux > 12) { return UMC_ERR_INVALID_STREAM; } sps_ex->alpha_incr_flag = Get1Bit(); sps_ex->alpha_opaque_value = (uint8_t)GetBits(sps_ex->bit_depth_aux + 1); sps_ex->alpha_transparent_value = (uint8_t)GetBits(sps_ex->bit_depth_aux + 1); } sps_ex->additional_extension_flag = Get1Bit(); CheckBSLeft(); return UMC_OK; } // GetSequenceParamSetExtension template <class num_t, class items_t> static Status DecodeViewReferenceInfo(num_t &numItems, items_t *pItems, H264HeadersBitstream &bitStream) { uint32_t j; // decode number of items numItems = (num_t) bitStream.GetVLCElement(false); if (H264_MAX_NUM_VIEW_REF <= numItems) { return UMC_ERR_INVALID_STREAM; } // decode items for (j = 0; j < numItems; j += 1) { pItems[j] = (items_t) bitStream.GetVLCElement(false); if (H264_MAX_NUM_VIEW <= pItems[j]) { return UMC_ERR_INVALID_STREAM; } } return UMC_OK; } // Status DecodeViewReferenceInfo(num_t &numItems, items_t *pItems, H264HeadersBitstream &bitStream) Status H264HeadersBitstream::GetSequenceParamSetSvcExt(H264SeqParamSetSVCExtension *pSPSSvcExt) { pSPSSvcExt->Reset(); if ((pSPSSvcExt->profile_idc != H264VideoDecoderParams::H264_PROFILE_SCALABLE_BASELINE) && (pSPSSvcExt->profile_idc != H264VideoDecoderParams::H264_PROFILE_SCALABLE_HIGH)) return UMC_OK; pSPSSvcExt->inter_layer_deblocking_filter_control_present_flag = Get1Bit(); pSPSSvcExt->extended_spatial_scalability = (uint8_t)GetBits(2); if (pSPSSvcExt->chroma_format_idc == 1 || pSPSSvcExt->chroma_format_idc == 2) { pSPSSvcExt->chroma_phase_x = Get1Bit() - 1; pSPSSvcExt->seq_ref_layer_chroma_phase_x = pSPSSvcExt->chroma_phase_x; } if (pSPSSvcExt->chroma_format_idc == 1) { pSPSSvcExt->chroma_phase_y = (int8_t)(GetBits(2) - 1); pSPSSvcExt->seq_ref_layer_chroma_phase_y = pSPSSvcExt->chroma_phase_y; } if (pSPSSvcExt->extended_spatial_scalability == 1) { if (pSPSSvcExt->chroma_format_idc > 0) { pSPSSvcExt->seq_ref_layer_chroma_phase_x = Get1Bit() - 1; pSPSSvcExt->seq_ref_layer_chroma_phase_y = (int8_t)(GetBits(2) - 1); } pSPSSvcExt->seq_scaled_ref_layer_left_offset = GetVLCElement(true); pSPSSvcExt->seq_scaled_ref_layer_top_offset = GetVLCElement(true); pSPSSvcExt->seq_scaled_ref_layer_right_offset = GetVLCElement(true); pSPSSvcExt->seq_scaled_ref_layer_bottom_offset = GetVLCElement(true); } pSPSSvcExt->seq_tcoeff_level_prediction_flag = Get1Bit(); if (pSPSSvcExt->seq_tcoeff_level_prediction_flag) { pSPSSvcExt->adaptive_tcoeff_level_prediction_flag = Get1Bit(); } pSPSSvcExt->slice_header_restriction_flag = Get1Bit(); CheckBSLeft(); /* Reference has SVC VUI extension here, but there is no mention about it in standard */ uint32_t svc_vui_parameters_present_flag = Get1Bit(); if (svc_vui_parameters_present_flag) { GetSequenceParamSetSvcVuiExt(pSPSSvcExt); // ignore return status } Get1Bit(); // additional_extension2_flag return UMC_OK; } struct VUI_Entry { uint32_t vui_ext_dependency_id; uint32_t vui_ext_quality_id; uint32_t vui_ext_temporal_id; uint32_t vui_ext_timing_info_present_flag; uint32_t vui_ext_num_units_in_tick; uint32_t vui_ext_time_scale; uint32_t vui_ext_fixed_frame_rate_flag; uint32_t vui_ext_nal_hrd_parameters_present_flag; uint32_t vui_ext_vcl_hrd_parameters_present_flag; uint32_t vui_ext_low_delay_hrd_flag; uint32_t vui_ext_pic_struct_present_flag; }; struct SVC_VUI { uint32_t vui_ext_num_entries; VUI_Entry vui_entry[1023]; }; Status H264HeadersBitstream::GetSequenceParamSetSvcVuiExt(H264SeqParamSetSVCExtension *pSPSSvcExt) { SVC_VUI vui; vui.vui_ext_num_entries = GetVLCElement(false) + 1; for(uint32_t i = 0; i < vui.vui_ext_num_entries; i++) { vui.vui_entry[i].vui_ext_dependency_id = GetBits(3); vui.vui_entry[i].vui_ext_quality_id = GetBits(4); vui.vui_entry[i].vui_ext_temporal_id = GetBits(3); vui.vui_entry[i].vui_ext_timing_info_present_flag = Get1Bit(); if (vui.vui_entry[i].vui_ext_timing_info_present_flag) { vui.vui_entry[i].vui_ext_num_units_in_tick = GetBits(32); vui.vui_entry[i].vui_ext_time_scale = GetBits(32); vui.vui_entry[i].vui_ext_fixed_frame_rate_flag = Get1Bit(); } vui.vui_entry[i].vui_ext_nal_hrd_parameters_present_flag = Get1Bit(); if (vui.vui_entry[i].vui_ext_nal_hrd_parameters_present_flag) { Status sts = GetHRDParam(pSPSSvcExt, &pSPSSvcExt->vui); if (sts != UMC_OK) return sts; } vui.vui_entry[i].vui_ext_vcl_hrd_parameters_present_flag = Get1Bit(); if (vui.vui_entry[i].vui_ext_vcl_hrd_parameters_present_flag) { Status sts = GetHRDParam(pSPSSvcExt, &pSPSSvcExt->vui); if (sts != UMC_OK) return sts; } if (vui.vui_entry[i].vui_ext_nal_hrd_parameters_present_flag || vui.vui_entry[i].vui_ext_vcl_hrd_parameters_present_flag) vui.vui_entry[i].vui_ext_low_delay_hrd_flag = Get1Bit(); vui.vui_entry[i].vui_ext_pic_struct_present_flag = Get1Bit(); } return UMC_OK; } Status H264HeadersBitstream::GetSequenceParamSetMvcExt(H264SeqParamSetMVCExtension *pSPSMvcExt) { pSPSMvcExt->Reset(); // decode the number of available views pSPSMvcExt->num_views_minus1 = GetVLCElement(false); if (H264_MAX_NUM_VIEW <= pSPSMvcExt->num_views_minus1) { return UMC_ERR_INVALID_STREAM; } // allocate the views' info structs pSPSMvcExt->viewInfo.resize(pSPSMvcExt->num_views_minus1 + 1, H264ViewRefInfo()); // parse view IDs for (uint32_t i = 0; i <= pSPSMvcExt->num_views_minus1; i += 1) { H264ViewRefInfo &viewRefInfo = pSPSMvcExt->viewInfo[i]; // get the view ID viewRefInfo.view_id = GetVLCElement(false); if (H264_MAX_NUM_VIEW <= viewRefInfo.view_id) { return UMC_ERR_INVALID_STREAM; } } // parse anchor refs for (uint32_t i = 1; i <= pSPSMvcExt->num_views_minus1; i += 1) { H264ViewRefInfo &viewRefInfo = pSPSMvcExt->viewInfo[i]; uint32_t listNum; for (listNum = LIST_0; listNum <= LIST_1; listNum += 1) { // decode LX anchor refs info Status umcRes = DecodeViewReferenceInfo(viewRefInfo.num_anchor_refs_lx[listNum], viewRefInfo.anchor_refs_lx[listNum], *this); if (UMC_OK != umcRes) { return umcRes; } } } // parse non-anchor refs for (uint32_t i = 1; i <= pSPSMvcExt->num_views_minus1; i += 1) { H264ViewRefInfo &viewRefInfo = pSPSMvcExt->viewInfo[i]; uint32_t listNum; for (listNum = LIST_0; listNum <= LIST_1; listNum += 1) { // decode L0 non-anchor refs info Status umcRes = DecodeViewReferenceInfo(viewRefInfo.num_non_anchor_refs_lx[listNum], viewRefInfo.non_anchor_refs_lx[listNum], *this); if (UMC_OK != umcRes) { return umcRes; } } } // decode the number of applicable signal points pSPSMvcExt->num_level_values_signalled_minus1 = GetVLCElement(false); if (H264_MAX_NUM_OPS <= pSPSMvcExt->num_level_values_signalled_minus1) { return UMC_ERR_INVALID_STREAM; } // allocate the level info structure pSPSMvcExt->levelInfo.resize(pSPSMvcExt->num_level_values_signalled_minus1 + 1, H264LevelValueSignaled()); // decode all ops for (uint32_t i = 0; i <= pSPSMvcExt->num_level_values_signalled_minus1; i += 1) { H264LevelValueSignaled &levelInfo = pSPSMvcExt->levelInfo[i]; uint32_t j; // decode the level's profile idc levelInfo.level_idc = (uint8_t) GetBits(8); MFX_CHECK(CheckLevel(levelInfo.level_idc), UMC_ERR_INVALID_STREAM); // decode the number of operation points levelInfo.num_applicable_ops_minus1 = (uint16_t) GetVLCElement(false); if (H264_MAX_NUM_VIEW <= levelInfo.num_applicable_ops_minus1) { return UMC_ERR_INVALID_STREAM; } // allocate the operation points structures levelInfo.opsInfo.resize(levelInfo.num_applicable_ops_minus1 + 1, H264ApplicableOp()); // decode operation points for (j = 0; j <= levelInfo.num_applicable_ops_minus1; j += 1) { H264ApplicableOp &op = levelInfo.opsInfo[j]; uint32_t k; // decode the temporal ID of the op op.applicable_op_temporal_id = (uint8_t) GetBits(3); // decode the number of target views op.applicable_op_num_target_views_minus1 = (uint16_t) GetVLCElement(false); if (H264_MAX_NUM_VIEW <= op.applicable_op_num_target_views_minus1) { return UMC_ERR_INVALID_STREAM; } // allocate the target view ID array op.applicable_op_target_view_id.resize(op.applicable_op_num_target_views_minus1 + 1, 0); // read target view IDs for (k = 0; k <= op.applicable_op_num_target_views_minus1; k += 1) { op.applicable_op_target_view_id[k] = (uint16_t) GetVLCElement(false); if (H264_MAX_NUM_VIEW <= op.applicable_op_target_view_id[k]) { return UMC_ERR_INVALID_STREAM; } } // decode applicable number of views op.applicable_op_num_views_minus1 = (uint16_t) GetVLCElement(false); if (H264_MAX_NUM_VIEW <= op.applicable_op_num_views_minus1) { return UMC_ERR_INVALID_STREAM; } } } CheckBSLeft(); return UMC_OK; } // Status H264HeadersBitstream::GetSequenceParamSetMvcExt(H264SeqParamSetMVCExtension *pSPSMvcExt) Status H264HeadersBitstream::GetPictureParamSetPart1(H264PicParamSet *pps) { // Not all members of the pic param set structure are contained in all // pic param sets. So start by init all to zero. pps->Reset(); // id uint32_t pic_parameter_set_id = GetVLCElement(false); pps->pic_parameter_set_id = (uint16_t)pic_parameter_set_id; if (pic_parameter_set_id > MAX_NUM_PIC_PARAM_SETS-1) { return UMC_ERR_INVALID_STREAM; } // seq param set referred to by this pic param set uint32_t seq_parameter_set_id = GetVLCElement(false); pps->seq_parameter_set_id = (uint8_t)seq_parameter_set_id; if (seq_parameter_set_id > MAX_NUM_SEQ_PARAM_SETS-1) { return UMC_ERR_INVALID_STREAM; } CheckBSLeft(); return UMC_OK; } // GetPictureParamSetPart1 // Number of bits required to code slice group ID, index is num_slice_groups - 2 static const uint8_t SGIdBits[7] = {1,2,2,3,3,3,3}; // --------------------------------------------------------------------------- // Read picture parameter set data from bitstream. // --------------------------------------------------------------------------- Status H264HeadersBitstream::GetPictureParamSetPart2(H264PicParamSet *pps, H264SeqParamSet const* sps) { if (!sps) return UMC_ERR_NULL_PTR; pps->entropy_coding_mode = Get1Bit(); pps->bottom_field_pic_order_in_frame_present_flag = Get1Bit(); // number of slice groups, bitstream has value - 1 pps->num_slice_groups = GetVLCElement(false) + 1; if (pps->num_slice_groups != 1) { if (pps->num_slice_groups > MAX_NUM_SLICE_GROUPS) { return UMC_ERR_INVALID_STREAM; } uint32_t slice_group_map_type = GetVLCElement(false); pps->SliceGroupInfo.slice_group_map_type = (uint8_t)slice_group_map_type; if (slice_group_map_type > 6) return UMC_ERR_INVALID_STREAM; uint32_t const PicSizeInMapUnits = sps->frame_width_in_mbs * sps->frame_height_in_mbs; // Get additional, map type dependent slice group data switch (pps->SliceGroupInfo.slice_group_map_type) { case 0: for (uint32_t slice_group = 0; slice_group < pps->num_slice_groups; slice_group++) { // run length, bitstream has value - 1 pps->SliceGroupInfo.run_length[slice_group] = GetVLCElement(false) + 1; if (pps->SliceGroupInfo.run_length[slice_group] > PicSizeInMapUnits) return UMC_ERR_INVALID_STREAM; } break; case 1: // no additional info break; case 2: for (uint32_t slice_group = 0; slice_group < (uint32_t)(pps->num_slice_groups-1); slice_group++) { pps->SliceGroupInfo.t1.top_left[slice_group] = GetVLCElement(false); if (pps->SliceGroupInfo.t1.top_left[slice_group] >= PicSizeInMapUnits) return UMC_ERR_INVALID_STREAM; pps->SliceGroupInfo.t1.bottom_right[slice_group] = GetVLCElement(false); if (pps->SliceGroupInfo.t1.bottom_right[slice_group] >= PicSizeInMapUnits) return UMC_ERR_INVALID_STREAM; // check for legal values if (pps->SliceGroupInfo.t1.top_left[slice_group] > pps->SliceGroupInfo.t1.bottom_right[slice_group]) { return UMC_ERR_INVALID_STREAM; } } break; case 3: case 4: case 5: // For map types 3..5, number of slice groups must be 2 if (pps->num_slice_groups != 2) { return UMC_ERR_INVALID_STREAM; } pps->SliceGroupInfo.t2.slice_group_change_direction_flag = Get1Bit(); pps->SliceGroupInfo.t2.slice_group_change_rate = GetVLCElement(false) + 1; if (pps->SliceGroupInfo.t2.slice_group_change_rate > PicSizeInMapUnits) return UMC_ERR_INVALID_STREAM; break; case 6: // mapping of slice group to map unit (macroblock if not fields) is // per map unit, read from bitstream { // number of map units, bitstream has value - 1 pps->SliceGroupInfo.t3.pic_size_in_map_units = GetVLCElement(false) + 1; if (pps->SliceGroupInfo.t3.pic_size_in_map_units != PicSizeInMapUnits) return UMC_ERR_INVALID_STREAM; uint32_t const len = std::max(1u, pps->SliceGroupInfo.t3.pic_size_in_map_units); pps->SliceGroupInfo.pSliceGroupIDMap.resize(len); // num_bits is Ceil(log2(num_groups)) - number of bits used to code each slice group id uint32_t const num_bits = SGIdBits[pps->num_slice_groups - 2]; for (uint32_t map_unit = 0; map_unit < pps->SliceGroupInfo.t3.pic_size_in_map_units; map_unit++) { uint8_t const slice_group_id = (uint8_t)GetBits(num_bits); if (slice_group_id > pps->num_slice_groups - 1) return UMC_ERR_INVALID_STREAM; pps->SliceGroupInfo.pSliceGroupIDMap[map_unit] = slice_group_id; } } break; default: return UMC_ERR_INVALID_STREAM; } // switch } // slice group info // number of list 0 ref pics used to decode picture, bitstream has value - 1 pps->num_ref_idx_l0_active = GetVLCElement(false) + 1; // number of list 1 ref pics used to decode picture, bitstream has value - 1 pps->num_ref_idx_l1_active = GetVLCElement(false) + 1; if (pps->num_ref_idx_l1_active > MAX_NUM_REF_FRAMES || pps->num_ref_idx_l0_active > MAX_NUM_REF_FRAMES) return UMC_ERR_INVALID_STREAM; // weighted pediction pps->weighted_pred_flag = Get1Bit(); pps->weighted_bipred_idc = (uint8_t)GetBits(2); // default slice QP, bitstream has value - 26 int32_t pic_init_qp = GetVLCElement(true) + 26; pps->pic_init_qp = (int8_t)pic_init_qp; if (pic_init_qp > QP_MAX) { //return UMC_ERR_INVALID_STREAM; } // default SP/SI slice QP, bitstream has value - 26 pps->pic_init_qs = (uint8_t)(GetVLCElement(true) + 26); if (pps->pic_init_qs > QP_MAX) { //return UMC_ERR_INVALID_STREAM; } pps->chroma_qp_index_offset[0] = (int8_t)GetVLCElement(true); if ((pps->chroma_qp_index_offset[0] < -12) || (pps->chroma_qp_index_offset[0] > 12)) { //return UMC_ERR_INVALID_STREAM; } pps->deblocking_filter_variables_present_flag = Get1Bit(); pps->constrained_intra_pred_flag = Get1Bit(); pps->redundant_pic_cnt_present_flag = Get1Bit(); if (More_RBSP_Data()) { pps->transform_8x8_mode_flag = Get1Bit(); pps->pic_scaling_matrix_present_flag = Get1Bit(); H264ScalingPicParams * scaling = &pps->scaling[0]; if (pps->pic_scaling_matrix_present_flag) { for (int32_t i = 0; i < 3; i++) { pps->pic_scaling_list_present_flag[i] = Get1Bit(); if (pps->pic_scaling_list_present_flag[i]) { GetScalingList4x4(&scaling->ScalingLists4x4[i], (uint8_t*)default_intra_scaling_list4x4, &pps->type_of_scaling_list_used[i]); } else { pps->type_of_scaling_list_used[i] = SCLDEFAULT; } } for (int32_t i = 3; i < 6; i++) { pps->pic_scaling_list_present_flag[i] = Get1Bit(); if (pps->pic_scaling_list_present_flag[i]) { GetScalingList4x4(&scaling->ScalingLists4x4[i], (uint8_t*)default_inter_scaling_list4x4, &pps->type_of_scaling_list_used[i]); } else { pps->type_of_scaling_list_used[i] = SCLDEFAULT; } } if (pps->transform_8x8_mode_flag) { pps->pic_scaling_list_present_flag[6] = Get1Bit(); if (pps->pic_scaling_list_present_flag[6]) { GetScalingList8x8(&scaling->ScalingLists8x8[0], (uint8_t*)default_intra_scaling_list8x8, &pps->type_of_scaling_list_used[6]); } else { pps->type_of_scaling_list_used[6] = SCLDEFAULT; } pps->pic_scaling_list_present_flag[7] = Get1Bit(); if (pps->pic_scaling_list_present_flag[7]) { GetScalingList8x8(&scaling->ScalingLists8x8[1], (uint8_t*)default_inter_scaling_list8x8, &pps->type_of_scaling_list_used[7]); } else { pps->type_of_scaling_list_used[7] = SCLDEFAULT; } } MFX_INTERNAL_CPY(&pps->scaling[1], &pps->scaling[0], sizeof(H264ScalingPicParams)); } pps->chroma_qp_index_offset[1] = (int8_t)GetVLCElement(true); } else { pps->chroma_qp_index_offset[1] = pps->chroma_qp_index_offset[0]; } CheckBSLeft(); return UMC_OK; } // GetPictureParamSet Status InitializePictureParamSet(H264PicParamSet *pps, const H264SeqParamSet *sps, bool isExtension) { if (!pps || !sps || pps->initialized[isExtension]) return UMC_OK; if (pps->num_slice_groups != 1) { uint32_t PicSizeInMapUnits = sps->frame_width_in_mbs * sps->frame_height_in_mbs; // for range checks // Get additional, map type dependent slice group data switch (pps->SliceGroupInfo.slice_group_map_type) { case 0: for (uint32_t slice_group=0; slice_group<pps->num_slice_groups; slice_group++) { if (pps->SliceGroupInfo.run_length[slice_group] > PicSizeInMapUnits) { return UMC_ERR_INVALID_STREAM; } } break; case 1: // no additional info break; case 2: for (uint32_t slice_group=0; slice_group<(uint32_t)(pps->num_slice_groups-1); slice_group++) { if (pps->SliceGroupInfo.t1.bottom_right[slice_group] >= PicSizeInMapUnits) { return UMC_ERR_INVALID_STREAM; } if ((pps->SliceGroupInfo.t1.top_left[slice_group] % sps->frame_width_in_mbs) > (pps->SliceGroupInfo.t1.bottom_right[slice_group] % sps->frame_width_in_mbs)) { return UMC_ERR_INVALID_STREAM; } } break; case 3: case 4: case 5: if (pps->SliceGroupInfo.t2.slice_group_change_rate > PicSizeInMapUnits) { return UMC_ERR_INVALID_STREAM; } break; case 6: // mapping of slice group to map unit (macroblock if not fields) is // per map unit, read from bitstream { if (pps->SliceGroupInfo.t3.pic_size_in_map_units != PicSizeInMapUnits) { return UMC_ERR_INVALID_STREAM; } for (uint32_t map_unit = 0; map_unit < pps->SliceGroupInfo.t3.pic_size_in_map_units; map_unit++) { if (pps->SliceGroupInfo.pSliceGroupIDMap[map_unit] > pps->num_slice_groups - 1) { return UMC_ERR_INVALID_STREAM; } } } break; default: return UMC_ERR_INVALID_STREAM; } // switch } // slice group info H264ScalingPicParams * scaling = &pps->scaling[isExtension]; if (pps->pic_scaling_matrix_present_flag) { uint8_t *default_scaling = (uint8_t*)default_intra_scaling_list4x4; for (int32_t i = 0; i < 6; i += 3) { if (!pps->pic_scaling_list_present_flag[i]) { if (sps->seq_scaling_matrix_present_flag) { FillScalingList4x4(&scaling->ScalingLists4x4[i], (uint8_t*)sps->ScalingLists4x4[i].ScalingListCoeffs); } else { FillScalingList4x4(&scaling->ScalingLists4x4[i], (uint8_t*)default_scaling); } } if (!pps->pic_scaling_list_present_flag[i+1]) { FillScalingList4x4(&scaling->ScalingLists4x4[i+1], (uint8_t*)scaling->ScalingLists4x4[i].ScalingListCoeffs); } if (!pps->pic_scaling_list_present_flag[i+2]) { FillScalingList4x4(&scaling->ScalingLists4x4[i+2], (uint8_t*)scaling->ScalingLists4x4[i+1].ScalingListCoeffs); } default_scaling = (uint8_t*)default_inter_scaling_list4x4; } if (pps->transform_8x8_mode_flag) { if (sps->seq_scaling_matrix_present_flag) { for (int32_t i = 6; i < 8; i++) { if (!pps->pic_scaling_list_present_flag[i]) { FillScalingList8x8(&scaling->ScalingLists8x8[i-6], (uint8_t*)sps->ScalingLists8x8[i-6].ScalingListCoeffs); } } } else { if (!pps->pic_scaling_list_present_flag[6]) { FillScalingList8x8(&scaling->ScalingLists8x8[0], (uint8_t*)default_intra_scaling_list8x8); } if (!pps->pic_scaling_list_present_flag[7]) { FillScalingList8x8(&scaling->ScalingLists8x8[1], (uint8_t*)default_inter_scaling_list8x8); } } } } else { for (int32_t i = 0; i < 6; i++) { FillScalingList4x4(&scaling->ScalingLists4x4[i],(uint8_t *)sps->ScalingLists4x4[i].ScalingListCoeffs); pps->type_of_scaling_list_used[i] = sps->type_of_scaling_list_used[i]; } if (pps->transform_8x8_mode_flag) { for (int32_t i = 0; i < 2; i++) { FillScalingList8x8(&scaling->ScalingLists8x8[i],(uint8_t *)sps->ScalingLists8x8[i].ScalingListCoeffs); pps->type_of_scaling_list_used[i] = sps->type_of_scaling_list_used[i]; } } } // calculate level scale matrices //start DC first //to do: reduce th anumber of matrices (in fact 1 is enough) // now process other 4x4 matrices for (int32_t i = 0; i < 6; i++) { for (int32_t j = 0; j < 88; j++) for (int32_t k = 0; k < 16; k++) { uint32_t level_scale = scaling->ScalingLists4x4[i].ScalingListCoeffs[k]*pre_norm_adjust4x4[j%6][pre_norm_adjust_index4x4[k]]; scaling->m_LevelScale4x4[i].LevelScaleCoeffs[j][k] = (int16_t) level_scale; } } // process remaining 8x8 matrices for (int32_t i = 0; i < 2; i++) { for (int32_t j = 0; j < 88; j++) for (int32_t k = 0; k < 64; k++) { uint32_t level_scale = scaling->ScalingLists8x8[i].ScalingListCoeffs[k]*pre_norm_adjust8x8[j%6][pre_norm_adjust_index8x8[k]]; scaling->m_LevelScale8x8[i].LevelScaleCoeffs[j][k] = (int16_t) level_scale; } } pps->initialized[isExtension] = 1; return UMC_OK; } Status H264HeadersBitstream::GetNalUnitPrefix(H264NalExtension *pExt, uint32_t NALRef_idc) { Status ps = UMC_OK; ps = GetNalUnitExtension(pExt); if (ps != UMC_OK || !pExt->svc_extension_flag) return ps; if (pExt->svc.dependency_id || pExt->svc.quality_id) // shall be equals zero for prefix NAL units return UMC_ERR_INVALID_STREAM; pExt->svc.adaptiveMarkingInfo.num_entries = 0; if (NALRef_idc != 0) { pExt->svc.store_ref_base_pic_flag = Get1Bit(); if ((pExt->svc.use_ref_base_pic_flag || pExt->svc.store_ref_base_pic_flag) && !pExt->svc.idr_flag) { ps = DecRefBasePicMarking(&pExt->svc.adaptiveMarkingInfo, pExt->svc.adaptive_ref_base_pic_marking_mode_flag); if (ps != UMC_OK) return ps; } /*int32_t additional_prefix_nal_unit_extension_flag = (int32_t) Get1Bit(); if (additional_prefix_nal_unit_extension_flag == 1) { additional_prefix_nal_unit_extension_flag = Get1Bit(); }*/ } CheckBSLeft(); return ps; } // Status H264HeadersBitstream::GetNalUnitPrefix(void) Status H264HeadersBitstream::GetNalUnitExtension(H264NalExtension *pExt) { pExt->Reset(); pExt->extension_present = 1; // decode the type of the extension pExt->svc_extension_flag = (uint8_t) GetBits(1); // decode SVC extension if (pExt->svc_extension_flag) { pExt->svc.idr_flag = Get1Bit(); pExt->svc.priority_id = (uint8_t) GetBits(6); pExt->svc.no_inter_layer_pred_flag = Get1Bit(); pExt->svc.dependency_id = (uint8_t) GetBits(3); pExt->svc.quality_id = (uint8_t) GetBits(4); pExt->svc.temporal_id = (uint8_t) GetBits(3); pExt->svc.use_ref_base_pic_flag = Get1Bit(); pExt->svc.discardable_flag = Get1Bit(); pExt->svc.output_flag = Get1Bit(); GetBits(2); } // decode MVC extension else { pExt->mvc.non_idr_flag = Get1Bit(); pExt->mvc.priority_id = (uint16_t) GetBits(6); pExt->mvc.view_id = (uint16_t) GetBits(10); pExt->mvc.temporal_id = (uint8_t) GetBits(3); pExt->mvc.anchor_pic_flag = Get1Bit(); pExt->mvc.inter_view_flag = Get1Bit(); GetBits(1); } CheckBSLeft(); return UMC_OK; } // Status H264HeadersBitstream::GetNalUnitExtension(H264NalExtension *pExt) // --------------------------------------------------------------------------- // Read H.264 first part of slice header // // Reading the rest of the header requires info in the picture and sequence // parameter sets referred to by this slice header. // // Do not print debug messages when IsSearch is true. In that case the function // is being used to find the next compressed frame, errors may occur and should // not be reported. // // --------------------------------------------------------------------------- Status H264HeadersBitstream::GetSliceHeaderPart1(H264SliceHeader *hdr) { uint32_t val; // decode NAL extension if (NAL_UT_CODED_SLICE_EXTENSION == hdr->nal_unit_type) { GetNalUnitExtension(&hdr->nal_ext); // set the IDR flag if (hdr->nal_ext.svc_extension_flag) { hdr->IdrPicFlag = hdr->nal_ext.svc.idr_flag; } else { hdr->IdrPicFlag = hdr->nal_ext.mvc.non_idr_flag ^ 1; } } else { if (hdr->nal_ext.extension_present) { if (hdr->nal_ext.svc_extension_flag) { //hdr->IdrPicFlag = hdr->nal_ext.svc.idr_flag; } else { //hdr->IdrPicFlag = hdr->nal_ext.mvc.non_idr_flag ^ 1; } } else { //hdr->IdrPicFlag = (NAL_UT_IDR_SLICE == hdr->nal_unit_type) ? 1 : 0; hdr->nal_ext.mvc.anchor_pic_flag = (uint8_t) hdr->IdrPicFlag ? 1 : 0; hdr->nal_ext.mvc.inter_view_flag = (uint8_t) 1; } hdr->IdrPicFlag = (NAL_UT_IDR_SLICE == hdr->nal_unit_type) ? 1 : 0; } hdr->first_mb_in_slice = GetVLCElement(false); if (0 > hdr->first_mb_in_slice) // upper bound is checked in H264Slice return UMC_ERR_INVALID_STREAM; // slice type val = GetVLCElement(false); if (val > S_INTRASLICE) { if (val > S_INTRASLICE + S_INTRASLICE + 1) { return UMC_ERR_INVALID_STREAM; } else { // Slice type is specifying type of not only this but all remaining // slices in the picture. Since slice type is always present, this bit // of info is not used in our implementation. Adjust (just shift range) // and return type without this extra info. val -= (S_INTRASLICE + 1); } } if (val > INTRASLICE) // all other doesn't support return UMC_ERR_INVALID_STREAM; hdr->slice_type = (EnumSliceCodType)val; if (NAL_UT_IDR_SLICE == hdr->nal_unit_type && hdr->slice_type != INTRASLICE) return UMC_ERR_INVALID_STREAM; uint32_t pic_parameter_set_id = GetVLCElement(false); hdr->pic_parameter_set_id = (uint16_t)pic_parameter_set_id; if (pic_parameter_set_id > MAX_NUM_PIC_PARAM_SETS - 1) { return UMC_ERR_INVALID_STREAM; } CheckBSLeft(); return UMC_OK; } // Status GetSliceHeaderPart1(H264SliceHeader *pSliceHeader) Status H264HeadersBitstream::GetSliceHeaderPart2(H264SliceHeader *hdr, const H264PicParamSet *pps, const H264SeqParamSet *sps) { hdr->frame_num = GetBits(sps->log2_max_frame_num); hdr->bottom_field_flag = 0; if (sps->frame_mbs_only_flag == 0) { hdr->field_pic_flag = Get1Bit(); hdr->MbaffFrameFlag = !hdr->field_pic_flag && sps->mb_adaptive_frame_field_flag; if (hdr->field_pic_flag != 0) { hdr->bottom_field_flag = Get1Bit(); } } if (hdr->MbaffFrameFlag) { uint32_t const first_mb_in_slice = hdr->first_mb_in_slice; if (first_mb_in_slice * 2 > INT_MAX) return UMC_ERR_INVALID_STREAM; // correct frst_mb_in_slice in order to handle MBAFF hdr->first_mb_in_slice *= 2; } if (hdr->IdrPicFlag) { int32_t pic_id = hdr->idr_pic_id = GetVLCElement(false); if (pic_id < 0 || pic_id > 65535) return UMC_ERR_INVALID_STREAM; } if (sps->pic_order_cnt_type == 0) { hdr->pic_order_cnt_lsb = GetBits(sps->log2_max_pic_order_cnt_lsb); if (pps->bottom_field_pic_order_in_frame_present_flag && (!hdr->field_pic_flag)) hdr->delta_pic_order_cnt_bottom = GetVLCElement(true); } if ((sps->pic_order_cnt_type == 1) && (sps->delta_pic_order_always_zero_flag == 0)) { hdr->delta_pic_order_cnt[0] = GetVLCElement(true); if (pps->bottom_field_pic_order_in_frame_present_flag && (!hdr->field_pic_flag)) hdr->delta_pic_order_cnt[1] = GetVLCElement(true); } if (pps->redundant_pic_cnt_present_flag) { hdr->hw_wa_redundant_elimination_bits[0] = (uint32_t)BitsDecoded(); // redundant pic count hdr->redundant_pic_cnt = GetVLCElement(false); if (hdr->redundant_pic_cnt > 127) return UMC_ERR_INVALID_STREAM; hdr->hw_wa_redundant_elimination_bits[1] = (uint32_t)BitsDecoded(); } CheckBSLeft(); return UMC_OK; } Status H264HeadersBitstream::DecRefBasePicMarking(AdaptiveMarkingInfo *pAdaptiveMarkingInfo, uint8_t &adaptive_ref_pic_marking_mode_flag) { uint32_t memory_management_control_operation; uint32_t num_entries = 0; adaptive_ref_pic_marking_mode_flag = Get1Bit(); while (adaptive_ref_pic_marking_mode_flag != 0) { memory_management_control_operation = (uint8_t)GetVLCElement(false); if (memory_management_control_operation == 0) break; if (memory_management_control_operation > 6) return UMC_ERR_INVALID_STREAM; pAdaptiveMarkingInfo->mmco[num_entries] = (uint8_t)memory_management_control_operation; if (memory_management_control_operation != 5) pAdaptiveMarkingInfo->value[num_entries*2] = GetVLCElement(false); // Only mmco 3 requires 2 values if (memory_management_control_operation == 3) pAdaptiveMarkingInfo->value[num_entries*2+1] = GetVLCElement(false); num_entries++; if (num_entries >= MAX_NUM_REF_FRAMES) { return UMC_ERR_INVALID_STREAM; } } // while pAdaptiveMarkingInfo->num_entries = num_entries; return UMC_OK; } Status H264HeadersBitstream::GetPredWeightTable( H264SliceHeader *hdr, // slice header read goes here const H264SeqParamSet *sps, PredWeightTable *pPredWeight_L0, // L0 weight table goes here PredWeightTable *pPredWeight_L1) // L1 weight table goes here { uint32_t luma_log2_weight_denom = GetVLCElement(false); hdr->luma_log2_weight_denom = (uint8_t)luma_log2_weight_denom; if (luma_log2_weight_denom > 7) return UMC_ERR_INVALID_STREAM; if (sps->chroma_format_idc != 0) { uint32_t chroma_log2_weight_denom = GetVLCElement(false); hdr->chroma_log2_weight_denom = (uint8_t)chroma_log2_weight_denom; if (chroma_log2_weight_denom > 7) return UMC_ERR_INVALID_STREAM; } for (int32_t refindex = 0; refindex < hdr->num_ref_idx_l0_active; refindex++) { pPredWeight_L0[refindex].luma_weight_flag = Get1Bit(); if (pPredWeight_L0[refindex].luma_weight_flag) { pPredWeight_L0[refindex].luma_weight = (int8_t)GetVLCElement(true); pPredWeight_L0[refindex].luma_offset = (int8_t)GetVLCElement(true); pPredWeight_L0[refindex].luma_offset <<= (sps->bit_depth_luma - 8); } else { pPredWeight_L0[refindex].luma_weight = (int8_t)(1 << hdr->luma_log2_weight_denom); pPredWeight_L0[refindex].luma_offset = 0; } pPredWeight_L0[refindex].chroma_weight_flag = 0; if (sps->chroma_format_idc != 0) { pPredWeight_L0[refindex].chroma_weight_flag = Get1Bit(); } if (pPredWeight_L0[refindex].chroma_weight_flag) { pPredWeight_L0[refindex].chroma_weight[0] = (int8_t)GetVLCElement(true); pPredWeight_L0[refindex].chroma_offset[0] = (int8_t)GetVLCElement(true); pPredWeight_L0[refindex].chroma_weight[1] = (int8_t)GetVLCElement(true); pPredWeight_L0[refindex].chroma_offset[1] = (int8_t)GetVLCElement(true); pPredWeight_L0[refindex].chroma_offset[0] <<= (sps->bit_depth_chroma - 8); pPredWeight_L0[refindex].chroma_offset[1] <<= (sps->bit_depth_chroma - 8); } else { pPredWeight_L0[refindex].chroma_weight[0] = (int8_t)(1 << hdr->chroma_log2_weight_denom); pPredWeight_L0[refindex].chroma_weight[1] = (int8_t)(1 << hdr->chroma_log2_weight_denom); pPredWeight_L0[refindex].chroma_offset[0] = 0; pPredWeight_L0[refindex].chroma_offset[1] = 0; } } if (BPREDSLICE == hdr->slice_type) { for (int32_t refindex = 0; refindex < hdr->num_ref_idx_l1_active; refindex++) { pPredWeight_L1[refindex].luma_weight_flag = Get1Bit(); if (pPredWeight_L1[refindex].luma_weight_flag) { pPredWeight_L1[refindex].luma_weight = (int8_t)GetVLCElement(true); pPredWeight_L1[refindex].luma_offset = (int8_t)GetVLCElement(true); pPredWeight_L1[refindex].luma_offset <<= (sps->bit_depth_luma - 8); } else { pPredWeight_L1[refindex].luma_weight = (int8_t)(1 << hdr->luma_log2_weight_denom); pPredWeight_L1[refindex].luma_offset = 0; } pPredWeight_L1[refindex].chroma_weight_flag = 0; if (sps->chroma_format_idc != 0) pPredWeight_L1[refindex].chroma_weight_flag = Get1Bit(); if (pPredWeight_L1[refindex].chroma_weight_flag) { pPredWeight_L1[refindex].chroma_weight[0] = (int8_t)GetVLCElement(true); pPredWeight_L1[refindex].chroma_offset[0] = (int8_t)GetVLCElement(true); pPredWeight_L1[refindex].chroma_weight[1] = (int8_t)GetVLCElement(true); pPredWeight_L1[refindex].chroma_offset[1] = (int8_t)GetVLCElement(true); pPredWeight_L1[refindex].chroma_offset[0] <<= (sps->bit_depth_chroma - 8); pPredWeight_L1[refindex].chroma_offset[1] <<= (sps->bit_depth_chroma - 8); } else { pPredWeight_L1[refindex].chroma_weight[0] = (int8_t)(1 << hdr->chroma_log2_weight_denom); pPredWeight_L1[refindex].chroma_weight[1] = (int8_t)(1 << hdr->chroma_log2_weight_denom); pPredWeight_L1[refindex].chroma_offset[0] = 0; pPredWeight_L1[refindex].chroma_offset[1] = 0; } } } // B slice return UMC_OK; } Status H264HeadersBitstream::GetSliceHeaderPart3( H264SliceHeader *hdr, // slice header read goes here PredWeightTable *pPredWeight_L0, // L0 weight table goes here PredWeightTable *pPredWeight_L1, // L1 weight table goes here RefPicListReorderInfo *pReorderInfo_L0, RefPicListReorderInfo *pReorderInfo_L1, AdaptiveMarkingInfo *pAdaptiveMarkingInfo, AdaptiveMarkingInfo *pBaseAdaptiveMarkingInfo, const H264PicParamSet *pps, const H264SeqParamSet *sps, const H264SeqParamSetSVCExtension *spsSvcExt) { uint8_t ref_pic_list_reordering_flag_l0 = 0; uint8_t ref_pic_list_reordering_flag_l1 = 0; Status ps = UMC_OK; pReorderInfo_L0->num_entries = 0; pReorderInfo_L1->num_entries = 0; hdr->num_ref_idx_l0_active = pps->num_ref_idx_l0_active; hdr->num_ref_idx_l1_active = pps->num_ref_idx_l1_active; hdr->direct_spatial_mv_pred_flag = 1; if (!hdr->nal_ext.svc_extension_flag || hdr->nal_ext.svc.quality_id == 0) { if (BPREDSLICE == hdr->slice_type) { // direct mode prediction method hdr->direct_spatial_mv_pred_flag = Get1Bit(); } if (PREDSLICE == hdr->slice_type || S_PREDSLICE == hdr->slice_type || BPREDSLICE == hdr->slice_type) { hdr->num_ref_idx_active_override_flag = Get1Bit(); if (hdr->num_ref_idx_active_override_flag != 0) // ref idx active l0 and l1 { hdr->num_ref_idx_l0_active = GetVLCElement(false) + 1; if (BPREDSLICE == hdr->slice_type) hdr->num_ref_idx_l1_active = GetVLCElement(false) + 1; } } // ref idx override if (hdr->num_ref_idx_l0_active < 0 || hdr->num_ref_idx_l0_active > (int32_t)MAX_NUM_REF_FRAMES || hdr->num_ref_idx_l1_active < 0 || hdr->num_ref_idx_l1_active > (int32_t)MAX_NUM_REF_FRAMES) return UMC_ERR_INVALID_STREAM; if (hdr->slice_type != INTRASLICE && hdr->slice_type != S_INTRASLICE) { uint32_t reordering_of_pic_nums_idc; uint32_t reorder_idx; // Reference picture list reordering ref_pic_list_reordering_flag_l0 = Get1Bit(); if (ref_pic_list_reordering_flag_l0) { reorder_idx = 0; reordering_of_pic_nums_idc = 0; // Get reorder idc,pic_num pairs until idc==3 for (;;) { reordering_of_pic_nums_idc = (uint8_t)GetVLCElement(false); if (reordering_of_pic_nums_idc > 5) return UMC_ERR_INVALID_STREAM; if (reordering_of_pic_nums_idc == 3) break; if (reorder_idx >= MAX_NUM_REF_FRAMES) { return UMC_ERR_INVALID_STREAM; } pReorderInfo_L0->reordering_of_pic_nums_idc[reorder_idx] = (uint8_t)reordering_of_pic_nums_idc; pReorderInfo_L0->reorder_value[reorder_idx] = GetVLCElement(false); if (reordering_of_pic_nums_idc != 2) // abs_diff_pic_num is coded minus 1 pReorderInfo_L0->reorder_value[reorder_idx]++; reorder_idx++; } // while pReorderInfo_L0->num_entries = reorder_idx; } // L0 reordering info else pReorderInfo_L0->num_entries = 0; if (BPREDSLICE == hdr->slice_type) { ref_pic_list_reordering_flag_l1 = Get1Bit(); if (ref_pic_list_reordering_flag_l1) { // Get reorder idc,pic_num pairs until idc==3 reorder_idx = 0; reordering_of_pic_nums_idc = 0; for (;;) { reordering_of_pic_nums_idc = GetVLCElement(false); if (reordering_of_pic_nums_idc > 5) return UMC_ERR_INVALID_STREAM; if (reordering_of_pic_nums_idc == 3) break; if (reorder_idx >= MAX_NUM_REF_FRAMES) { return UMC_ERR_INVALID_STREAM; } pReorderInfo_L1->reordering_of_pic_nums_idc[reorder_idx] = (uint8_t)reordering_of_pic_nums_idc; pReorderInfo_L1->reorder_value[reorder_idx] = GetVLCElement(false); if (reordering_of_pic_nums_idc != 2) // abs_diff_pic_num is coded minus 1 pReorderInfo_L1->reorder_value[reorder_idx]++; reorder_idx++; } // while pReorderInfo_L1->num_entries = reorder_idx; } // L1 reordering info else pReorderInfo_L1->num_entries = 0; } // B slice } // reordering info hdr->luma_log2_weight_denom = 0; hdr->chroma_log2_weight_denom = 0; // prediction weight table if ( (pps->weighted_pred_flag && ((PREDSLICE == hdr->slice_type) || (S_PREDSLICE == hdr->slice_type))) || ((pps->weighted_bipred_idc == 1) && (BPREDSLICE == hdr->slice_type))) { ps = GetPredWeightTable(hdr, sps, pPredWeight_L0, pPredWeight_L1); if (ps != UMC_OK) return ps; } // dec_ref_pic_marking pAdaptiveMarkingInfo->num_entries = 0; pBaseAdaptiveMarkingInfo->num_entries = 0; if (hdr->nal_ref_idc) { ps = DecRefPicMarking(hdr, pAdaptiveMarkingInfo); if (ps != UMC_OK) { return ps; } if (hdr->nal_unit_type == NAL_UT_CODED_SLICE_EXTENSION && hdr->nal_ext.svc_extension_flag && spsSvcExt && !spsSvcExt->slice_header_restriction_flag) { hdr->nal_ext.svc.store_ref_base_pic_flag = Get1Bit(); if ((hdr->nal_ext.svc.use_ref_base_pic_flag || hdr->nal_ext.svc.store_ref_base_pic_flag) && (!hdr->nal_ext.svc.idr_flag)) { ps = DecRefBasePicMarking(pBaseAdaptiveMarkingInfo, hdr->nal_ext.svc.adaptive_ref_base_pic_marking_mode_flag); if (ps != UMC_OK) return ps; } } } // def_ref_pic_marking } if (pps->entropy_coding_mode == 1 && // CABAC (hdr->slice_type != INTRASLICE && hdr->slice_type != S_INTRASLICE)) hdr->cabac_init_idc = GetVLCElement(false); else hdr->cabac_init_idc = 0; if (hdr->cabac_init_idc > 2) return UMC_ERR_INVALID_STREAM; hdr->slice_qp_delta = GetVLCElement(true); if (S_PREDSLICE == hdr->slice_type || S_INTRASLICE == hdr->slice_type) { if (S_PREDSLICE == hdr->slice_type) hdr->sp_for_switch_flag = Get1Bit(); hdr->slice_qs_delta = GetVLCElement(true); } if (pps->deblocking_filter_variables_present_flag) { // deblock filter flag and offsets hdr->disable_deblocking_filter_idc = GetVLCElement(false); if (hdr->disable_deblocking_filter_idc > DEBLOCK_FILTER_ON_NO_SLICE_EDGES) return UMC_ERR_INVALID_STREAM; if (hdr->disable_deblocking_filter_idc != DEBLOCK_FILTER_OFF) { hdr->slice_alpha_c0_offset = GetVLCElement(true)<<1; hdr->slice_beta_offset = GetVLCElement(true)<<1; if (hdr->slice_alpha_c0_offset < -12 || hdr->slice_alpha_c0_offset > 12) { return UMC_ERR_INVALID_STREAM; } if (hdr->slice_beta_offset < -12 || hdr->slice_beta_offset > 12) { return UMC_ERR_INVALID_STREAM; } } else { // set filter offsets to max values to disable filter hdr->slice_alpha_c0_offset = (int8_t)(0 - QP_MAX); hdr->slice_beta_offset = (int8_t)(0 - QP_MAX); } } if (pps->num_slice_groups > 1 && pps->SliceGroupInfo.slice_group_map_type >= 3 && pps->SliceGroupInfo.slice_group_map_type <= 5) { uint32_t num_bits; // number of bits used to code slice_group_change_cycle uint32_t val; uint32_t pic_size_in_map_units; uint32_t max_slice_group_change_cycle=0; // num_bits is Ceil(log2(picsizeinmapunits/slicegroupchangerate + 1)) pic_size_in_map_units = sps->frame_width_in_mbs * sps->frame_height_in_mbs; // TBD: change above to support fields max_slice_group_change_cycle = pic_size_in_map_units / pps->SliceGroupInfo.t2.slice_group_change_rate; if (pic_size_in_map_units % pps->SliceGroupInfo.t2.slice_group_change_rate) max_slice_group_change_cycle++; val = max_slice_group_change_cycle;// + 1; num_bits = 0; while (val) { num_bits++; val >>= 1; } hdr->slice_group_change_cycle = GetBits(num_bits); if (hdr->slice_group_change_cycle > max_slice_group_change_cycle) { //return UMC_ERR_INVALID_STREAM; don't see any reasons for that } } CheckBSLeft(); return UMC_OK; } // GetSliceHeaderPart3() Status H264HeadersBitstream::DecRefPicMarking(H264SliceHeader *hdr, // slice header read goes here AdaptiveMarkingInfo *pAdaptiveMarkingInfo) { if (hdr->IdrPicFlag) { hdr->no_output_of_prior_pics_flag = Get1Bit(); hdr->long_term_reference_flag = Get1Bit(); } else { return DecRefBasePicMarking(pAdaptiveMarkingInfo, hdr->adaptive_ref_pic_marking_mode_flag); } return UMC_OK; } Status H264HeadersBitstream::GetSliceHeaderPart4(H264SliceHeader *hdr, const H264SeqParamSetSVCExtension *) { hdr->scan_idx_start = 0; hdr->scan_idx_end = 15; return UMC_OK; }// GetSliceHeaderPart4() void H264HeadersBitstream::GetScalingList4x4(H264ScalingList4x4 *scl, uint8_t *def, uint8_t *scl_type) { uint32_t lastScale = 8; uint32_t nextScale = 8; bool DefaultMatrix = false; int32_t j; for (j = 0; j < 16; j++ ) { if (nextScale != 0) { int32_t delta_scale = GetVLCElement(true); if (delta_scale < -128 || delta_scale > 127) throw h264_exception(UMC_ERR_INVALID_STREAM); nextScale = ( lastScale + delta_scale + 256 ) & 0xff; DefaultMatrix = ( j == 0 && nextScale == 0 ); } scl->ScalingListCoeffs[ mp_scan4x4[0][j] ] = ( nextScale == 0 ) ? (uint8_t)lastScale : (uint8_t)nextScale; lastScale = scl->ScalingListCoeffs[ mp_scan4x4[0][j] ]; } if (!DefaultMatrix) { *scl_type=SCLREDEFINED; return; } *scl_type= SCLDEFAULT; FillScalingList4x4(scl,def); return; } void H264HeadersBitstream::GetScalingList8x8(H264ScalingList8x8 *scl, uint8_t *def, uint8_t *scl_type) { uint32_t lastScale = 8; uint32_t nextScale = 8; bool DefaultMatrix=false; int32_t j; for (j = 0; j < 64; j++ ) { if (nextScale != 0) { int32_t delta_scale = GetVLCElement(true); if (delta_scale < -128 || delta_scale > 127) throw h264_exception(UMC_ERR_INVALID_STREAM); nextScale = ( lastScale + delta_scale + 256 ) & 0xff; DefaultMatrix = ( j == 0 && nextScale == 0 ); } scl->ScalingListCoeffs[ hp_scan8x8[0][j] ] = ( nextScale == 0 ) ? (uint8_t)lastScale : (uint8_t)nextScale; lastScale = scl->ScalingListCoeffs[ hp_scan8x8[0][j] ]; } if (!DefaultMatrix) { *scl_type=SCLREDEFINED; return; } *scl_type= SCLDEFAULT; FillScalingList8x8(scl,def); return; } Status H264HeadersBitstream::GetNALUnitType(NAL_Unit_Type &nal_unit_type, uint32_t &nal_ref_idc) { uint32_t code; h264GetBits(m_pbs, m_bitOffset, 8, code); nal_ref_idc = (uint32_t) ((code & NAL_STORAGE_IDC_BITS)>>5); nal_unit_type = (NAL_Unit_Type) (code & NAL_UNITTYPE_BITS); return UMC_OK; } const H264SeqParamSet *GetSeqParams(const Headers & headers, int32_t seq_parameter_set_id) { if (seq_parameter_set_id == -1) return 0; const H264SeqParamSet *csps = headers.m_SeqParams.GetHeader(seq_parameter_set_id); if (csps) return csps; csps = headers.m_SeqParamsMvcExt.GetHeader(seq_parameter_set_id); if (csps) return csps; csps = headers.m_SeqParamsSvcExt.GetHeader(seq_parameter_set_id); if (csps) return csps; return 0; } int32_t H264HeadersBitstream::ParseSEI(const Headers & headers, H264SEIPayLoad *spl) { int32_t current_sps = headers.m_SeqParams.GetCurrentID(); return sei_message(headers, current_sps, spl); } int32_t H264HeadersBitstream::sei_message(const Headers & headers, int32_t current_sps, H264SEIPayLoad *spl) { uint32_t code; int32_t payloadType = 0; PeakNextBits(m_pbs, m_bitOffset, 8, code); while (code == 0xFF) { /* fixed-pattern bit string using 8 bits written equal to 0xFF */ h264GetBits(m_pbs, m_bitOffset, 8, code); payloadType += 255; PeakNextBits(m_pbs, m_bitOffset, 8, code); } int32_t last_payload_type_byte; //uint32_t integer using 8 bits h264GetBits(m_pbs, m_bitOffset, 8, last_payload_type_byte); payloadType += last_payload_type_byte; int32_t payloadSize = 0; PeakNextBits(m_pbs, m_bitOffset, 8, code); while( code == 0xFF ) { /* fixed-pattern bit string using 8 bits written equal to 0xFF */ h264GetBits(m_pbs, m_bitOffset, 8, code); payloadSize += 255; PeakNextBits(m_pbs, m_bitOffset, 8, code); } int32_t last_payload_size_byte; //uint32_t integer using 8 bits h264GetBits(m_pbs, m_bitOffset, 8, last_payload_size_byte); payloadSize += last_payload_size_byte; spl->Reset(); spl->payLoadSize = payloadSize; if (payloadType < 0 || payloadType > SEI_RESERVED) payloadType = SEI_RESERVED; spl->payLoadType = (SEI_TYPE)payloadType; if (spl->payLoadSize > BytesLeft()) { throw h264_exception(UMC_ERR_INVALID_STREAM); } uint32_t * pbs; uint32_t bitOffsetU; int32_t bitOffset; GetState(&pbs, &bitOffsetU); bitOffset = bitOffsetU; CheckBSLeft(spl->payLoadSize); spl->isValid = 1; int32_t ret = sei_payload(headers, current_sps, spl); for (uint32_t i = 0; i < spl->payLoadSize; i++) { SkipNBits(pbs, bitOffset, 8); } SetState(pbs, bitOffset); return ret; } int32_t H264HeadersBitstream::sei_payload(const Headers & headers, int32_t current_sps,H264SEIPayLoad *spl) { uint32_t payloadType =spl->payLoadType; switch( payloadType) { case SEI_BUFFERING_PERIOD_TYPE: buffering_period(headers, current_sps,spl); break; case SEI_PIC_TIMING_TYPE: pic_timing(headers,current_sps,spl); break; case SEI_DEC_REF_PIC_MARKING_TYPE: dec_ref_pic_marking_repetition(headers,current_sps,spl); break; case SEI_USER_DATA_REGISTERED_TYPE: user_data_registered_itu_t_t35(spl); break; case SEI_RECOVERY_POINT_TYPE: recovery_point(spl); break; case SEI_SCALABILITY_INFO: scalability_info(spl); break; case SEI_SCALABLE_NESTING: case SEI_USER_DATA_UNREGISTERED_TYPE: case SEI_PAN_SCAN_RECT_TYPE: case SEI_FILLER_TYPE: case SEI_SPARE_PIC_TYPE: case SEI_SCENE_INFO_TYPE: case SEI_SUB_SEQ_INFO_TYPE: case SEI_SUB_SEQ_LAYER_TYPE: case SEI_SUB_SEQ_TYPE: case SEI_FULL_FRAME_FREEZE_TYPE: case SEI_FULL_FRAME_FREEZE_RELEASE_TYPE: case SEI_FULL_FRAME_SNAPSHOT_TYPE: case SEI_PROGRESSIVE_REF_SEGMENT_START_TYPE: case SEI_PROGRESSIVE_REF_SEGMENT_END_TYPE: case SEI_MOTION_CONSTRAINED_SG_SET_TYPE: default: unparsed_sei_message(spl); break; } return current_sps; } int32_t H264HeadersBitstream::buffering_period(const Headers & headers, int32_t , H264SEIPayLoad *spl) { int32_t seq_parameter_set_id = (uint8_t) GetVLCElement(false); const H264SeqParamSet *csps = GetSeqParams(headers, seq_parameter_set_id); H264SEIPayLoad::SEIMessages::BufferingPeriod &bps = spl->SEI_messages.buffering_period; // touch unreferenced parameters if (!csps) { throw h264_exception(UMC_ERR_INVALID_STREAM); } if (csps->vui.nal_hrd_parameters_present_flag) { if (csps->vui.cpb_cnt >= 32) throw h264_exception(UMC_ERR_INVALID_STREAM); for(int32_t i=0; i < csps->vui.cpb_cnt; i++) { bps.initial_cpb_removal_delay[0][i] = GetBits(csps->vui.initial_cpb_removal_delay_length); bps.initial_cpb_removal_delay_offset[0][i] = GetBits(csps->vui.initial_cpb_removal_delay_length); } } if (csps->vui.vcl_hrd_parameters_present_flag) { if (csps->vui.cpb_cnt >= 32) throw h264_exception(UMC_ERR_INVALID_STREAM); for(int32_t i=0; i < csps->vui.cpb_cnt; i++) { bps.initial_cpb_removal_delay[1][i] = GetBits(csps->vui.cpb_removal_delay_length); bps.initial_cpb_removal_delay_offset[1][i] = GetBits(csps->vui.cpb_removal_delay_length); } } AlignPointerRight(); return seq_parameter_set_id; } int32_t H264HeadersBitstream::pic_timing(const Headers & headers, int32_t current_sps, H264SEIPayLoad *spl) { if (current_sps == -1) throw h264_exception(UMC_ERR_INVALID_STREAM); const uint8_t NumClockTS[]={1,1,1,2,2,3,3,2,3}; const H264SeqParamSet *csps = GetSeqParams(headers, current_sps); H264SEIPayLoad::SEIMessages::PicTiming &pts = spl->SEI_messages.pic_timing; if (!csps) throw h264_exception(UMC_ERR_INVALID_STREAM); if (csps->vui.nal_hrd_parameters_present_flag || csps->vui.vcl_hrd_parameters_present_flag) { pts.cbp_removal_delay = GetBits(csps->vui.cpb_removal_delay_length); pts.dpb_output_delay = GetBits(csps->vui.dpb_output_delay_length); } else { pts.cbp_removal_delay = INVALID_DPB_OUTPUT_DELAY; pts.dpb_output_delay = INVALID_DPB_OUTPUT_DELAY; } if (csps->vui.pic_struct_present_flag) { uint8_t picStruct = (uint8_t)GetBits(4); if (picStruct > 8) return UMC_ERR_INVALID_STREAM; pts.pic_struct = (DisplayPictureStruct)picStruct; for (int32_t i = 0; i < NumClockTS[pts.pic_struct]; i++) { pts.clock_timestamp_flag[i] = (uint8_t)Get1Bit(); if (pts.clock_timestamp_flag[i]) { pts.clock_timestamps[i].ct_type = (uint8_t)GetBits(2); pts.clock_timestamps[i].nunit_field_based_flag = (uint8_t)Get1Bit(); pts.clock_timestamps[i].counting_type = (uint8_t)GetBits(5); pts.clock_timestamps[i].full_timestamp_flag = (uint8_t)Get1Bit(); pts.clock_timestamps[i].discontinuity_flag = (uint8_t)Get1Bit(); pts.clock_timestamps[i].cnt_dropped_flag = (uint8_t)Get1Bit(); pts.clock_timestamps[i].n_frames = (uint8_t)GetBits(8); if (pts.clock_timestamps[i].full_timestamp_flag) { pts.clock_timestamps[i].seconds_value = (uint8_t)GetBits(6); pts.clock_timestamps[i].minutes_value = (uint8_t)GetBits(6); pts.clock_timestamps[i].hours_value = (uint8_t)GetBits(5); } else { if (Get1Bit()) { pts.clock_timestamps[i].seconds_value = (uint8_t)GetBits(6); if (Get1Bit()) { pts.clock_timestamps[i].minutes_value = (uint8_t)GetBits(6); if (Get1Bit()) { pts.clock_timestamps[i].hours_value = (uint8_t)GetBits(5); } } } } if (csps->vui.time_offset_length > 0) pts.clock_timestamps[i].time_offset = (uint8_t)GetBits(csps->vui.time_offset_length); } } } AlignPointerRight(); return current_sps; } void H264HeadersBitstream::user_data_registered_itu_t_t35(H264SEIPayLoad *spl) { H264SEIPayLoad::SEIMessages::UserDataRegistered * user_data = &(spl->SEI_messages.user_data_registered); uint32_t code; h264GetBits(m_pbs, m_bitOffset, 8, code); user_data->itu_t_t35_country_code = (uint8_t)code; uint32_t i = 1; user_data->itu_t_t35_country_code_extension_byte = 0; if (user_data->itu_t_t35_country_code == 0xff) { h264GetBits(m_pbs, m_bitOffset, 8, code); user_data->itu_t_t35_country_code_extension_byte = (uint8_t)code; i++; } spl->user_data.resize(spl->payLoadSize + 1); for(int32_t k = 0; i < spl->payLoadSize; i++, k++) { h264GetBits(m_pbs, m_bitOffset, 8, code); spl->user_data[k] = (uint8_t) code; } } void H264HeadersBitstream::recovery_point(H264SEIPayLoad *spl) { H264SEIPayLoad::SEIMessages::RecoveryPoint * recPoint = &(spl->SEI_messages.recovery_point); recPoint->recovery_frame_cnt = (uint8_t)GetVLCElement(false); recPoint->exact_match_flag = (uint8_t)Get1Bit(); recPoint->broken_link_flag = (uint8_t)Get1Bit(); recPoint->changing_slice_group_idc = (uint8_t)GetBits(2); if (recPoint->changing_slice_group_idc > 2) { spl->isValid = 0; } } int32_t H264HeadersBitstream::dec_ref_pic_marking_repetition(const Headers & headers, int32_t current_sps, H264SEIPayLoad *spl) { if (current_sps == -1) throw h264_exception(UMC_ERR_INVALID_STREAM); const H264SeqParamSet *csps = GetSeqParams(headers, current_sps); if (!csps) throw h264_exception(UMC_ERR_INVALID_STREAM); spl->SEI_messages.dec_ref_pic_marking_repetition.original_idr_flag = (uint8_t)Get1Bit(); spl->SEI_messages.dec_ref_pic_marking_repetition.original_frame_num = (uint8_t)GetVLCElement(false); if (!csps->frame_mbs_only_flag) { spl->SEI_messages.dec_ref_pic_marking_repetition.original_field_pic_flag = (uint8_t)Get1Bit(); if (spl->SEI_messages.dec_ref_pic_marking_repetition.original_field_pic_flag) { spl->SEI_messages.dec_ref_pic_marking_repetition.original_bottom_field_flag = (uint8_t)Get1Bit(); } } H264SliceHeader hdr; memset(&hdr, 0, sizeof(H264SliceHeader)); hdr.IdrPicFlag = spl->SEI_messages.dec_ref_pic_marking_repetition.original_idr_flag; Status sts = DecRefPicMarking(&hdr, &spl->SEI_messages.dec_ref_pic_marking_repetition.adaptiveMarkingInfo); if (sts != UMC_OK) throw h264_exception(UMC_ERR_INVALID_STREAM); spl->SEI_messages.dec_ref_pic_marking_repetition.long_term_reference_flag = hdr.long_term_reference_flag; return current_sps; } void H264HeadersBitstream::unparsed_sei_message(H264SEIPayLoad *spl) { for(uint32_t i = 0; i < spl->payLoadSize; i++) SkipNBits(m_pbs, m_bitOffset, 8) AlignPointerRight(); } #ifdef _MSVC_LANG #pragma warning(disable : 4189) #endif void H264HeadersBitstream::scalability_info(H264SEIPayLoad *spl) { spl->SEI_messages.scalability_info.temporal_id_nesting_flag = (uint8_t)Get1Bit(); spl->SEI_messages.scalability_info.priority_layer_info_present_flag = (uint8_t)Get1Bit(); spl->SEI_messages.scalability_info.priority_id_setting_flag = (uint8_t)Get1Bit(); spl->SEI_messages.scalability_info.num_layers = GetVLCElement(false) + 1; if (spl->SEI_messages.scalability_info.num_layers > 1024) throw h264_exception(UMC_ERR_INVALID_STREAM); spl->user_data.resize(sizeof(scalability_layer_info) * spl->SEI_messages.scalability_info.num_layers); scalability_layer_info * layers = (scalability_layer_info *) (&spl->user_data[0]); for (uint32_t i = 0; i < spl->SEI_messages.scalability_info.num_layers; i++) { layers[i].layer_id = GetVLCElement(false); layers[i].priority_id = (uint8_t)GetBits(6); layers[i].discardable_flag = (uint8_t)Get1Bit(); layers[i].dependency_id = (uint8_t)GetBits(3); layers[i].quality_id = (uint8_t)GetBits(4); layers[i].temporal_id = (uint8_t)GetBits(3); uint8_t sub_pic_layer_flag = (uint8_t)Get1Bit(); // Need to check uint8_t sub_region_layer_flag = (uint8_t)Get1Bit(); // Need to check //if (sub_pic_layer_flag && !sub_region_layer_flag) // throw h264_exception(UMC_ERR_INVALID_STREAM); uint8_t iroi_division_info_present_flag = (uint8_t)Get1Bit(); // Need to check //if (sub_pic_layer_flag && iroi_division_info_present_flag) // throw h264_exception(UMC_ERR_INVALID_STREAM); uint8_t profile_level_info_present_flag = (uint8_t)Get1Bit(); uint8_t bitrate_info_present_flag = (uint8_t)Get1Bit(); uint8_t frm_rate_info_present_flag = (uint8_t)Get1Bit(); uint8_t frm_size_info_present_flag = (uint8_t)Get1Bit(); uint8_t layer_dependency_info_present_flag = (uint8_t)Get1Bit(); uint8_t parameter_sets_info_present_flag = (uint8_t)Get1Bit(); uint8_t bitstream_restriction_info_present_flag = (uint8_t)Get1Bit(); /*uint8_t exact_inter_layer_pred_flag = (uint8_t)*/Get1Bit(); if (sub_pic_layer_flag || iroi_division_info_present_flag) { /*uint8_t exact_sample_value_match_flag = (uint8_t)*/Get1Bit(); } uint8_t layer_conversion_flag = (uint8_t)Get1Bit(); /*uint8_t layer_output_flag = (uint8_t)*/Get1Bit(); if (profile_level_info_present_flag) { /*uint32_t layer_profile_level_idc = (uint8_t)*/GetBits(24); } if (bitrate_info_present_flag) { /*uint32_t avg_bitrate = */GetBits(16); /*uint32_t max_bitrate_layer = */GetBits(16); /*uint32_t max_bitrate_layer_representation = */GetBits(16); /*uint32_t max_bitrate_calc_window = */GetBits(16); } if (frm_rate_info_present_flag) { layers[i].constant_frm_rate_idc = GetBits(2); layers[i].avg_frm_rate = GetBits(16); } if (frm_size_info_present_flag || iroi_division_info_present_flag) { layers[i].frm_width_in_mbs = GetVLCElement(false) + 1; layers[i].frm_height_in_mbs = GetVLCElement(false) + 1; } if (sub_region_layer_flag) { /*uint32_t base_region_layer_id = */GetVLCElement(false); uint8_t dynamic_rect_flag = (uint8_t)Get1Bit(); if (!dynamic_rect_flag) { /*uint32_t horizontal_offset = */GetBits(16); /*uint32_t vertical_offset = */GetBits(16); /*uint32_t region_width = */GetBits(16); /*uint32_t region_height = */GetBits(16); } } if(sub_pic_layer_flag) { /*uint32_t roi_id = */GetVLCElement(false); } if (iroi_division_info_present_flag) { uint8_t iroi_grid_flag = (uint8_t)Get1Bit(); if (iroi_grid_flag) { /*uint32_t grid_width_in_mbs_minus1 = */GetVLCElement(false); /*uint32_t grid_height_in_mbs_minus1 = */GetVLCElement(false); } else { int32_t num_rois_minus1 = GetVLCElement(false); int32_t FrmSizeInMbs = layers[i].frm_height_in_mbs * layers[i].frm_width_in_mbs; if (num_rois_minus1 < 0 || num_rois_minus1 > FrmSizeInMbs) throw h264_exception(UMC_ERR_INVALID_STREAM); for (int32_t j = 0; j <= num_rois_minus1; j++) { /*uint32_t first_mb_in_roi = */GetVLCElement(false); /*uint32_t roi_width_in_mbs_minus1 = */GetVLCElement(false); /*uint32_t roi_height_in_mbs_minus1 = */GetVLCElement(false); } } } if (layer_dependency_info_present_flag) { layers[i].num_directly_dependent_layers = GetVLCElement(false); if (layers[i].num_directly_dependent_layers > 255) throw h264_exception(UMC_ERR_INVALID_STREAM); for(uint32_t j = 0; j < layers[i].num_directly_dependent_layers; j++) { layers[i].directly_dependent_layer_id_delta_minus1[j] = GetVLCElement(false); } } else { layers[i].layer_dependency_info_src_layer_id_delta = GetVLCElement(false); } if (parameter_sets_info_present_flag) { int32_t num_seq_parameter_set_minus1 = GetVLCElement(false); if (num_seq_parameter_set_minus1 < 0 || num_seq_parameter_set_minus1 > 32) throw h264_exception(UMC_ERR_INVALID_STREAM); for(int32_t j = 0; j <= num_seq_parameter_set_minus1; j++ ) /*uint32_t seq_parameter_set_id_delta = */GetVLCElement(false); int32_t num_subset_seq_parameter_set_minus1 = GetVLCElement(false); if (num_subset_seq_parameter_set_minus1 < 0 || num_subset_seq_parameter_set_minus1 > 32) throw h264_exception(UMC_ERR_INVALID_STREAM); for(int32_t j = 0; j <= num_subset_seq_parameter_set_minus1; j++ ) /*uint32_t subset_seq_parameter_set_id_delta = */GetVLCElement(false); int32_t num_pic_parameter_set_minus1 = GetVLCElement(false); if (num_pic_parameter_set_minus1 < 0 || num_pic_parameter_set_minus1 > 255) throw h264_exception(UMC_ERR_INVALID_STREAM); for(int32_t j = 0; j <= num_pic_parameter_set_minus1; j++) /*uint32_t pic_parameter_set_id_delta = */GetVLCElement(false); } else { /*uint32_t parameter_sets_info_src_layer_id_delta = */GetVLCElement(false); } if (bitstream_restriction_info_present_flag) { /*uint8_t motion_vectors_over_pic_boundaries_flag = (uint8_t)*/Get1Bit(); /*uint32_t max_bytes_per_pic_denom = */GetVLCElement(false); /*uint32_t max_bits_per_mb_denom = */GetVLCElement(false); /*uint32_t log2_max_mv_length_horizontal = */GetVLCElement(false); /*uint32_t log2_max_mv_length_vertical = */GetVLCElement(false); /*uint32_t num_reorder_frames = */GetVLCElement(false); /*uint32_t max_dec_frame_buffering = */GetVLCElement(false); } if (layer_conversion_flag) { /*uint32_t conversion_type_idc = */GetVLCElement(false); for(uint32_t j = 0; j < 2; j++) { uint8_t rewriting_info_flag = (uint8_t)Get1Bit(); if (rewriting_info_flag) { /*uint32_t rewriting_profile_level_idc = */GetBits(24); /*uint32_t rewriting_avg_bitrate = */GetBits(16); /*uint32_t rewriting_max_bitrate = */GetBits(16); } } } } // for 0..num_layers if (spl->SEI_messages.scalability_info.priority_layer_info_present_flag) { uint32_t pr_num_dId_minus1 = GetVLCElement(false); for(uint32_t i = 0; i <= pr_num_dId_minus1; i++) { /*uint32_t pr_dependency_id = */GetBits(3); int32_t pr_num_minus1 = GetVLCElement(false); if (pr_num_minus1 < 0 || pr_num_minus1 > 63) throw h264_exception(UMC_ERR_INVALID_STREAM); for(int32_t j = 0; j <= pr_num_minus1; j++) { /*uint32_t pr_id = */GetVLCElement(false); /*uint32_t pr_profile_level_idc = */GetBits(24); /*uint32_t pr_avg_bitrate = */GetBits(16); /*uint32_t pr_max_bitrate = */GetBits(16); } } } if (spl->SEI_messages.scalability_info.priority_id_setting_flag) { std::vector<char> priority_id_setting_uri; // it is string uint32_t PriorityIdSettingUriIdx = 0; do { priority_id_setting_uri.push_back(1); priority_id_setting_uri[PriorityIdSettingUriIdx] = (uint8_t)GetBits(8); } while (priority_id_setting_uri[PriorityIdSettingUriIdx++] != 0); } } #ifdef _MSVC_LANG #pragma warning(default : 4189) #endif void SetDefaultScalingLists(H264SeqParamSet * sps) { int32_t i; for (i = 0; i < 6; i += 1) { FillFlatScalingList4x4(&sps->ScalingLists4x4[i]); } for (i = 0; i < 2; i += 1) { FillFlatScalingList8x8(&sps->ScalingLists8x8[i]); } } } // namespace UMC #endif // MFX_ENABLE_H264_VIDEO_DECODE
34.857583
145
0.611281
wangyan42164
8b25aa4cb4d6c6134baf186d56f4b157e585a2c7
4,418
cpp
C++
Fusin/src/Utilities/FusinCharCode.cpp
LegendaryMauricius/Fusin
36364b708257630be8b3f1aec27c9f711d255ab1
[ "MIT" ]
null
null
null
Fusin/src/Utilities/FusinCharCode.cpp
LegendaryMauricius/Fusin
36364b708257630be8b3f1aec27c9f711d255ab1
[ "MIT" ]
null
null
null
Fusin/src/Utilities/FusinCharCode.cpp
LegendaryMauricius/Fusin
36364b708257630be8b3f1aec27c9f711d255ab1
[ "MIT" ]
null
null
null
#include "Utilities/FusinCharCode.h" #include <sstream> #include <map> namespace Fusin { namespace { const std::map<String, Char> NameToKeyMap = { {FUSIN_STR("Home"), CC_HOME}, {FUSIN_STR("End"), CC_END}, {FUSIN_STR("L_Shift"), CC_LSHIFT}, {FUSIN_STR("R_Shift"), CC_RSHIFT}, {FUSIN_STR("L_Ctrl"), CC_LCONTROL}, {FUSIN_STR("R_Ctrl"), CC_RCONTROL}, {FUSIN_STR("Backspace"), CC_BACKSPACE}, {FUSIN_STR("Tab"), CC_TAB}, {FUSIN_STR("New_Line"), CC_NEW_LINE}, {FUSIN_STR("Clear"), CC_CLEAR}, {FUSIN_STR("Return"), CC_RETURN}, {FUSIN_STR("Page_Up"), CC_PAGE_UP}, {FUSIN_STR("Page_Down"), CC_PAGE_DOWN}, {FUSIN_STR("Pause"), CC_PAUSE}, {FUSIN_STR("Num_Lock"), CC_NUM_LOCK}, {FUSIN_STR("Scroll_Lock"), CC_SCROLL_LOCK}, {FUSIN_STR("Caps_Lock"), CC_CAPSLOCK}, {FUSIN_STR("L_Alt"), CC_LALT}, {FUSIN_STR("R_Alt"), CC_RALT}, {FUSIN_STR("Menu"), CC_MENU}, {FUSIN_STR("L_Win"), CC_LSUPER}, {FUSIN_STR("R_Win"), CC_RSUPER}, {FUSIN_STR("Esc"), CC_ESCAPE}, {FUSIN_STR("Print_Scr"), CC_PRINT_SCREEN}, {FUSIN_STR("Insert"), CC_INSERT}, {FUSIN_STR("Space"), CC_SPACE}, {FUSIN_STR("Multiply"), CC_MULTIPLY}, {FUSIN_STR("Add"), CC_ADD}, {FUSIN_STR("Subtract"), CC_SUBTRACT}, {FUSIN_STR("Decimal"), CC_DECIMAL}, {FUSIN_STR("Divide"), CC_DIVIDE}, {FUSIN_STR("Left"), CC_LEFT}, {FUSIN_STR("Up"), CC_UP}, {FUSIN_STR("Right"), CC_RIGHT}, {FUSIN_STR("Down"), CC_DOWN}, {FUSIN_STR("Del"), CC_DELETE}, }; } String keyToName(Char c) { StringStream ss; if (c >= CC_NUMPAD_FIRST && c <= CC_NUMPAD_LAST) { ss << "Num_" << (int)(c - CC_NUMPAD_FIRST); } else if (c >= CC_FUNCTION_FIRST && c <= CC_FUNCTION_LAST) { ss << "F" << (int)(c - CC_FUNCTION_FIRST + 1); } else { switch (c) { case CC_HOME: ss << "Home"; break; case CC_END: ss << "End"; break; case CC_LSHIFT: ss << "L_Shift"; break; case CC_RSHIFT: ss << "R_Shift"; break; case CC_LCONTROL: ss << "L_Ctrl"; break; case CC_RCONTROL: ss << "R_Ctrl"; break; case CC_BACKSPACE: ss << "Backspace"; break; case CC_TAB: ss << "Tab"; break; case CC_NEW_LINE: ss << "New_Line"; break; case CC_CLEAR: ss << "Clear"; break; case CC_RETURN: ss << "Return"; break; case CC_PAGE_UP: ss << "Page_Up"; break; case CC_PAGE_DOWN: ss << "Page_Down"; break; case CC_PAUSE: ss << "Pause"; break; case CC_NUM_LOCK: ss << "Num_Lock"; break; case CC_SCROLL_LOCK: ss << "Scroll_Lock"; break; case CC_CAPSLOCK: ss << "Caps_Lock"; break; case CC_LALT: ss << "L_Alt"; break; case CC_RALT: ss << "R_Alt"; break; case CC_MENU: ss << "Menu"; break; case CC_LSUPER: ss << "L_Win"; break; case CC_RSUPER: ss << "R_Win"; break; case CC_ESCAPE: ss << "Esc"; break; case CC_PRINT_SCREEN: ss << "Print_Scr"; break; case CC_INSERT: ss << "Insert"; break; case CC_SPACE: ss << "Space"; break; case CC_MULTIPLY: ss << "Multiply"; break; case CC_ADD: ss << "Add"; break; case CC_SUBTRACT: ss << "Subtract"; break; case CC_DECIMAL: ss << "Decimal"; break; case CC_DIVIDE: ss << "Divide"; break; case CC_LEFT: ss << "Left"; break; case CC_UP: ss << "Up"; break; case CC_RIGHT: ss << "Right"; break; case CC_DOWN: ss << "Down"; break; case CC_DELETE: ss << "Del"; break; default: ss << "'" << c << "'"; } } return ss.str(); } Char nameToKey(String name) { if (name.length() >= 4 && name.substr(0, 4) == FUSIN_STR("Num_")) { StringStream ss(name.substr(4)); int n; ss >> n; return CC_NUMPAD_FIRST + n; } else if (name[0] == 'F') { StringStream ss(name.substr(1)); int n; ss >> n; return CC_FUNCTION_FIRST + n - 1; } else { auto it = NameToKeyMap.find(name);// Add new Charcodes to NameToKeyMap if (it != NameToKeyMap.end()) return it->second; else if (name[0] == '\'') return name[1];//'c' } return '\0'; } /* List of Charcodes CC_BACKSPACE CC_TAB CC_NEW_LINE CC_CLEAR CC_RETURN CC_ENTER CC_SHIFT CC_CONTROL CC_ALT CC_PAUSE CC_CAPSLOCK CC_ESCAPE CC_SPACE CC_PAGE_UP CC_PAGE_DOWN CC_END CC_HOME CC_LEFT CC_UP CC_RIGHT CC_DOWN CC_PRINT_SCREEN CC_INSERT CC_DELETE CC_LSUPER CC_RSUPER CC_MULTIPLY CC_ADD CC_SUBTRACT CC_DECIMAL CC_DIVIDE CC_NUM_LOCK CC_SCROLL_LOCK CC_LSHIFT CC_RSHIFT CC_LCONTROL CC_RCONTROL CC_LMENU CC_RMENU */ }
22.426396
73
0.627433
LegendaryMauricius
8b29259ca6ff65382d92f2fdae9eff525497213d
1,250
cpp
C++
lang/cpp/cpp1114/for.cpp
yohshiy/programmers_notes
ececf1fc158ca8f541dc3ebc4310d2694c687ef5
[ "MIT" ]
null
null
null
lang/cpp/cpp1114/for.cpp
yohshiy/programmers_notes
ececf1fc158ca8f541dc3ebc4310d2694c687ef5
[ "MIT" ]
null
null
null
lang/cpp/cpp1114/for.cpp
yohshiy/programmers_notes
ececf1fc158ca8f541dc3ebc4310d2694c687ef5
[ "MIT" ]
null
null
null
/// /// 範囲 for サンプル /// /// g++ -std=c++14 for.cpp #include <iostream> #include <vector> #include <string> #include <map> using namespace std; int main() { // STL コンテナー vector<int> ary = { 3,2,9,6 }; for (auto elem : ary) { cout << elem << endl; } cout << endl; // 配列 int cary[] = { 3,2,9,6 }; for (auto elem : cary) { cout << elem << endl; } cout << endl; // 初期化リスト for (auto elem : { 3,2,9,6 }) { cout << elem << endl; } cout << endl; //////////////////////////////////////////////////////////////// vector<string> strs = { "foo", "bar", "baz" }; for (auto &elem : strs) { elem += "!"; } // { "foo!", "bar!", "baz!" } for (const auto &elem : strs) { cout << elem << endl; } cout << endl; //////////////////////////////////////////////////////////////// map<string, int> strmap = { { "foo", 3 }, { "bar", 2 }, { "baz", 9 } }; for (const auto &elem : strmap) { cout << elem.first << " - " << elem.second << endl; } //////////////////////////////////////////////////////////////// for (auto itr = ary.begin() ; itr != ary.end() ; itr++) { auto elem = *itr; // 要素に対する処理 } return 0; }
13.888889
66
0.3776
yohshiy
8b2a4df2e8ba9ffedd97f02d9cb7847b245de32f
131,701
cc
C++
vehicle/simvehicle.cc
vinijabes/simutrans
cb90d7e29e8f7910936d98733fe9fe5f24893535
[ "Artistic-1.0" ]
null
null
null
vehicle/simvehicle.cc
vinijabes/simutrans
cb90d7e29e8f7910936d98733fe9fe5f24893535
[ "Artistic-1.0" ]
null
null
null
vehicle/simvehicle.cc
vinijabes/simutrans
cb90d7e29e8f7910936d98733fe9fe5f24893535
[ "Artistic-1.0" ]
null
null
null
/* * This file is part of the Simutrans project under the Artistic License. * (see LICENSE.txt) */ #include <limits.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include "../boden/grund.h" #include "../boden/wege/runway.h" #include "../boden/wege/kanal.h" #include "../boden/wege/schiene.h" #include "../boden/wege/monorail.h" #include "../boden/wege/strasse.h" #include "../bauer/goods_manager.h" #include "../simworld.h" #include "../simdebug.h" #include "../simdepot.h" #include "../simconvoi.h" #include "../simunits.h" #include "../player/simplay.h" #include "../simfab.h" #include "../simware.h" #include "../simhalt.h" #include "../simsound.h" #include "../display/simimg.h" #include "../simmesg.h" #include "../simcolor.h" #include "../display/simgraph.h" #include "../simline.h" #include "../simintr.h" #include "../obj/wolke.h" #include "../obj/signal.h" #include "../obj/roadsign.h" #include "../obj/crossing.h" #include "../obj/zeiger.h" #include "../gui/minimap.h" #include "../descriptor/citycar_desc.h" #include "../descriptor/goods_desc.h" #include "../descriptor/skin_desc.h" #include "../descriptor/roadsign_desc.h" #include "../dataobj/schedule.h" #include "../dataobj/translator.h" #include "../dataobj/loadsave.h" #include "../dataobj/environment.h" #include "../utils/simstring.h" #include "../utils/cbuffer_t.h" #include "../bauer/vehikelbauer.h" #include "simvehicle.h" #include "simroadtraffic.h" /* get dx and dy from dir (just to remind you) * any vehicle (including city cars and pedestrians) * will go this distance per sync step. * (however, the real dirs are only calculated during display, these are the old ones) */ sint8 vehicle_base_t::dxdy[ 8*2 ] = { -2, 1, // s -2, -1, // w -4, 0, // sw 0, 2, //se 2, -1, // n 2, 1, // e 4, 0, // ne 0, -2 // nw }; // Constants uint8 vehicle_base_t::old_diagonal_vehicle_steps_per_tile = 128; uint8 vehicle_base_t::diagonal_vehicle_steps_per_tile = 181; uint16 vehicle_base_t::diagonal_multiplier = 724; // set only once, before loading! void vehicle_base_t::set_diagonal_multiplier( uint32 multiplier, uint32 old_diagonal_multiplier ) { diagonal_multiplier = (uint16)multiplier; diagonal_vehicle_steps_per_tile = (uint8)(130560u/diagonal_multiplier) + 1; old_diagonal_vehicle_steps_per_tile = (uint8)(130560u/old_diagonal_multiplier) + 1; } // if true, convoi, must restart! bool vehicle_base_t::need_realignment() const { return old_diagonal_vehicle_steps_per_tile!=diagonal_vehicle_steps_per_tile && ribi_t::is_bend(direction); } // [0]=xoff [1]=yoff sint8 vehicle_base_t::driveleft_base_offsets[8][2] = { { 12, 6 }, { -12, 6 }, { 0, 6 }, { 12, 0 }, { -12, -6 }, { 12, -6 }, { 0, -6 }, { -12, 0 } // { 12, -12, 0, 12, -12, 12, 0 -12 }, // { 6, 6, 6, 0, -6, -6, -6, 0 } }; // [0]=xoff [1]=yoff sint8 vehicle_base_t::overtaking_base_offsets[8][2]; // recalc offsets for overtaking void vehicle_base_t::set_overtaking_offsets( bool driving_on_the_left ) { sint8 sign = driving_on_the_left ? -1 : 1; // a tile has the internal size of const sint8 XOFF=12; const sint8 YOFF=6; overtaking_base_offsets[0][0] = sign * XOFF; overtaking_base_offsets[1][0] = -sign * XOFF; overtaking_base_offsets[2][0] = 0; overtaking_base_offsets[3][0] = sign * XOFF; overtaking_base_offsets[4][0] = -sign * XOFF; overtaking_base_offsets[5][0] = sign * XOFF; overtaking_base_offsets[6][0] = 0; overtaking_base_offsets[7][0] = sign * (-XOFF-YOFF); overtaking_base_offsets[0][1] = sign * YOFF; overtaking_base_offsets[1][1] = sign * YOFF; overtaking_base_offsets[2][1] = sign * YOFF; overtaking_base_offsets[3][1] = 0; overtaking_base_offsets[4][1] = -sign * YOFF; overtaking_base_offsets[5][1] = -sign * YOFF; overtaking_base_offsets[6][1] = -sign * YOFF; overtaking_base_offsets[7][1] = 0; } /** * Checks if this vehicle must change the square upon next move * THIS IS ONLY THERE FOR LOADING OLD SAVES! */ bool vehicle_base_t::is_about_to_hop( const sint8 neu_xoff, const sint8 neu_yoff ) const { const sint8 y_off_2 = 2*neu_yoff; const sint8 c_plus = y_off_2 + neu_xoff; const sint8 c_minus = y_off_2 - neu_xoff; return ! (c_plus < OBJECT_OFFSET_STEPS*2 && c_minus < OBJECT_OFFSET_STEPS*2 && c_plus > -OBJECT_OFFSET_STEPS*2 && c_minus > -OBJECT_OFFSET_STEPS*2); } vehicle_base_t::vehicle_base_t(): obj_t() { image = IMG_EMPTY; set_flag( obj_t::is_vehicle ); steps = 0; steps_next = VEHICLE_STEPS_PER_TILE - 1; use_calc_height = true; dx = 0; dy = 0; zoff_start = zoff_end = 0; disp_lane = 2; } vehicle_base_t::vehicle_base_t(koord3d pos): obj_t(pos) { image = IMG_EMPTY; set_flag( obj_t::is_vehicle ); pos_next = pos; steps = 0; steps_next = VEHICLE_STEPS_PER_TILE - 1; use_calc_height = true; dx = 0; dy = 0; zoff_start = zoff_end = 0; disp_lane = 2; } void vehicle_base_t::rotate90() { koord3d pos_cur = get_pos(); pos_cur.rotate90( welt->get_size().y-1 ); set_pos( pos_cur ); // directions are counterclockwise to ribis! direction = ribi_t::rotate90( direction ); pos_next.rotate90( welt->get_size().y-1 ); // new offsets: very tricky ... sint8 new_dx = -dy*2; dy = dx/2; dx = new_dx; // new pos + step offsets (only possible, since we know the height! sint8 neu_yoff = get_xoff()/2; set_xoff( -get_yoff()*2 ); set_yoff( neu_yoff ); // adjust disp_lane individually } void vehicle_base_t::leave_tile() { // first: release crossing grund_t *gr = welt->lookup(get_pos()); if( gr && gr->ist_uebergang() ) { crossing_t *cr = gr->find<crossing_t>(2); grund_t *gr2 = welt->lookup(pos_next); if( gr2==NULL || gr2==gr || !gr2->ist_uebergang() || cr->get_logic()!=gr2->find<crossing_t>(2)->get_logic() ) { cr->release_crossing(this); } } // then remove from ground (or search whole map, if failed) if(!get_flag(not_on_map) && (gr==NULL || !gr->obj_remove(this)) ) { // was not removed (not found?) dbg->error("vehicle_base_t::leave_tile()","'typ %i' %p could not be removed from %d %d", get_typ(), this, get_pos().x, get_pos().y); DBG_MESSAGE("vehicle_base_t::leave_tile()","checking all plan squares"); // check, whether it is on another height ... const planquadrat_t *pl = welt->access( get_pos().get_2d() ); if( pl ) { gr = pl->get_boden_von_obj(this); if( gr ) { gr->obj_remove(this); dbg->warning("vehicle_base_t::leave_tile()","removed vehicle typ %i (%p) from %d %d",get_typ(), this, get_pos().x, get_pos().y); } return; } koord k; bool ok = false; for(k.y=0; k.y<welt->get_size().y; k.y++) { for(k.x=0; k.x<welt->get_size().x; k.x++) { grund_t *gr = welt->access( k )->get_boden_von_obj(this); if(gr && gr->obj_remove(this)) { dbg->warning("vehicle_base_t::leave_tile()","removed vehicle typ %i (%p) from %d %d",get_name(), this, k.x, k.y); ok = true; } } } if(!ok) { dbg->error("vehicle_base_t::leave_tile()","'%s' %p was not found on any map square!",get_name(), this); } } } void vehicle_base_t::enter_tile(grund_t* gr) { if(!gr) { dbg->error("vehicle_base_t::enter_tile()","'%s' new position (%i,%i,%i)!",get_name(), get_pos().x, get_pos().y, get_pos().z ); gr = welt->lookup_kartenboden(get_pos().get_2d()); set_pos( gr->get_pos() ); } gr->obj_add(this); } /* THE routine for moving vehicles * it will drive on as log as it can * @return the distance actually traveled */ uint32 vehicle_base_t::do_drive(uint32 distance) { uint32 steps_to_do = distance >> YARDS_PER_VEHICLE_STEP_SHIFT; if( steps_to_do == 0 ) { // ok, we will not move in this steps return 0; } // ok, so moving ... if( !get_flag(obj_t::dirty) ) { mark_image_dirty( image, 0 ); set_flag( obj_t::dirty ); } grund_t *gr = NULL; // if hopped, then this is new position uint32 steps_target = steps_to_do + steps; uint32 distance_travelled; // Return value if( steps_target > steps_next ) { // We are going far enough to hop. // We'll be adding steps_next+1 for each hop, as if we // started at the beginning of this tile, so for an accurate // count of steps done we must subtract the location we started with. sint32 steps_done = -steps; // Hop as many times as possible. while( steps_target > steps_next && (gr = hop_check()) ) { // now do the update for hopping steps_target -= steps_next+1; steps_done += steps_next+1; koord pos_prev(get_pos().get_2d()); hop(gr); use_calc_height = true; // set offsets set_xoff( (dx<0) ? OBJECT_OFFSET_STEPS : -OBJECT_OFFSET_STEPS ); set_yoff( (dy<0) ? OBJECT_OFFSET_STEPS/2 : -OBJECT_OFFSET_STEPS/2 ); if(dx*dy==0) { if(dx==0) { if(dy>0) { set_xoff( pos_prev.x!=get_pos().x ? -OBJECT_OFFSET_STEPS : OBJECT_OFFSET_STEPS ); } else { set_xoff( pos_prev.x!=get_pos().x ? OBJECT_OFFSET_STEPS : -OBJECT_OFFSET_STEPS ); } } else { if(dx>0) { set_yoff( pos_prev.y!=get_pos().y ? OBJECT_OFFSET_STEPS/2 : -OBJECT_OFFSET_STEPS/2 ); } else { set_yoff( pos_prev.y!=get_pos().y ? -OBJECT_OFFSET_STEPS/2 : OBJECT_OFFSET_STEPS/2 ); } } } } if( steps_next == 0 ) { // only needed for aircrafts, which can turn on the same tile // the indicate the turn with this here steps_next = VEHICLE_STEPS_PER_TILE - 1; steps_target = VEHICLE_STEPS_PER_TILE - 1; steps_done -= VEHICLE_STEPS_PER_TILE - 1; } // Update internal status, how far we got within the tile. if( steps_target <= steps_next ) { steps = steps_target; } else { // could not go as far as we wanted (hop_check failed) => stop at end of tile steps = steps_next; } steps_done += steps; distance_travelled = steps_done << YARDS_PER_VEHICLE_STEP_SHIFT; } else { // Just travel to target, it's on same tile steps = steps_target; distance_travelled = distance & YARDS_VEHICLE_STEP_MASK; // round down to nearest step } if(use_calc_height) { calc_height(gr); } // remaining steps return distance_travelled; } // to make smaller steps than the tile granularity, we have to use this trick void vehicle_base_t::get_screen_offset( int &xoff, int &yoff, const sint16 raster_width ) const { // vehicles needs finer steps to appear smoother sint32 display_steps = (uint32)steps*(uint16)raster_width; if(dx && dy) { display_steps &= 0xFFFFFC00; } else { display_steps = (display_steps*diagonal_multiplier)>>10; } xoff += (display_steps*dx) >> 10; yoff += ((display_steps*dy) >> 10) + (get_hoff(raster_width))/(4*16); } // calcs new direction and applies it to the vehicles ribi_t::ribi vehicle_base_t::calc_set_direction(const koord3d& start, const koord3d& ende) { ribi_t::ribi direction = ribi_t::none; const sint8 di = ende.x - start.x; const sint8 dj = ende.y - start.y; if(dj < 0 && di == 0) { direction = ribi_t::north; dx = 2; dy = -1; steps_next = VEHICLE_STEPS_PER_TILE - 1; } else if(dj > 0 && di == 0) { direction = ribi_t::south; dx = -2; dy = 1; steps_next = VEHICLE_STEPS_PER_TILE - 1; } else if(di < 0 && dj == 0) { direction = ribi_t::west; dx = -2; dy = -1; steps_next = VEHICLE_STEPS_PER_TILE - 1; } else if(di >0 && dj == 0) { direction = ribi_t::east; dx = 2; dy = 1; steps_next = VEHICLE_STEPS_PER_TILE - 1; } else if(di > 0 && dj > 0) { direction = ribi_t::southeast; dx = 0; dy = 2; steps_next = diagonal_vehicle_steps_per_tile - 1; } else if(di < 0 && dj < 0) { direction = ribi_t::northwest; dx = 0; dy = -2; steps_next = diagonal_vehicle_steps_per_tile - 1; } else if(di > 0 && dj < 0) { direction = ribi_t::northeast; dx = 4; dy = 0; steps_next = diagonal_vehicle_steps_per_tile - 1; } else { direction = ribi_t::southwest; dx = -4; dy = 0; steps_next = diagonal_vehicle_steps_per_tile - 1; } // we could artificially make diagonals shorter: but this would break existing game behaviour return direction; } // this routine calculates the new height // beware of bridges, tunnels, slopes, ... void vehicle_base_t::calc_height(grund_t *gr) { use_calc_height = false; // assume, we are only needed after next hop zoff_start = zoff_end = 0; // assume flat way if(gr==NULL) { gr = welt->lookup(get_pos()); } if(gr==NULL) { // slope changed below a moving thing?!? return; } else if( gr->ist_tunnel() && gr->ist_karten_boden() && !is_flying() ) { use_calc_height = true; // to avoid errors if underground mode is switched if( grund_t::underground_mode == grund_t::ugm_none || (grund_t::underground_mode == grund_t::ugm_level && gr->get_hoehe() < grund_t::underground_level) ) { // need hiding? One of the few uses of XOR: not half driven XOR exiting => not hide! ribi_t::ribi hang_ribi = ribi_type( gr->get_grund_hang() ); if((steps<(steps_next/2)) ^ ((hang_ribi&direction)!=0) ) { set_image(IMG_EMPTY); } else { calc_image(); } } } else { // force a valid image above ground, with special handling of tunnel entraces if( get_image()==IMG_EMPTY ) { if( !gr->ist_tunnel() && gr->ist_karten_boden() ) { calc_image(); } } // will not work great with ways, but is very short! slope_t::type hang = gr->get_weg_hang(); if( hang ) { const uint slope_height = (hang & 7) ? 1 : 2; ribi_t::ribi hang_ribi = ribi_type(hang); if( ribi_t::doubles(hang_ribi) == ribi_t::doubles(direction)) { zoff_start = hang_ribi & direction ? 2*slope_height : 0; // 0 .. 4 zoff_end = hang_ribi & ribi_t::backward(direction) ? 2*slope_height : 0; // 0 .. 4 } else { // only for shadows and movingobjs ... zoff_start = hang_ribi & direction ? slope_height+1 : 0; // 0 .. 3 zoff_end = hang_ribi & ribi_t::backward(direction) ? slope_height+1 : 0; // 0 .. 3 } } else { zoff_start = (gr->get_weg_yoff() * 2) / TILE_HEIGHT_STEP; zoff_end = zoff_start; } } } sint16 vehicle_base_t::get_hoff(const sint16 raster_width) const { sint16 h_start = -(sint8)TILE_HEIGHT_STEP * (sint8)zoff_start; sint16 h_end = -(sint8)TILE_HEIGHT_STEP * (sint8)zoff_end; return ((h_start*steps + h_end*(256-steps))*raster_width) >> 9; } /* true, if one could pass through this field * also used for citycars, thus defined here */ vehicle_base_t *vehicle_base_t::no_cars_blocking( const grund_t *gr, const convoi_t *cnv, const uint8 current_direction, const uint8 next_direction, const uint8 next_90direction ) { // Search vehicle for( uint8 pos=1; pos<(uint8)gr->get_top(); pos++ ) { if( vehicle_base_t* const v = obj_cast<vehicle_base_t>(gr->obj_bei(pos)) ) { if( v->get_typ()==obj_t::pedestrian ) { continue; } // check for car uint8 other_direction=255; bool other_moving = false; if( road_vehicle_t const* const at = obj_cast<road_vehicle_t>(v) ) { // ignore ourself if( cnv == at->get_convoi() ) { continue; } other_direction = at->get_direction(); other_moving = at->get_convoi()->get_akt_speed() > kmh_to_speed(1); } // check for city car else if( v->get_waytype() == road_wt ) { other_direction = v->get_direction(); if( private_car_t const* const sa = obj_cast<private_car_t>(v) ){ other_moving = sa->get_current_speed() > 1; } } // ok, there is another car ... if( other_direction != 255 ) { if( next_direction == other_direction && !ribi_t::is_threeway(gr->get_weg_ribi(road_wt)) ) { // cars going in the same direction and no crossing => that mean blocking ... return v; } const ribi_t::ribi other_90direction = (gr->get_pos().get_2d() == v->get_pos_next().get_2d()) ? other_direction : calc_direction(gr->get_pos(), v->get_pos_next()); if( other_90direction == next_90direction ) { // Want to exit in same as other ~50% of the time return v; } const bool drives_on_left = welt->get_settings().is_drive_left(); const bool across = next_direction == (drives_on_left ? ribi_t::rotate45l(next_90direction) : ribi_t::rotate45(next_90direction)); // turning across the opposite directions lane const bool other_across = other_direction == (drives_on_left ? ribi_t::rotate45l(other_90direction) : ribi_t::rotate45(other_90direction)); // other is turning across the opposite directions lane if( other_direction == next_direction && !(other_across || across) ) { // entering same straight waypoint as other ~18% return v; } const bool straight = next_direction == next_90direction; // driving straight const ribi_t::ribi current_90direction = straight ? ribi_t::backward(next_90direction) : (~(next_direction|ribi_t::backward(next_90direction)))&0x0F; const bool other_straight = other_direction == other_90direction; // other is driving straight const bool other_exit_same_side = current_90direction == other_90direction; // other is exiting same side as we're entering const bool other_exit_opposite_side = ribi_t::backward(current_90direction) == other_90direction; // other is exiting side across from where we're entering if( across && ((ribi_t::is_perpendicular(current_90direction,other_direction) && other_moving) || (other_across && other_exit_opposite_side) || ((other_across || other_straight) && other_exit_same_side && other_moving) ) ) { // other turning across in front of us from orth entry dir'n ~4% return v; } const bool headon = ribi_t::backward(current_direction) == other_direction; // we're meeting the other headon const bool other_exit_across = (drives_on_left ? ribi_t::rotate90l(next_90direction) : ribi_t::rotate90(next_90direction)) == other_90direction; // other is exiting by turning across the opposite directions lane if( straight && (ribi_t::is_perpendicular(current_90direction,other_direction) || (other_across && other_moving && (other_exit_across || (other_exit_same_side && !headon))) ) ) { // other turning across in front of us, but allow if other is stopped - duplicating historic behaviour ~2% return v; } else if( other_direction == current_direction && current_90direction == ribi_t::none ) { // entering same diagonal waypoint as other ~1% return v; } // else other car is not blocking ~25% } } } // way is free return NULL; } void vehicle_t::rotate90() { vehicle_base_t::rotate90(); previous_direction = ribi_t::rotate90( previous_direction ); last_stop_pos.rotate90( welt->get_size().y-1 ); } void vehicle_t::rotate90_freight_destinations(const sint16 y_size) { // now rotate the freight FOR(slist_tpl<ware_t>, & tmp, fracht) { tmp.rotate90(y_size ); } } void vehicle_t::set_convoi(convoi_t *c) { /* cnv can have three values: * NULL: not previously assigned * 1 (only during loading): convoi wants to reserve the whole route * other: previous convoi (in this case, currently always c==cnv) * * if c is NULL, then the vehicle is removed from the convoi * (the rail_vehicle_t::set_convoi etc. routines must then remove a * possibly pending reservation of stops/tracks) */ assert( c==NULL || cnv==NULL || cnv==(convoi_t *)1 || c==cnv); cnv = c; if(cnv) { // we need to re-establish the finish flag after loading if(leading) { route_t const& r = *cnv->get_route(); check_for_finish = r.empty() || route_index >= r.get_count() || get_pos() == r.at(route_index); } if( pos_next != koord3d::invalid ) { route_t const& r = *cnv->get_route(); if (!r.empty() && route_index < r.get_count() - 1) { grund_t const* const gr = welt->lookup(pos_next); if (!gr || !gr->get_weg(get_waytype())) { if (!(water_wt == get_waytype() && gr->is_water())) { // ships on the open sea are valid pos_next = r.at(route_index + 1U); } } } } // just correct freight destinations FOR(slist_tpl<ware_t>, & c, fracht) { c.finish_rd(welt); } } } /** * Unload freight to halt * @return sum of unloaded goods */ uint16 vehicle_t::unload_cargo(halthandle_t halt, bool unload_all ) { uint16 sum_menge = 0, sum_delivered = 0, index = 0; if( !halt.is_bound() ) { return 0; } if( halt->is_enabled( get_cargo_type() ) ) { if( !fracht.empty() ) { for( slist_tpl<ware_t>::iterator i = fracht.begin(), end = fracht.end(); i != end; ) { const ware_t& tmp = *i; halthandle_t end_halt = tmp.get_ziel(); halthandle_t via_halt = tmp.get_zwischenziel(); // check if destination or transfer is still valid if( !end_halt.is_bound() || !via_halt.is_bound() ) { // target halt no longer there => delete and remove from fab in transit fabrik_t::update_transit( &tmp, false ); DBG_MESSAGE("vehicle_t::unload_freight()", "destination of %d %s is no longer reachable",tmp.menge,translator::translate(tmp.get_name())); total_freight -= tmp.menge; sum_weight -= tmp.menge * tmp.get_desc()->get_weight_per_unit(); i = fracht.erase( i ); } else if( end_halt == halt || via_halt == halt || unload_all ) { // printf("Liefere %d %s nach %s via %s an %s\n", // tmp->menge, // tmp->name(), // end_halt->get_name(), // via_halt->get_name(), // halt->get_name()); // here, only ordinary goods should be processed int menge = halt->liefere_an(tmp); sum_menge += menge; total_freight -= menge; sum_weight -= tmp.menge * tmp.get_desc()->get_weight_per_unit(); index = tmp.get_index(); if(end_halt==halt) { sum_delivered += menge; } i = fracht.erase( i ); } else { ++i; } } } } if( sum_menge ) { // book transported goods get_owner()->book_transported( sum_menge, get_desc()->get_waytype(), index ); if( sum_delivered ) { // book delivered goods to destination get_owner()->book_delivered( sum_delivered, get_desc()->get_waytype(), index ); } // add delivered goods to statistics cnv->book( sum_menge, convoi_t::CONVOI_TRANSPORTED_GOODS ); // add delivered goods to halt's statistics halt->book( sum_menge, HALT_ARRIVED ); } return sum_menge; } /** * Load freight from halt * @return amount loaded */ uint16 vehicle_t::load_cargo(halthandle_t halt, const vector_tpl<halthandle_t>& destination_halts) { if( !halt.is_bound() || !halt->gibt_ab(desc->get_freight_type()) ) { return 0; } const uint16 total_freight_start = total_freight; const uint16 capacity_left = desc->get_capacity() - total_freight; if (capacity_left > 0) { slist_tpl<ware_t> freight_add; halt->fetch_goods( freight_add, desc->get_freight_type(), capacity_left, destination_halts); if( freight_add.empty() ) { // now empty, but usually, we can get it here ... return 0; } for( slist_tpl<ware_t>::iterator iter_z = freight_add.begin(); iter_z != freight_add.end(); ) { ware_t &ware = *iter_z; total_freight += ware.menge; sum_weight += ware.menge * ware.get_desc()->get_weight_per_unit(); // could this be joined with existing freight? FOR( slist_tpl<ware_t>, & tmp, fracht ) { // for pax: join according next stop // for all others we *must* use target coordinates if( ware.same_destination(tmp) ) { tmp.menge += ware.menge; ware.menge = 0; break; } } // if != 0 we could not join it to existing => load it if( ware.menge != 0 ) { ++iter_z; // we add list directly } else { iter_z = freight_add.erase(iter_z); } } if( !freight_add.empty() ) { fracht.append_list(freight_add); } } return total_freight - total_freight_start; } /** * Remove freight that no longer can reach it's destination * i.e. because of a changed schedule */ void vehicle_t::remove_stale_cargo() { DBG_DEBUG("vehicle_t::remove_stale_cargo()", "called"); // and now check every piece of ware on board, // if its target is somewhere on // the new schedule, if not -> remove slist_tpl<ware_t> kill_queue; total_freight = 0; if (!fracht.empty()) { FOR(slist_tpl<ware_t>, & tmp, fracht) { bool found = false; if( tmp.get_zwischenziel().is_bound() ) { // the original halt exists, but does we still go there? FOR(minivec_tpl<schedule_entry_t>, const& i, cnv->get_schedule()->entries) { if( haltestelle_t::get_halt( i.pos, cnv->get_owner()) == tmp.get_zwischenziel() ) { found = true; break; } } } if( !found ) { // the target halt may have been joined or there is a closer one now, thus our original target is no longer valid const int offset = cnv->get_schedule()->get_current_stop(); const int max_count = cnv->get_schedule()->entries.get_count(); for( int i=0; i<max_count; i++ ) { // try to unload on next stop halthandle_t halt = haltestelle_t::get_halt( cnv->get_schedule()->entries[ (i+offset)%max_count ].pos, cnv->get_owner() ); if( halt.is_bound() ) { if( halt->is_enabled(tmp.get_index()) ) { // ok, lets change here, since goods are accepted here tmp.access_zwischenziel() = halt; if (!tmp.get_ziel().is_bound()) { // set target, to prevent that unload_freight drops cargo tmp.set_ziel( halt ); } found = true; break; } } } } if( !found ) { kill_queue.insert(tmp); } else { // since we need to point at factory (0,0), we recheck this too koord k = tmp.get_zielpos(); fabrik_t *fab = fabrik_t::get_fab( k ); tmp.set_zielpos( fab ? fab->get_pos().get_2d() : k ); total_freight += tmp.menge; } } FOR(slist_tpl<ware_t>, const& c, kill_queue) { fabrik_t::update_transit( &c, false ); fracht.remove(c); } } sum_weight = get_cargo_weight() + desc->get_weight(); } void vehicle_t::play_sound() const { if( desc->get_sound() >= 0 && !welt->is_fast_forward() ) { welt->play_sound_area_clipped(get_pos().get_2d(), desc->get_sound(), TRAFFIC_SOUND ); } } /** * Prepare vehicle for new ride. * Sets route_index, pos_next, steps_next. * If @p recalc is true this sets position and recalculates/resets movement parameters. */ void vehicle_t::initialise_journey(uint16 start_route_index, bool recalc) { route_index = start_route_index+1; check_for_finish = false; use_calc_height = true; if(welt->is_within_limits(get_pos().get_2d())) { mark_image_dirty( get_image(), 0 ); } route_t const& r = *cnv->get_route(); if(!recalc) { // always set pos_next pos_next = r.at(route_index); assert(get_pos() == r.at(start_route_index)); } else { // set pos_next if (route_index < r.get_count()) { pos_next = r.at(route_index); } else { // already at end of route check_for_finish = true; } set_pos(r.at(start_route_index)); // recalc directions previous_direction = direction; direction = calc_set_direction( get_pos(), pos_next ); zoff_start = zoff_end = 0; steps = 0; set_xoff( (dx<0) ? OBJECT_OFFSET_STEPS : -OBJECT_OFFSET_STEPS ); set_yoff( (dy<0) ? OBJECT_OFFSET_STEPS/2 : -OBJECT_OFFSET_STEPS/2 ); calc_image(); } if ( ribi_t::is_single(direction) ) { steps_next = VEHICLE_STEPS_PER_TILE - 1; } else { steps_next = diagonal_vehicle_steps_per_tile - 1; } } vehicle_t::vehicle_t(koord3d pos, const vehicle_desc_t* desc, player_t* player) : vehicle_base_t(pos) { this->desc = desc; set_owner( player ); purchase_time = welt->get_current_month(); cnv = NULL; speed_limit = SPEED_UNLIMITED; route_index = 1; smoke = true; direction = ribi_t::none; current_friction = 4; total_freight = 0; sum_weight = desc->get_weight(); leading = last = false; check_for_finish = false; use_calc_height = true; has_driven = false; previous_direction = direction = ribi_t::none; target_halt = halthandle_t(); } vehicle_t::vehicle_t() : vehicle_base_t() { smoke = true; desc = NULL; cnv = NULL; route_index = 1; current_friction = 4; sum_weight = 10; total_freight = 0; leading = last = false; check_for_finish = false; use_calc_height = true; previous_direction = direction = ribi_t::none; } bool vehicle_t::calc_route(koord3d start, koord3d ziel, sint32 max_speed, route_t* route) { return route->calc_route(welt, start, ziel, this, max_speed, 0 ); } grund_t* vehicle_t::hop_check() { // the leading vehicle will do all the checks if(leading) { if(check_for_finish) { // so we are there yet? cnv->ziel_erreicht(); if(cnv->get_state()==convoi_t::INITIAL) { // to avoid crashes with airplanes use_calc_height = false; } return NULL; } // now check, if we can go here grund_t *bd = welt->lookup(pos_next); if(bd==NULL || !check_next_tile(bd) || cnv->get_route()->empty()) { // way (weg) not existent (likely destroyed) or no route ... cnv->suche_neue_route(); return NULL; } // check for one-way sign etc. const waytype_t wt = get_waytype(); if( air_wt != wt && route_index < cnv->get_route()->get_count()-1 ) { uint8 dir = get_ribi(bd); koord3d nextnext_pos = cnv->get_route()->at(route_index+1); if ( nextnext_pos == get_pos() ) { dbg->error("vehicle_t::hop_check", "route contains point (%s) twice for %s", nextnext_pos.get_str(), cnv->get_name()); } uint8 new_dir = ribi_type(nextnext_pos - pos_next); if((dir&new_dir)==0) { // new one way sign here? cnv->suche_neue_route(); return NULL; } // check for recently built bridges/tunnels or reverse branches (really slows down the game, so we do this only on slopes) if( bd->get_weg_hang() ) { grund_t *from; if( !bd->get_neighbour( from, get_waytype(), ribi_type( get_pos(), pos_next ) ) ) { // way likely destroyed or altered => reroute cnv->suche_neue_route(); return NULL; } } } sint32 restart_speed = -1; // ist_weg_frei() berechnet auch die Geschwindigkeit // mit der spaeter weitergefahren wird if( !can_enter_tile( bd, restart_speed, 0 ) ) { // stop convoi, when the way is not free cnv->warten_bis_weg_frei(restart_speed); // don't continue return NULL; } // we cache it here, hop() will use it to save calls to karte_t::lookup return bd; } else { // this is needed since in convoi_t::vorfahren the flag 'leading' is set to null if(check_for_finish) { return NULL; } } return welt->lookup(pos_next); } bool vehicle_t::can_enter_tile(sint32 &restart_speed, uint8 second_check_count) { grund_t *gr = welt->lookup( pos_next ); if( gr ) { return can_enter_tile( gr, restart_speed, second_check_count ); } else { if( !second_check_count ) { cnv->suche_neue_route(); } return false; } } void vehicle_t::leave_tile() { vehicle_base_t::leave_tile(); #ifndef DEBUG_ROUTES if(last && minimap_t::is_visible) { minimap_t::get_instance()->calc_map_pixel(get_pos().get_2d()); } #endif } /** this routine add a vehicle to a tile and will insert it in the correct sort order to prevent overlaps */ void vehicle_t::enter_tile(grund_t* gr) { vehicle_base_t::enter_tile(gr); if(leading && minimap_t::is_visible ) { minimap_t::get_instance()->calc_map_pixel( get_pos().get_2d() ); } } void vehicle_t::hop(grund_t* gr) { leave_tile(); koord3d pos_prev = get_pos(); set_pos( pos_next ); // next field if(route_index<cnv->get_route()->get_count()-1) { route_index ++; pos_next = cnv->get_route()->at(route_index); } else { route_index ++; check_for_finish = true; } previous_direction = direction; // check if arrived at waypoint, and update schedule to next destination // route search through the waypoint is already complete if( get_pos()==cnv->get_schedule_target() ) { if( route_index >= cnv->get_route()->get_count() ) { // we end up here after loading a game or when a waypoint is reached which crosses next itself cnv->set_schedule_target( koord3d::invalid ); } else { cnv->get_schedule()->advance(); const koord3d ziel = cnv->get_schedule()->get_current_entry().pos; cnv->set_schedule_target( cnv->is_waypoint(ziel) ? ziel : koord3d::invalid ); } } // this is a required hack for aircrafts! Aircrafts can turn on a single square, and this confuses the previous calculation! if(!check_for_finish && pos_prev==pos_next) { direction = calc_set_direction( get_pos(), pos_next); steps_next = 0; } else { if( pos_next!=get_pos() ) { direction = calc_set_direction( pos_prev, pos_next ); } else if( ( check_for_finish && welt->lookup(pos_next) && ribi_t::is_straight(welt->lookup(pos_next)->get_weg_ribi_unmasked(get_waytype())) ) || welt->lookup(pos_next)->is_halt()) { // allow diagonal stops at waypoints on diagonal tracks but avoid them on halts and at straight tracks... direction = calc_set_direction( pos_prev, pos_next ); } } // change image if direction changes if (previous_direction != direction) { calc_image(); } sint32 old_speed_limit = speed_limit; enter_tile(gr); const weg_t *weg = gr->get_weg(get_waytype()); if( weg ) { speed_limit = kmh_to_speed( weg->get_max_speed() ); if( weg->is_crossing() ) { gr->find<crossing_t>(2)->add_to_crossing(this); } } else { speed_limit = SPEED_UNLIMITED; } if( leading ) { if( check_for_finish && (direction==ribi_t::north || direction==ribi_t::west) ) { steps_next = (steps_next/2)+1; } cnv->add_running_cost( weg ); cnv->must_recalc_data_front(); } // update friction and friction weight of convoy sint16 old_friction = current_friction; calc_friction(gr); if (old_friction != current_friction) { cnv->update_friction_weight( (current_friction-old_friction) * (sint64)sum_weight); } // if speed limit changed, then cnv must recalc if (speed_limit != old_speed_limit) { if (speed_limit < old_speed_limit) { if (speed_limit < cnv->get_speed_limit()) { // update cnv->set_speed_limit(speed_limit); } } else { if (old_speed_limit == cnv->get_speed_limit()) { // convoy's speed limit may be larger now cnv->must_recalc_speed_limit(); } } } } /** calculates the current friction coefficient based on the current track * flat, slope, curve ... */ void vehicle_t::calc_friction(const grund_t *gr) { // assume straight flat track current_friction = 1; // curve: higher friction if(previous_direction != direction) { current_friction = 8; } // or a hill? const slope_t::type hang = gr->get_weg_hang(); if( hang != slope_t::flat ) { const uint slope_height = (hang & 7) ? 1 : 2; if( ribi_type(hang) == direction ) { // hill up, since height offsets are negative: heavy decelerate current_friction += 15 * slope_height * slope_height; } else { // hill down: accelerate current_friction += -7 * slope_height * slope_height; } } } void vehicle_t::make_smoke() const { // does it smoke at all? if( smoke && desc->get_smoke() ) { // only produce smoke when heavily accelerating or steam engine if( cnv->get_akt_speed() < (sint32)((cnv->get_speed_limit() * 7u) >> 3) || desc->get_engine_type() == vehicle_desc_t::steam ) { grund_t* const gr = welt->lookup( get_pos() ); if( gr ) { wolke_t* const abgas = new wolke_t( get_pos(), get_xoff() + ((dx * (sint16)((uint16)steps * OBJECT_OFFSET_STEPS)) >> VEHICLE_STEPS_PER_TILE_SHIFT), get_yoff() + ((dy * (sint16)((uint16)steps * OBJECT_OFFSET_STEPS)) >> VEHICLE_STEPS_PER_TILE_SHIFT), get_hoff() - LEGACY_SMOKE_YOFFSET, DEFAULT_EXHAUSTSMOKE_TIME, DEFAULT_SMOKE_UPLIFT, desc->get_smoke() ); if( !gr->obj_add( abgas ) ) { abgas->set_flag( obj_t::not_on_map ); delete abgas; } else { welt->sync_way_eyecandy.add( abgas ); } } } } } /** * Payment is done per hop. It iterates all goods and calculates * the income for the last hop. This method must be called upon * every stop. * @return income total for last hop */ sint64 vehicle_t::calc_revenue(const koord3d& start, const koord3d& end) const { // may happen when waiting in station if (start == end || fracht.empty()) { return 0; } // cnv_kmh = lesser of min_top_speed, power limited top speed, and average way speed limits on trip, except aircraft which are not power limited and don't have speed limits sint32 cnv_kmh = cnv->get_speedbonus_kmh(); sint64 value = 0; // cache speedbonus price const goods_desc_t* last_freight = NULL; sint64 freight_revenue = 0; sint32 dist = 0; if( welt->get_settings().get_pay_for_total_distance_mode() == settings_t::TO_PREVIOUS ) { // pay distance traveled dist = koord_distance( start, end ); } FOR(slist_tpl<ware_t>, const& ware, fracht) { if( ware.menge==0 ) { continue; } // which distance will be paid? switch(welt->get_settings().get_pay_for_total_distance_mode()) { case settings_t::TO_TRANSFER: { // pay distance traveled to next transfer stop // now only use the real gain in difference for the revenue (may as well be negative!) if (ware.get_zwischenziel().is_bound()) { const koord &zwpos = ware.get_zwischenziel()->get_basis_pos(); // cast of koord_distance to sint32 is necessary otherwise the r-value would be interpreted as unsigned, leading to overflows dist = (sint32)koord_distance( zwpos, start ) - (sint32)koord_distance( end, zwpos ); } else { dist = koord_distance( end, start ); } break; } case settings_t::TO_DESTINATION: { // pay only the distance, we get closer to our destination // now only use the real gain in difference for the revenue (may as well be negative!) const koord &zwpos = ware.get_zielpos(); // cast of koord_distance to sint32 is necessary otherwise the r-value would be interpreted as unsigned, leading to overflows dist = (sint32)koord_distance( zwpos, start ) - (sint32)koord_distance( end, zwpos ); break; } default: ; // no need to recompute } // calculate freight revenue incl. speed-bonus if (ware.get_desc() != last_freight) { freight_revenue = ware_t::calc_revenue(ware.get_desc(), get_desc()->get_waytype(), cnv_kmh); last_freight = ware.get_desc(); } const sint64 price = freight_revenue * (sint64)dist * (sint64)ware.menge; // sum up new price value += price; } // Rounded value, in cents return (value+1500ll)/3000ll; } const char *vehicle_t::get_cargo_mass() const { return get_cargo_type()->get_mass(); } /** * Calculate transported cargo total weight in KG */ uint32 vehicle_t::get_cargo_weight() const { uint32 weight = 0; FOR(slist_tpl<ware_t>, const& c, fracht) { weight += c.menge * c.get_desc()->get_weight_per_unit(); } return weight; } void vehicle_t::get_cargo_info(cbuffer_t & buf) const { if (fracht.empty()) { buf.append(" "); buf.append(translator::translate("leer")); buf.append("\n"); } else { FOR(slist_tpl<ware_t>, const& ware, fracht) { const char * name = "Error in Routing"; halthandle_t halt = ware.get_ziel(); if(halt.is_bound()) { name = halt->get_name(); } buf.printf(" %u%s %s > %s\n", ware.menge, translator::translate(ware.get_mass()), translator::translate(ware.get_name()), name); } } } /** * Delete all vehicle load */ void vehicle_t::discard_cargo() { FOR( slist_tpl<ware_t>, w, fracht ) { fabrik_t::update_transit( &w, false ); } fracht.clear(); sum_weight = desc->get_weight(); } void vehicle_t::calc_image() { image_id old_image=get_image(); if (fracht.empty()) { set_image(desc->get_image_id(ribi_t::get_dir(get_direction()),NULL)); } else { set_image(desc->get_image_id(ribi_t::get_dir(get_direction()), fracht.front().get_desc())); } if(old_image!=get_image()) { set_flag(obj_t::dirty); } } image_id vehicle_t::get_loaded_image() const { return desc->get_image_id(ribi_t::dir_south, fracht.empty() ? NULL : fracht.front().get_desc()); } // true, if this vehicle did not moved for some time bool vehicle_t::is_stuck() { return cnv==NULL || cnv->is_waiting(); } void vehicle_t::rdwr(loadsave_t *file) { // this is only called from objlist => we save nothing ... assert( file->is_saving() ); (void)file; } void vehicle_t::rdwr_from_convoi(loadsave_t *file) { xml_tag_t r( file, "vehikel_t" ); sint32 fracht_count = 0; if(file->is_saving()) { fracht_count = fracht.get_count(); // we try to have one freight count to guess the right freight // when no desc is given if(fracht_count==0 && desc->get_freight_type()!=goods_manager_t::none && desc->get_capacity()>0) { fracht_count = 1; } } obj_t::rdwr(file); // since obj_t does no longer save positions if( file->is_version_atleast(101, 0) ) { koord3d pos = get_pos(); pos.rdwr(file); set_pos(pos); } sint8 hoff = file->is_saving() ? get_hoff() : 0; if(file->is_version_less(86, 6)) { sint32 l; file->rdwr_long(purchase_time); file->rdwr_long(l); dx = (sint8)l; file->rdwr_long(l); dy = (sint8)l; file->rdwr_long(l); hoff = (sint8)(l*TILE_HEIGHT_STEP/16); file->rdwr_long(speed_limit); file->rdwr_enum(direction); file->rdwr_enum(previous_direction); file->rdwr_long(fracht_count); file->rdwr_long(l); route_index = (uint16)l; purchase_time = (purchase_time >> welt->ticks_per_world_month_shift) + welt->get_settings().get_starting_year(); DBG_MESSAGE("vehicle_t::rdwr_from_convoi()","bought at %i/%i.",(purchase_time%12)+1,purchase_time/12); } else { // changed several data types to save runtime memory file->rdwr_long(purchase_time); if(file->is_version_less(99, 18)) { file->rdwr_byte(dx); file->rdwr_byte(dy); } else { file->rdwr_byte(steps); file->rdwr_byte(steps_next); if(steps_next==old_diagonal_vehicle_steps_per_tile - 1 && file->is_loading()) { // reset diagonal length (convoi will be reset anyway, if game diagonal is different) steps_next = diagonal_vehicle_steps_per_tile - 1; } } sint16 dummy16 = ((16*(sint16)hoff)/TILE_HEIGHT_STEP); file->rdwr_short(dummy16); hoff = (sint8)((TILE_HEIGHT_STEP*(sint16)dummy16)/16); file->rdwr_long(speed_limit); file->rdwr_enum(direction); file->rdwr_enum(previous_direction); file->rdwr_long(fracht_count); file->rdwr_short(route_index); // restore dxdy information dx = dxdy[ ribi_t::get_dir(direction)*2]; dy = dxdy[ ribi_t::get_dir(direction)*2+1]; } // convert steps to position if(file->is_version_less(99, 18)) { sint8 ddx=get_xoff(), ddy=get_yoff()-hoff; sint8 i=1; dx = dxdy[ ribi_t::get_dir(direction)*2]; dy = dxdy[ ribi_t::get_dir(direction)*2+1]; while( !is_about_to_hop(ddx+dx*i,ddy+dy*i ) && i<16 ) { i++; } i--; set_xoff( ddx-(16-i)*dx ); set_yoff( ddy-(16-i)*dy ); if(file->is_loading()) { if(dx && dy) { steps = min( VEHICLE_STEPS_PER_TILE - 1, VEHICLE_STEPS_PER_TILE - 1-(i*16) ); steps_next = VEHICLE_STEPS_PER_TILE - 1; } else { // will be corrected anyway, if in a convoi steps = min( diagonal_vehicle_steps_per_tile - 1, diagonal_vehicle_steps_per_tile - 1-(uint8)(((uint16)i*(uint16)(diagonal_vehicle_steps_per_tile - 1))/8) ); steps_next = diagonal_vehicle_steps_per_tile - 1; } } } // information about the target halt if(file->is_version_atleast(88, 7)) { bool target_info; if(file->is_loading()) { file->rdwr_bool(target_info); cnv = (convoi_t *)target_info; // will be checked during convoi reassignment } else { target_info = target_halt.is_bound(); file->rdwr_bool(target_info); } } else { if(file->is_loading()) { cnv = NULL; // no reservation too } } if(file->is_version_less(112, 9)) { koord3d pos_prev(koord3d::invalid); pos_prev.rdwr(file); } if(file->is_version_less(99, 5)) { koord3d dummy; dummy.rdwr(file); // current pos (is already saved as ding => ignore) } pos_next.rdwr(file); if(file->is_saving()) { const char *s = desc->get_name(); file->rdwr_str(s); } else { char s[256]; file->rdwr_str(s, lengthof(s)); desc = vehicle_builder_t::get_info(s); if(desc==NULL) { desc = vehicle_builder_t::get_info(translator::compatibility_name(s)); } if(desc==NULL) { welt->add_missing_paks( s, karte_t::MISSING_VEHICLE ); dbg->warning("vehicle_t::rdwr_from_convoi()","no vehicle pak for '%s' search for something similar", s); } } if(file->is_saving()) { if (fracht.empty() && fracht_count>0) { // create dummy freight for savegame compatibility ware_t ware( desc->get_freight_type() ); ware.menge = 0; ware.set_ziel( halthandle_t() ); ware.set_zwischenziel( halthandle_t() ); ware.set_zielpos( get_pos().get_2d() ); ware.rdwr(file); } else { FOR(slist_tpl<ware_t>, ware, fracht) { ware.rdwr(file); } } } else { for(int i=0; i<fracht_count; i++) { ware_t ware(file); if( (desc==NULL || ware.menge>0) && welt->is_within_limits(ware.get_zielpos()) && ware.get_desc() ) { // also add, of the desc is unknown to find matching replacement fracht.insert(ware); #ifdef CACHE_TRANSIT if( file->is_version_less(112, 1) ) #endif // restore in-transit information fabrik_t::update_transit( &ware, true ); } else if( ware.menge>0 ) { if( ware.get_desc() ) { dbg->error( "vehicle_t::rdwr_from_convoi()", "%i of %s to %s ignored!", ware.menge, ware.get_name(), ware.get_zielpos().get_str() ); } else { dbg->error( "vehicle_t::rdwr_from_convoi()", "%i of unknown to %s ignored!", ware.menge, ware.get_zielpos().get_str() ); } } } } // skip first last info (the convoi will know this better than we!) if(file->is_version_less(88, 7)) { bool dummy = 0; file->rdwr_bool(dummy); file->rdwr_bool(dummy); } // koordinate of the last stop if(file->is_version_atleast(99, 15)) { // This used to be 2d, now it's 3d. if(file->is_version_less(112, 8)) { if(file->is_saving()) { koord last_stop_pos_2d = last_stop_pos.get_2d(); last_stop_pos_2d.rdwr(file); } else { // loading. Assume ground level stop (could be wrong, but how would we know?) koord last_stop_pos_2d = koord::invalid; last_stop_pos_2d.rdwr(file); const grund_t* gr = welt->lookup_kartenboden(last_stop_pos_2d); if (gr) { last_stop_pos = koord3d(last_stop_pos_2d, gr->get_hoehe()); } else { // no ground?!? last_stop_pos = koord3d::invalid; } } } else { // current version, 3d last_stop_pos.rdwr(file); } } if(file->is_loading()) { leading = last = false; // dummy, will be set by convoi afterwards if(desc) { calc_image(); // full weight after loading sum_weight = get_cargo_weight() + desc->get_weight(); } // recalc total freight total_freight = 0; FOR(slist_tpl<ware_t>, const& c, fracht) { total_freight += c.menge; } } if( file->is_version_atleast(110, 0) ) { bool hd = has_driven; file->rdwr_bool( hd ); has_driven = hd; } else { if (file->is_loading()) { has_driven = false; } } } uint32 vehicle_t::calc_sale_value() const { // if already used, there is a general price reduction double value = (double)desc->get_price(); if( has_driven ) { value *= (1000 - welt->get_settings().get_used_vehicle_reduction()) / 1000.0; } // after 20 year, it has only half value return (uint32)( value * pow(0.997, (int)(welt->get_current_month() - get_purchase_time()))); } void vehicle_t::show_info() { if( cnv != NULL ) { cnv->open_info_window(); } else { dbg->warning("vehicle_t::show_info()","cnv is null, can't open convoi window!"); } } void vehicle_t::info(cbuffer_t & buf) const { if(cnv) { cnv->info(buf); } } const char *vehicle_t::is_deletable(const player_t *) { return "Fahrzeuge koennen so nicht entfernt werden"; } vehicle_t::~vehicle_t() { // remove vehicle's marker from the minimap minimap_t::get_instance()->calc_map_pixel(get_pos().get_2d()); } #ifdef MULTI_THREAD void vehicle_t::display_overlay(int xpos, int ypos) const { if( cnv && leading ) { #else void vehicle_t::display_after(int xpos, int ypos, bool is_global) const { if( is_global && cnv && leading ) { #endif PIXVAL color = 0; // not used, but stop compiler warning about uninitialized char tooltip_text[1024]; tooltip_text[0] = 0; uint8 state = env_t::show_vehicle_states; if( state==1 ) { // only show when mouse over vehicle if( welt->get_zeiger()->get_pos()==get_pos() ) { state = 2; } else { state = 0; } } // now find out what has happened switch(cnv->get_state()) { case convoi_t::WAITING_FOR_CLEARANCE_ONE_MONTH: case convoi_t::WAITING_FOR_CLEARANCE: case convoi_t::CAN_START: case convoi_t::CAN_START_ONE_MONTH: if( state>=2 ) { snprintf( tooltip_text, lengthof(tooltip_text), "%s (%s)", translator::translate("Waiting for clearance!"), cnv->get_schedule()->get_current_entry().pos.get_str() ); color = color_idx_to_rgb(COL_YELLOW); } break; case convoi_t::LOADING: if( state>=1 ) { sprintf( tooltip_text, translator::translate("Loading (%i->%i%%)!"), cnv->get_loading_level(), cnv->get_loading_limit() ); color = color_idx_to_rgb(COL_YELLOW); } break; case convoi_t::EDIT_SCHEDULE: // case convoi_t::ROUTING_1: if( state>=2 ) { tstrncpy( tooltip_text, translator::translate("Schedule changing!"), lengthof(tooltip_text) ); color = color_idx_to_rgb(COL_YELLOW); } break; case convoi_t::DRIVING: if( state>=1 ) { grund_t const* const gr = welt->lookup(cnv->get_route()->back()); if( gr && gr->get_depot() ) { tstrncpy( tooltip_text, translator::translate("go home"), lengthof(tooltip_text) ); color = color_idx_to_rgb(COL_GREEN); } else if( cnv->get_no_load() ) { tstrncpy( tooltip_text, translator::translate("no load"), lengthof(tooltip_text) ); color = color_idx_to_rgb(COL_GREEN); } } break; case convoi_t::LEAVING_DEPOT: if( state>=2 ) { tstrncpy( tooltip_text, translator::translate("Leaving depot!"), lengthof(tooltip_text) ); color = color_idx_to_rgb(COL_GREEN); } break; case convoi_t::WAITING_FOR_CLEARANCE_TWO_MONTHS: case convoi_t::CAN_START_TWO_MONTHS: snprintf( tooltip_text, lengthof(tooltip_text), "%s (%s)", translator::translate("clf_chk_stucked"), cnv->get_schedule()->get_current_entry().pos.get_str() ); color = color_idx_to_rgb(COL_ORANGE); break; case convoi_t::NO_ROUTE: tstrncpy( tooltip_text, translator::translate("clf_chk_noroute"), lengthof(tooltip_text) ); color = color_idx_to_rgb(COL_RED); break; } // something to show? if( tooltip_text[0] ) { const int width = proportional_string_width(tooltip_text)+7; const int raster_width = get_current_tile_raster_width(); get_screen_offset( xpos, ypos, raster_width ); xpos += tile_raster_scale_x(get_xoff(), raster_width); ypos += tile_raster_scale_y(get_yoff(), raster_width)+14; if(ypos>LINESPACE+32 && ypos+LINESPACE<display_get_clip_wh().yy) { display_ddd_proportional_clip( xpos, ypos, width, 0, color, color_idx_to_rgb(COL_BLACK), tooltip_text, true ); } } } } road_vehicle_t::road_vehicle_t(koord3d pos, const vehicle_desc_t* desc, player_t* player, convoi_t* cn) : vehicle_t(pos, desc, player) { cnv = cn; } road_vehicle_t::road_vehicle_t(loadsave_t *file, bool is_first, bool is_last) : vehicle_t() { rdwr_from_convoi(file); if( file->is_loading() ) { static const vehicle_desc_t *last_desc = NULL; if(is_first) { last_desc = NULL; } // try to find a matching vehicle if(desc==NULL) { const goods_desc_t* w = (!fracht.empty() ? fracht.front().get_desc() : goods_manager_t::passengers); dbg->warning("road_vehicle_t::road_vehicle_t()","try to find a fitting vehicle for %s.", w->get_name() ); desc = vehicle_builder_t::get_best_matching(road_wt, 0, (fracht.empty() ? 0 : 50), is_first?50:0, speed_to_kmh(speed_limit), w, true, last_desc, is_last ); if(desc) { DBG_MESSAGE("road_vehicle_t::road_vehicle_t()","replaced by %s",desc->get_name()); // still wrong load ... calc_image(); } if(!fracht.empty() && fracht.front().menge == 0) { // this was only there to find a matching vehicle fracht.remove_first(); } } if( desc ) { last_desc = desc; } calc_disp_lane(); } } void road_vehicle_t::rotate90() { vehicle_t::rotate90(); calc_disp_lane(); } void road_vehicle_t::calc_disp_lane() { // driving in the back or the front ribi_t::ribi test_dir = welt->get_settings().is_drive_left() ? ribi_t::northeast : ribi_t::southwest; disp_lane = get_direction() & test_dir ? 1 : 3; } // need to reset halt reservation (if there was one) bool road_vehicle_t::calc_route(koord3d start, koord3d ziel, sint32 max_speed, route_t* route) { assert(cnv); // free target reservation if(leading && previous_direction!=ribi_t::none && cnv && target_halt.is_bound() ) { // now reserve our choice (beware: might be longer than one tile!) for( uint32 length=0; length<cnv->get_tile_length() && length+1<cnv->get_route()->get_count(); length++ ) { target_halt->unreserve_position( welt->lookup( cnv->get_route()->at( cnv->get_route()->get_count()-length-1) ), cnv->self ); } } target_halt = halthandle_t(); // no block reserved route_t::route_result_t r = route->calc_route(welt, start, ziel, this, max_speed, cnv->get_tile_length() ); if( r == route_t::valid_route_halt_too_short ) { cbuffer_t buf; buf.printf( translator::translate("Vehicle %s cannot choose because stop too short!"), cnv->get_name()); welt->get_message()->add_message( (const char *)buf, ziel.get_2d(), message_t::traffic_jams, PLAYER_FLAG | cnv->get_owner()->get_player_nr(), cnv->front()->get_base_image() ); } return r; } bool road_vehicle_t::check_next_tile(const grund_t *bd) const { strasse_t *str=(strasse_t *)bd->get_weg(road_wt); if(str==NULL || str->get_max_speed()==0) { return false; } bool electric = cnv!=NULL ? cnv->needs_electrification() : desc->get_engine_type()==vehicle_desc_t::electric; if(electric && !str->is_electrified()) { return false; } // check for signs if(str->has_sign()) { const roadsign_t* rs = bd->find<roadsign_t>(); if(rs!=NULL) { if( rs->get_desc()->get_min_speed()>0 && rs->get_desc()->get_min_speed()>kmh_to_speed(get_desc()->get_topspeed()) ) { return false; } if( rs->get_desc()->is_private_way() && (rs->get_player_mask() & (1<<get_player_nr()) ) == 0 ) { // private road return false; } // do not search further for a free stop beyond here if(target_halt.is_bound() && cnv->is_waiting() && rs->get_desc()->get_flags()&roadsign_desc_t::END_OF_CHOOSE_AREA) { return false; } } } return true; } // how expensive to go here (for way search) int road_vehicle_t::get_cost(const grund_t *gr, const weg_t *w, const sint32 max_speed, ribi_t::ribi from) const { // first favor faster ways if(!w) { return 0xFFFF; } // max_speed? sint32 max_tile_speed = w->get_max_speed(); // add cost for going (with maximum speed, cost is 1) int costs = (max_speed<=max_tile_speed) ? 1 : 4-(3*max_tile_speed)/max_speed; // assume all traffic is not good ... (otherwise even smoke counts ... ) costs += (w->get_statistics(WAY_STAT_CONVOIS) > ( 2 << (welt->get_settings().get_bits_per_month()-16) ) ); // effect of slope if( gr->get_weg_hang()!=0 ) { // check if the slope is upwards, relative to the previous tile // 15 hardcoded, see get_cost_upslope() costs += 15 * get_sloping_upwards( gr->get_weg_hang(), from ); } return costs; } // this routine is called by find_route, to determined if we reached a destination bool road_vehicle_t::is_target(const grund_t *gr, const grund_t *prev_gr) const { // just check, if we reached a free stop position of this halt if(gr->is_halt() && gr->get_halt()==target_halt && target_halt->is_reservable(gr,cnv->self)) { // now we must check the predecessor => try to advance as much as possible if(prev_gr!=NULL) { const koord dir=gr->get_pos().get_2d()-prev_gr->get_pos().get_2d(); ribi_t::ribi ribi = ribi_type(dir); if( gr->get_weg(get_waytype())->get_ribi_maske() & ribi ) { // one way sign wrong direction return false; } grund_t *to; if( !gr->get_neighbour(to,road_wt,ribi) || !(to->get_halt()==target_halt) || (gr->get_weg(get_waytype())->get_ribi_maske() & ribi_type(dir))!=0 || !target_halt->is_reservable(to,cnv->self) ) { // end of stop: Is it long enough? uint16 tiles = cnv->get_tile_length(); while( tiles>1 ) { if( !gr->get_neighbour(to,get_waytype(),ribi_t::backward(ribi)) || !(to->get_halt()==target_halt) || !target_halt->is_reservable(to,cnv->self) ) { return false; } gr = to; tiles --; } return true; } // can advance more return false; } //DBG_MESSAGE("is_target()","success at %i,%i",gr->get_pos().x,gr->get_pos().y); // return true; } return false; } // to make smaller steps than the tile granularity, we have to use this trick void road_vehicle_t::get_screen_offset( int &xoff, int &yoff, const sint16 raster_width ) const { vehicle_base_t::get_screen_offset( xoff, yoff, raster_width ); if( welt->get_settings().is_drive_left() ) { const int drive_left_dir = ribi_t::get_dir(get_direction()); xoff += tile_raster_scale_x( driveleft_base_offsets[drive_left_dir][0], raster_width ); yoff += tile_raster_scale_y( driveleft_base_offsets[drive_left_dir][1], raster_width ); } // eventually shift position to take care of overtaking if(cnv) { if( cnv->is_overtaking() ) { xoff += tile_raster_scale_x(overtaking_base_offsets[ribi_t::get_dir(get_direction())][0], raster_width); yoff += tile_raster_scale_x(overtaking_base_offsets[ribi_t::get_dir(get_direction())][1], raster_width); } else if( cnv->is_overtaken() ) { xoff -= tile_raster_scale_x(overtaking_base_offsets[ribi_t::get_dir(get_direction())][0], raster_width)/5; yoff -= tile_raster_scale_x(overtaking_base_offsets[ribi_t::get_dir(get_direction())][1], raster_width)/5; } } } // chooses a route at a choose sign; returns true on success bool road_vehicle_t::choose_route(sint32 &restart_speed, ribi_t::ribi start_direction, uint16 index) { if( cnv->get_schedule_target()!=koord3d::invalid ) { // destination is a waypoint! return true; } // are we heading to a target? route_t *rt = cnv->access_route(); target_halt = haltestelle_t::get_halt( rt->back(), get_owner() ); if( target_halt.is_bound() ) { // since convois can long than one tile, check is more difficult bool can_go_there = true; bool original_route = (rt->back() == cnv->get_schedule()->get_current_entry().pos); for( uint32 length=0; can_go_there && length<cnv->get_tile_length() && length+1<rt->get_count(); length++ ) { if( grund_t *gr = welt->lookup( rt->at( rt->get_count()-length-1) ) ) { if (gr->get_halt().is_bound()) { can_go_there &= target_halt->is_reservable( gr, cnv->self ); } else { // if this is the original stop, it is too short! can_go_there |= original_route; } } } if( can_go_there ) { // then reserve it ... for( uint32 length=0; length<cnv->get_tile_length() && length+1<rt->get_count(); length++ ) { target_halt->reserve_position( welt->lookup( rt->at( rt->get_count()-length-1) ), cnv->self ); } } else { // cannot go there => need slot search // if we fail, we will wait in a step, much more simulation friendly if(!cnv->is_waiting()) { restart_speed = -1; target_halt = halthandle_t(); return false; } // check if there is a free position // this is much faster than waysearch if( !target_halt->find_free_position(road_wt,cnv->self,obj_t::road_vehicle )) { restart_speed = 0; target_halt = halthandle_t(); return false; } // now it make sense to search a route route_t target_rt; koord3d next3d = rt->at(index); if( !target_rt.find_route( welt, next3d, this, speed_to_kmh(cnv->get_min_top_speed()), start_direction, welt->get_settings().get_max_choose_route_steps() ) ) { // nothing empty or not route with less than 33 tiles target_halt = halthandle_t(); restart_speed = 0; return false; } // now reserve our choice (beware: might be longer than one tile!) for( uint32 length=0; length<cnv->get_tile_length() && length+1<target_rt.get_count(); length++ ) { target_halt->reserve_position( welt->lookup( target_rt.at( target_rt.get_count()-length-1) ), cnv->self ); } rt->remove_koord_from( index ); rt->append( &target_rt ); } } return true; } bool road_vehicle_t::can_enter_tile(const grund_t *gr, sint32 &restart_speed, uint8 second_check_count) { // check for traffic lights (only relevant for the first car in a convoi) if( leading ) { // no further check, when already entered a crossing (to allow leaving it) if( !second_check_count ) { const grund_t *gr_current = welt->lookup(get_pos()); if( gr_current && gr_current->ist_uebergang() ) { return true; } } assert(gr); const strasse_t *str = (strasse_t *)gr->get_weg(road_wt); if( !str || gr->get_top() > 250 ) { // too many cars here or no street return false; } // first: check roadsigns const roadsign_t *rs = NULL; if( str->has_sign() ) { rs = gr->find<roadsign_t>(); route_t const& r = *cnv->get_route(); if( rs && (route_index + 1u < r.get_count()) ) { // since at the corner, our direction may be diagonal, we make it straight uint8 direction90 = ribi_type(get_pos(), pos_next); if( rs->get_desc()->is_traffic_light() && (rs->get_dir()&direction90) == 0 ) { // wait here restart_speed = 16; return false; } // check, if we reached a choose point else { // route position after road sign const koord pos_next_next = r.at(route_index + 1u).get_2d(); // since at the corner, our direction may be diagonal, we make it straight direction90 = ribi_type( pos_next, pos_next_next ); if( rs->is_free_route(direction90) && !target_halt.is_bound() ) { if( second_check_count ) { return false; } if( !choose_route( restart_speed, direction90, route_index ) ) { return false; } } } } } vehicle_base_t *obj = NULL; uint32 test_index = route_index + 1u; // way should be clear for overtaking: we checked previously if( !cnv->is_overtaking() ) { // calculate new direction route_t const& r = *cnv->get_route(); koord3d next = route_index < r.get_count() - 1u ? r.at(route_index + 1u) : pos_next; ribi_t::ribi curr_direction = get_direction(); ribi_t::ribi curr_90direction = calc_direction(get_pos(), pos_next); ribi_t::ribi next_direction = calc_direction(get_pos(), next); ribi_t::ribi next_90direction = calc_direction(pos_next, next); obj = no_cars_blocking( gr, cnv, curr_direction, next_direction, next_90direction ); // do not block intersections const bool drives_on_left = welt->get_settings().is_drive_left(); bool int_block = ribi_t::is_threeway(str->get_ribi_unmasked()) && (((drives_on_left ? ribi_t::rotate90l(curr_90direction) : ribi_t::rotate90(curr_90direction)) & str->get_ribi_unmasked()) || curr_90direction != next_90direction || (rs && rs->get_desc()->is_traffic_light())); // check exit from crossings and intersections, allow to proceed after 4 consecutive while( !obj && (str->is_crossing() || int_block) && test_index < r.get_count() && test_index < route_index + 4u ) { if( str->is_crossing() ) { crossing_t* cr = gr->find<crossing_t>(2); if( !cr->request_crossing(this) ) { restart_speed = 0; return false; } } // test next position gr = welt->lookup(r.at(test_index)); if( !gr ) { // way (weg) not existent (likely destroyed) if( !second_check_count ) { cnv->suche_neue_route(); } return false; } str = (strasse_t *)gr->get_weg(road_wt); if( !str || gr->get_top() > 250 ) { // too many cars here or no street if( !second_check_count && !str) { cnv->suche_neue_route(); } return false; } // check cars curr_direction = next_direction; curr_90direction = next_90direction; if( test_index + 1u < r.get_count() ) { next = r.at(test_index + 1u); next_direction = calc_direction(r.at(test_index - 1u), next); next_90direction = calc_direction(r.at(test_index), next); obj = no_cars_blocking( gr, cnv, curr_direction, next_direction, next_90direction ); } else { next = r.at(test_index); next_90direction = calc_direction(r.at(test_index - 1u), next); if( curr_direction == next_90direction || !gr->is_halt() ) { // check cars but allow to enter intersection if we are turning even when a car is blocking the halt on the last tile of our route // preserves old bus terminal behaviour obj = no_cars_blocking( gr, cnv, curr_direction, next_90direction, ribi_t::none ); } } // check roadsigns if( str->has_sign() ) { rs = gr->find<roadsign_t>(); if( rs ) { // since at the corner, our direction may be diagonal, we make it straight if( rs->get_desc()->is_traffic_light() && (rs->get_dir() & curr_90direction)==0 ) { // wait here restart_speed = 16; return false; } // check, if we reached a choose point else if( rs->is_free_route(curr_90direction) && !target_halt.is_bound() ) { if( second_check_count ) { return false; } if( !choose_route( restart_speed, curr_90direction, test_index ) ) { return false; } } } } else { rs = NULL; } // check for blocking intersection int_block = ribi_t::is_threeway(str->get_ribi_unmasked()) && (((drives_on_left ? ribi_t::rotate90l(curr_90direction) : ribi_t::rotate90(curr_90direction)) & str->get_ribi_unmasked()) || curr_90direction != next_90direction || (rs && rs->get_desc()->is_traffic_light())); test_index++; } if( obj && test_index > route_index + 1u && !str->is_crossing() && !int_block ) { // found a car blocking us after checking at least 1 intersection or crossing // and the car is in a place we could stop. So if it can move, assume it will, so we will too. // but check only upto 8 cars ahead to prevent infinite recursion on roundabouts. if( second_check_count >= 8 ) { return false; } if( road_vehicle_t const* const car = obj_cast<road_vehicle_t>(obj) ) { const convoi_t* const ocnv = car->get_convoi(); sint32 dummy; if( ocnv->front()->get_route_index() < ocnv->get_route()->get_count() && ocnv->front()->can_enter_tile( dummy, second_check_count + 1 ) ) { return true; } } } } // stuck message ... if( obj && !second_check_count ) { if( obj->is_stuck() ) { // end of traffic jam, but no stuck message, because previous vehicle is stuck too restart_speed = 0; cnv->set_tiles_overtaking(0); cnv->reset_waiting(); } else { if( test_index == route_index + 1u ) { // no intersections or crossings, we might be able to overtake this one ... overtaker_t *over = obj->get_overtaker(); if( over && !over->is_overtaken() ) { if( over->is_overtaking() ) { // otherwise we would stop every time being overtaken return true; } // not overtaking/being overtake: we need to make a more thought test! if( road_vehicle_t const* const car = obj_cast<road_vehicle_t>(obj) ) { convoi_t* const ocnv = car->get_convoi(); if( cnv->can_overtake( ocnv, (ocnv->get_state()==convoi_t::LOADING ? 0 : over->get_max_power_speed()), ocnv->get_length_in_steps()+ocnv->get_vehikel(0)->get_steps()) ) { return true; } } else if( private_car_t* const caut = obj_cast<private_car_t>(obj) ) { if( cnv->can_overtake(caut, caut->get_desc()->get_topspeed(), VEHICLE_STEPS_PER_TILE) ) { return true; } } } } // we have to wait ... restart_speed = (cnv->get_akt_speed()*3)/4; cnv->set_tiles_overtaking(0); } } return obj==NULL; } return true; } overtaker_t* road_vehicle_t::get_overtaker() { return cnv; } void road_vehicle_t::enter_tile(grund_t* gr) { vehicle_t::enter_tile(gr); calc_disp_lane(); const int cargo = get_total_cargo(); weg_t *str = gr->get_weg(road_wt); str->book(cargo, WAY_STAT_GOODS); if (leading) { str->book(1, WAY_STAT_CONVOIS); cnv->update_tiles_overtaking(); } } schedule_t * road_vehicle_t::generate_new_schedule() const { return new truck_schedule_t(); } void road_vehicle_t::set_convoi(convoi_t *c) { DBG_MESSAGE("road_vehicle_t::set_convoi()","%p",c); if(c!=NULL) { bool target=(bool)cnv; // only during loadtype: cnv==1 indicates, that the convoi did reserve a stop vehicle_t::set_convoi(c); if(target && leading && c->get_route()->empty()) { // reinitialize the target halt const route_t *rt = cnv->get_route(); target_halt = haltestelle_t::get_halt( rt->back(), get_owner() ); if( target_halt.is_bound() ) { for( uint32 i=0; i<c->get_tile_length() && i+1<rt->get_count(); i++ ) { target_halt->reserve_position( welt->lookup( rt->at(rt->get_count()-i-1) ), cnv->self ); } } } } else { if( cnv && leading && target_halt.is_bound() ) { // now reserve our choice (beware: might be longer than one tile!) for( uint32 length=0; length<cnv->get_tile_length() && length+1<cnv->get_route()->get_count(); length++ ) { target_halt->unreserve_position( welt->lookup( cnv->get_route()->at( cnv->get_route()->get_count()-length-1) ), cnv->self ); } target_halt = halthandle_t(); } cnv = NULL; } } /* from now on rail vehicles (and other vehicles using blocks) */ rail_vehicle_t::rail_vehicle_t(loadsave_t *file, bool is_first, bool is_last) : vehicle_t() { vehicle_t::rdwr_from_convoi(file); if( file->is_loading() ) { static const vehicle_desc_t *last_desc = NULL; if(is_first) { last_desc = NULL; } // try to find a matching vehicle if(desc==NULL) { int power = (is_first || fracht.empty() || fracht.front() == goods_manager_t::none) ? 500 : 0; const goods_desc_t* w = fracht.empty() ? goods_manager_t::none : fracht.front().get_desc(); dbg->warning("rail_vehicle_t::rail_vehicle_t()","try to find a fitting vehicle for %s.", power>0 ? "engine": w->get_name() ); if(last_desc!=NULL && last_desc->can_follow(last_desc) && last_desc->get_freight_type()==w && (!is_last || last_desc->get_trailer(0)==NULL)) { // same as previously ... desc = last_desc; } else { // we have to search desc = vehicle_builder_t::get_best_matching(get_waytype(), 0, w!=goods_manager_t::none?5000:0, power, speed_to_kmh(speed_limit), w, false, last_desc, is_last ); } if(desc) { DBG_MESSAGE("rail_vehicle_t::rail_vehicle_t()","replaced by %s",desc->get_name()); calc_image(); } else { dbg->error("rail_vehicle_t::rail_vehicle_t()","no matching desc found for %s!",w->get_name()); } if (!fracht.empty() && fracht.front().menge == 0) { // this was only there to find a matching vehicle fracht.remove_first(); } } // update last desc if( desc ) { last_desc = desc; } } } rail_vehicle_t::rail_vehicle_t(koord3d pos, const vehicle_desc_t* desc, player_t* player, convoi_t* cn) : vehicle_t(pos, desc, player) { cnv = cn; } rail_vehicle_t::~rail_vehicle_t() { if (cnv && leading) { route_t const& r = *cnv->get_route(); if (!r.empty() && route_index < r.get_count()) { // free all reserved blocks uint16 dummy; block_reserver(&r, cnv->back()->get_route_index(), dummy, dummy, target_halt.is_bound() ? 100000 : 1, false, false); } } grund_t *gr = welt->lookup(get_pos()); if(gr) { schiene_t * sch = (schiene_t *)gr->get_weg(get_waytype()); if(sch) { sch->unreserve(this); } } } void rail_vehicle_t::set_convoi(convoi_t *c) { if(c!=cnv) { DBG_MESSAGE("rail_vehicle_t::set_convoi()","new=%p old=%p",c,cnv); if(leading) { if(cnv!=NULL && cnv!=(convoi_t *)1) { // free route from old convoi route_t const& r = *cnv->get_route(); if( !r.empty() && route_index + 1U < r.get_count() - 1 ) { uint16 dummy; block_reserver(&r, cnv->back()->get_route_index(), dummy, dummy, 100000, false, false); target_halt = halthandle_t(); } } else if( c->get_next_reservation_index()==0 ) { assert(c!=NULL); // eventually search new route route_t const& r = *c->get_route(); if( (r.get_count()<=route_index || r.empty() || get_pos()==r.back()) && c->get_state()!=convoi_t::INITIAL && c->get_state()!=convoi_t::LOADING && c->get_state()!=convoi_t::SELF_DESTRUCT ) { check_for_finish = true; dbg->warning("rail_vehicle_t::set_convoi()", "convoi %i had a too high route index! (%i of max %i)", c->self.get_id(), route_index, r.get_count() - 1); } // set default next stop index c->set_next_stop_index( max(route_index,1)-1 ); // need to reserve new route? if( !check_for_finish && c->get_state()!=convoi_t::SELF_DESTRUCT && (c->get_state()==convoi_t::DRIVING || c->get_state()>=convoi_t::LEAVING_DEPOT) ) { sint32 num_index = cnv==(convoi_t *)1 ? 1001 : 0; // only during loadtype: cnv==1 indicates, that the convoi did reserve a stop uint16 next_signal, next_crossing; cnv = c; if( block_reserver(&r, max(route_index,1)-1, next_signal, next_crossing, num_index, true, false) ) { c->set_next_stop_index( next_signal>next_crossing ? next_crossing : next_signal ); } } } } vehicle_t::set_convoi(c); } } // need to reset halt reservation (if there was one) bool rail_vehicle_t::calc_route(koord3d start, koord3d ziel, sint32 max_speed, route_t* route) { if(leading && route_index<cnv->get_route()->get_count()) { // free all reserved blocks uint16 dummy; block_reserver(cnv->get_route(), cnv->back()->get_route_index(), dummy, dummy, target_halt.is_bound() ? 100000 : 1, false, true); } cnv->set_next_reservation_index( 0 ); // nothing to reserve target_halt = halthandle_t(); // no block reserved // use length 8888 tiles to advance to the end of all stations return route->calc_route(welt, start, ziel, this, max_speed, 8888 /*cnv->get_tile_length()*/ ); } bool rail_vehicle_t::check_next_tile(const grund_t *bd) const { schiene_t const* const sch = obj_cast<schiene_t>(bd->get_weg(get_waytype())); if( !sch ) { return false; } // diesel and steam engines can use electrified track as well. // also allow driving on foreign tracks ... const bool needs_no_electric = !(cnv!=NULL ? cnv->needs_electrification() : desc->get_engine_type()==vehicle_desc_t::electric); if( (!needs_no_electric && !sch->is_electrified()) || sch->get_max_speed() == 0 ) { return false; } if (depot_t *depot = bd->get_depot()) { if (depot->get_waytype() != desc->get_waytype() || depot->get_owner() != get_owner()) { return false; } } // now check for special signs if(sch->has_sign()) { const roadsign_t* rs = bd->find<roadsign_t>(); if( rs->get_desc()->get_wtyp()==get_waytype() ) { if( cnv != NULL && rs->get_desc()->get_min_speed() > 0 && rs->get_desc()->get_min_speed() > cnv->get_min_top_speed() ) { // below speed limit return false; } if( rs->get_desc()->is_private_way() && (rs->get_player_mask() & (1<<get_player_nr()) ) == 0 ) { // private road return false; } } } if( target_halt.is_bound() && cnv->is_waiting() ) { // we are searching a stop here: // ok, we can go where we already are ... if(bd->get_pos()==get_pos()) { return true; } // we cannot pass an end of choose area if(sch->has_sign()) { const roadsign_t* rs = bd->find<roadsign_t>(); if( rs->get_desc()->get_wtyp()==get_waytype() ) { if( rs->get_desc()->get_flags() & roadsign_desc_t::END_OF_CHOOSE_AREA ) { return false; } } } // but we can only use empty blocks ... // now check, if we could enter here return sch->can_reserve(cnv->self); } return true; } // how expensive to go here (for way search) int rail_vehicle_t::get_cost(const grund_t *gr, const weg_t *w, const sint32 max_speed, ribi_t::ribi from) const { // first favor faster ways if( w==NULL ) { // only occurs when deletion during way search return 999; } // add cost for going (with maximum speed, cost is 1) const sint32 max_tile_speed = w->get_max_speed(); int costs = (max_speed<=max_tile_speed) ? 1 : 4-(3*max_tile_speed)/max_speed; // effect of slope if( gr->get_weg_hang()!=0 ) { // check if the slope is upwards, relative to the previous tile // 25 hardcoded, see get_cost_upslope() costs += 25 * get_sloping_upwards( gr->get_weg_hang(), from ); } return costs; } // this routine is called by find_route, to determined if we reached a destination bool rail_vehicle_t::is_target(const grund_t *gr,const grund_t *prev_gr) const { const schiene_t * sch1 = (const schiene_t *) gr->get_weg(get_waytype()); // first check blocks, if we can go there if( sch1->can_reserve(cnv->self) ) { // just check, if we reached a free stop position of this halt if( gr->is_halt() && gr->get_halt()==target_halt ) { // now we must check the predecessor ... if( prev_gr!=NULL ) { const koord dir=gr->get_pos().get_2d()-prev_gr->get_pos().get_2d(); const ribi_t::ribi ribi = ribi_type(dir); if( gr->get_weg(get_waytype())->get_ribi_maske() & ribi ) { // signal/one way sign wrong direction return false; } grund_t *to; if( !gr->get_neighbour(to,get_waytype(),ribi) || !(to->get_halt()==target_halt) || (to->get_weg(get_waytype())->get_ribi_maske() & ribi_type(dir))!=0 ) { // end of stop: Is it long enough? // end of stop could be also signal! uint16 tiles = cnv->get_tile_length(); while( tiles>1 ) { if( gr->get_weg(get_waytype())->get_ribi_maske() & ribi || !gr->get_neighbour(to,get_waytype(),ribi_t::backward(ribi)) || !(to->get_halt()==target_halt) ) { return false; } gr = to; tiles --; } return true; } } } } return false; } bool rail_vehicle_t::is_longblock_signal_clear(signal_t *sig, uint16 next_block, sint32 &restart_speed) { // longblock signal: first check, whether there is a signal coming up on the route => just like normal signal uint16 next_signal, next_crossing; if( !block_reserver( cnv->get_route(), next_block+1, next_signal, next_crossing, 0, true, false ) ) { // not even the "Normal" signal route part is free => no bother checking further on sig->set_state( roadsign_t::rot ); restart_speed = 0; return false; } if( next_signal != INVALID_INDEX ) { // success, and there is a signal before end of route => finished sig->set_state( roadsign_t::gruen ); cnv->set_next_stop_index( min( next_crossing, next_signal ) ); return true; } // no signal before end_of_route => need to do route search in a step if( !cnv->is_waiting() ) { restart_speed = -1; return false; } // now we can use the route search array // (route until end is already reserved at this point!) uint8 schedule_index = cnv->get_schedule()->get_current_stop()+1; route_t target_rt; koord3d cur_pos = cnv->get_route()->back(); uint16 dummy, next_next_signal; if(schedule_index >= cnv->get_schedule()->get_count()) { schedule_index = 0; } while( schedule_index != cnv->get_schedule()->get_current_stop() ) { // now search // search for route bool success = target_rt.calc_route( welt, cur_pos, cnv->get_schedule()->entries[schedule_index].pos, this, speed_to_kmh(cnv->get_min_top_speed()), 8888 /*cnv->get_tile_length()*/ ); if( target_rt.is_contained(get_pos()) ) { // do not reserve route going through my current stop& break; } if( success ) { success = block_reserver( &target_rt, 1, next_next_signal, dummy, 0, true, false ); block_reserver( &target_rt, 1, dummy, dummy, 0, false, false ); } if( success ) { // ok, would be free if( next_next_signal<target_rt.get_count() ) { // and here is a signal => finished // (however, if it is this signal, we need to renew reservation ... if( target_rt.at(next_next_signal) == cnv->get_route()->at( next_block ) ) { block_reserver( cnv->get_route(), next_block+1, next_signal, next_crossing, 0, true, false ); } sig->set_state( roadsign_t::gruen ); cnv->set_next_stop_index( min( min( next_crossing, next_signal ), cnv->get_route()->get_count() ) ); return true; } } if( !success ) { block_reserver( cnv->get_route(), next_block+1, next_next_signal, dummy, 0, false, false ); sig->set_state( roadsign_t::rot ); restart_speed = 0; return false; } // prepare for next leg of schedule cur_pos = target_rt.back(); schedule_index ++; if(schedule_index >= cnv->get_schedule()->get_count()) { schedule_index = 0; } } if( cnv->get_next_stop_index()-1 <= route_index ) { cnv->set_next_stop_index( cnv->get_route()->get_count()-1 ); } return true; } bool rail_vehicle_t::is_choose_signal_clear(signal_t *sig, const uint16 start_block, sint32 &restart_speed) { bool choose_ok = false; target_halt = halthandle_t(); uint16 next_signal, next_crossing; grund_t const* const target = welt->lookup(cnv->get_route()->back()); if( cnv->get_schedule_target()!=koord3d::invalid ) { // destination is a waypoint! goto skip_choose; } if( target==NULL ) { cnv->suche_neue_route(); return false; } // first check, if we are not heading to a waypoint if( !target->get_halt().is_bound() ) { goto skip_choose; } // now we might choose something at least choose_ok = true; // check, if there is another choose signal or end_of_choose on the route for( uint32 idx=start_block+1; choose_ok && idx<cnv->get_route()->get_count(); idx++ ) { grund_t *gr = welt->lookup(cnv->get_route()->at(idx)); if( gr==0 ) { choose_ok = false; break; } if( gr->get_halt()==target->get_halt() ) { target_halt = gr->get_halt(); break; } weg_t *way = gr->get_weg(get_waytype()); if( way==0 ) { choose_ok = false; break; } if( way->has_sign() ) { roadsign_t *rs = gr->find<roadsign_t>(1); if( rs && rs->get_desc()->get_wtyp()==get_waytype() ) { if( rs->get_desc()->get_flags() & roadsign_desc_t::END_OF_CHOOSE_AREA ) { // end of choose on route => not choosing here choose_ok = false; } } } if( way->has_signal() ) { signal_t *sig = gr->find<signal_t>(1); if( sig && sig->get_desc()->is_choose_sign() ) { // second choose signal on route => not choosing here choose_ok = false; } } } skip_choose: if( !choose_ok ) { // just act as normal signal if( block_reserver( cnv->get_route(), start_block+1, next_signal, next_crossing, 0, true, false ) ) { sig->set_state( roadsign_t::gruen ); cnv->set_next_stop_index( min( next_crossing, next_signal ) ); return true; } // not free => wait here if directly in front sig->set_state( roadsign_t::rot ); restart_speed = 0; return false; } target_halt = target->get_halt(); if( !block_reserver( cnv->get_route(), start_block+1, next_signal, next_crossing, 100000, true, false ) ) { // no free route to target! // note: any old reservations should be invalid after the block reserver call. // => We can now start freshly all over if(!cnv->is_waiting()) { restart_speed = -1; target_halt = halthandle_t(); return false; } // now we are in a step and can use the route search array // now it we are in a step and can use the route search route_t target_rt; const int richtung = ribi_type(get_pos(), pos_next); // to avoid confusion at diagonals if( !target_rt.find_route( welt, cnv->get_route()->at(start_block), this, speed_to_kmh(cnv->get_min_top_speed()), richtung, welt->get_settings().get_max_choose_route_steps() ) ) { // nothing empty or not route with less than get_max_choose_route_steps() tiles target_halt = halthandle_t(); sig->set_state( roadsign_t::rot ); restart_speed = 0; return false; } else { // try to alloc the whole route cnv->access_route()->remove_koord_from(start_block); cnv->access_route()->append( &target_rt ); if( !block_reserver( cnv->get_route(), start_block+1, next_signal, next_crossing, 100000, true, false ) ) { dbg->error( "rail_vehicle_t::is_choose_signal_clear()", "could not reserved route after find_route!" ); target_halt = halthandle_t(); sig->set_state( roadsign_t::rot ); restart_speed = 0; return false; } } // reserved route to target } sig->set_state( roadsign_t::gruen ); cnv->set_next_stop_index( min( next_crossing, next_signal ) ); return true; } bool rail_vehicle_t::is_pre_signal_clear(signal_t *sig, uint16 next_block, sint32 &restart_speed) { // parse to next signal; if needed recurse, since we allow cascading uint16 next_signal, next_crossing; if( block_reserver( cnv->get_route(), next_block+1, next_signal, next_crossing, 0, true, false ) ) { if( next_signal == INVALID_INDEX || cnv->get_route()->at(next_signal) == cnv->get_route()->back() || is_signal_clear( next_signal, restart_speed ) ) { // ok, end of route => we can go sig->set_state( roadsign_t::gruen ); cnv->set_next_stop_index( min( next_signal, next_crossing ) ); return true; } // when we reached here, the way is apparently not free => release reservation and set state to next free sig->set_state( roadsign_t::naechste_rot ); block_reserver( cnv->get_route(), next_block+1, next_signal, next_crossing, 0, false, false ); restart_speed = 0; return false; } // if we end up here, there was not even the next block free sig->set_state( roadsign_t::rot ); restart_speed = 0; return false; } bool rail_vehicle_t::is_priority_signal_clear(signal_t *sig, uint16 next_block, sint32 &restart_speed) { // parse to next signal; if needed recurse, since we allow cascading uint16 next_signal, next_crossing; if( block_reserver( cnv->get_route(), next_block+1, next_signal, next_crossing, 0, true, false ) ) { if( next_signal == INVALID_INDEX || cnv->get_route()->at(next_signal) == cnv->get_route()->back() || is_signal_clear( next_signal, restart_speed ) ) { // ok, end of route => we can go sig->set_state( roadsign_t::gruen ); cnv->set_next_stop_index( min( next_signal, next_crossing ) ); return true; } // when we reached here, the way after the last signal is not free though the way before is => we can still go if( cnv->get_next_stop_index()<=next_signal+1 ) { // only show third aspect on last signal of cascade sig->set_state( roadsign_t::naechste_rot ); } else { sig->set_state( roadsign_t::gruen ); } cnv->set_next_stop_index( min( next_signal, next_crossing ) ); return false; } // if we end up here, there was not even the next block free sig->set_state( roadsign_t::rot ); restart_speed = 0; return false; } bool rail_vehicle_t::is_signal_clear(uint16 next_block, sint32 &restart_speed) { // called, when there is a signal; will call other signal routines if needed grund_t *gr_next_block = welt->lookup(cnv->get_route()->at(next_block)); signal_t *sig = gr_next_block->find<signal_t>(); if( sig==NULL ) { dbg->error( "rail_vehicle_t::is_signal_clear()", "called at %s without a signal!", cnv->get_route()->at(next_block).get_str() ); return true; } // action depend on the next signal const roadsign_desc_t *sig_desc=sig->get_desc(); // simple signal: fail, if next block is not free if( sig_desc->is_simple_signal() ) { uint16 next_signal, next_crossing; if( block_reserver( cnv->get_route(), next_block+1, next_signal, next_crossing, 0, true, false ) ) { sig->set_state( roadsign_t::gruen ); cnv->set_next_stop_index( min( next_crossing, next_signal ) ); return true; } // not free => wait here if directly in front sig->set_state( roadsign_t::rot ); restart_speed = 0; return false; } if( sig_desc->is_pre_signal() ) { return is_pre_signal_clear( sig, next_block, restart_speed ); } if ( sig_desc->is_priority_signal() ) { return is_priority_signal_clear( sig, next_block, restart_speed ); } if( sig_desc->is_longblock_signal() ) { return is_longblock_signal_clear( sig, next_block, restart_speed ); } if( sig_desc->is_choose_sign() ) { return is_choose_signal_clear( sig, next_block, restart_speed ); } dbg->error( "rail_vehicle_t::is_signal_clear()", "felt through at signal at %s", cnv->get_route()->at(next_block).get_str() ); return false; } bool rail_vehicle_t::can_enter_tile(const grund_t *gr, sint32 &restart_speed, uint8) { assert(leading); uint16 next_signal, next_crossing; if( cnv->get_state()==convoi_t::CAN_START || cnv->get_state()==convoi_t::CAN_START_ONE_MONTH || cnv->get_state()==convoi_t::CAN_START_TWO_MONTHS ) { // reserve first block at the start until the next signal grund_t *gr_current = welt->lookup( get_pos() ); weg_t *w = gr_current ? gr_current->get_weg(get_waytype()) : NULL; if( w==NULL || !(w->has_signal() || w->is_crossing()) ) { // free track => reserve up to next signal if( !block_reserver(cnv->get_route(), max(route_index,1)-1, next_signal, next_crossing, 0, true, false ) ) { restart_speed = 0; return false; } cnv->set_next_stop_index( next_crossing<next_signal ? next_crossing : next_signal ); return true; } cnv->set_next_stop_index( max(route_index,1)-1 ); if( steps<steps_next ) { // not yet at tile border => can drive to signal safely return true; } // we start with a signal/crossing => use stuff below ... } assert(gr); if(gr->get_top()>250) { // too many objects here return false; } schiene_t *w = (schiene_t *)gr->get_weg(get_waytype()); if(w==NULL) { return false; } /* this should happen only before signals ... * but if it is already reserved, we can save lots of other checks later */ if( !w->can_reserve(cnv->self) ) { restart_speed = 0; return false; } // is there any signal/crossing to be reserved? uint16 next_block = cnv->get_next_stop_index()-1; if( next_block >= cnv->get_route()->get_count() ) { // no obstacle in the way => drive on ... return true; } // signal disappeared, train passes the tile of former signal if( next_block+1 < route_index ) { // we need to reserve the next block even if there is no signal present anymore bool ok = block_reserver( cnv->get_route(), route_index, next_signal, next_crossing, 0, true, false ); if (ok) { cnv->set_next_stop_index( min( next_crossing, next_signal ) ); } return ok; // if reservation was not possible the train will wait on the track until block is free } if( next_block <= route_index+3 ) { koord3d block_pos=cnv->get_route()->at(next_block); grund_t *gr_next_block = welt->lookup(block_pos); const schiene_t *sch1 = gr_next_block ? (const schiene_t *)gr_next_block->get_weg(get_waytype()) : NULL; if(sch1==NULL) { // way (weg) not existent (likely destroyed) cnv->suche_neue_route(); return false; } // Is a crossing? // note: crossing and signal might exist on same tile // so first check crossing if( sch1->is_crossing() ) { if( crossing_t* cr = gr_next_block->find<crossing_t>(2) ) { // ok, here is a draw/turnbridge ... bool ok = cr->request_crossing(this); if(!ok) { // cannot cross => wait here restart_speed = 0; return cnv->get_next_stop_index()>route_index+1; } else if( !sch1->has_signal() ) { // can reserve: find next place to do something and drive on if( block_pos == cnv->get_route()->back() ) { // is also last tile => go on ... cnv->set_next_stop_index( INVALID_INDEX ); return true; } else if( !block_reserver( cnv->get_route(), cnv->get_next_stop_index(), next_signal, next_crossing, 0, true, false ) ) { dbg->error( "rail_vehicle_t::can_enter_tile()", "block not free but was reserved!" ); return false; } cnv->set_next_stop_index( next_crossing<next_signal ? next_crossing : next_signal ); } } } // next check for signal if( sch1->has_signal() ) { if( !is_signal_clear( next_block, restart_speed ) ) { // only return false, if we are directly in front of the signal return cnv->get_next_stop_index()>route_index; } } } return true; } /** * reserves or un-reserves all blocks and returns the handle to the next block (if there) * if count is larger than 1, (and defined) maximum MAX_CHOOSE_BLOCK_TILES tiles will be checked * (freeing or reserving a choose signal path) * if (!reserve && force_unreserve) then un-reserve everything till the end of the route * return the last checked block */ bool rail_vehicle_t::block_reserver(const route_t *route, uint16 start_index, uint16 &next_signal_index, uint16 &next_crossing_index, int count, bool reserve, bool force_unreserve ) const { bool success=true; #ifdef MAX_CHOOSE_BLOCK_TILES int max_tiles=2*MAX_CHOOSE_BLOCK_TILES; // max tiles to check for choosesignals #endif slist_tpl<grund_t *> signs; // switch all signals on their way too ... if(start_index>=route->get_count()) { cnv->set_next_reservation_index( max(route->get_count(),1)-1 ); return 0; } if(route->at(start_index)==get_pos() && reserve) { start_index++; } if( !reserve ) { cnv->set_next_reservation_index( start_index ); } // find next block segment en route uint16 i=start_index; next_signal_index=INVALID_INDEX; next_crossing_index=INVALID_INDEX; bool unreserve_now = false; for ( ; success && count>=0 && i<route->get_count(); i++) { koord3d pos = route->at(i); grund_t *gr = welt->lookup(pos); schiene_t * sch1 = gr ? (schiene_t *)gr->get_weg(get_waytype()) : NULL; if(sch1==NULL && reserve) { // reserve until the end of track break; } // we un-reserve also nonexistent tiles! (may happen during deletion) #ifdef MAX_CHOOSE_BLOCK_TILES max_tiles--; if(max_tiles<0 && count>1) { break; } #endif if(reserve) { if( sch1->has_signal() && i<route->get_count()-1 ) { if(count) { signs.append(gr); } count --; next_signal_index = i; } if( !sch1->reserve( cnv->self, ribi_type( route->at(max(1u,i)-1u), route->at(min(route->get_count()-1u,i+1u)) ) ) ) { success = false; } if(next_crossing_index==INVALID_INDEX && sch1->is_crossing()) { next_crossing_index = i; } } else if(sch1) { if(!sch1->unreserve(cnv->self)) { if(unreserve_now) { // reached an reserved or free track => finished return false; } } else { // un-reserve from here (used during sale, since there might be reserved tiles not freed) unreserve_now = !force_unreserve; } if(sch1->has_signal()) { signal_t* signal = gr->find<signal_t>(); if(signal) { signal->set_state(roadsign_t::rot); } } if(sch1->is_crossing()) { gr->find<crossing_t>()->release_crossing(this); } } } if(!reserve) { return false; } // here we go only with reserve //DBG_MESSAGE("block_reserver()","signals at %i, success=%d",next_signal_index,success); // free, in case of un-reserve or no success in reservation if(!success) { // free reservation for ( int j=start_index; j<i; j++) { schiene_t * sch1 = (schiene_t *)welt->lookup( route->at(j))->get_weg(get_waytype()); sch1->unreserve(cnv->self); } cnv->set_next_reservation_index( start_index ); return false; } // ok, switch everything green ... FOR(slist_tpl<grund_t*>, const g, signs) { if (signal_t* const signal = g->find<signal_t>()) { signal->set_state(roadsign_t::gruen); } } cnv->set_next_reservation_index( i ); return true; } /* beware: we must un-reserve rail blocks... */ void rail_vehicle_t::leave_tile() { vehicle_t::leave_tile(); // fix counters if(last) { grund_t *gr = welt->lookup( get_pos() ); if(gr) { schiene_t *sch0 = (schiene_t *) gr->get_weg(get_waytype()); if(sch0) { sch0->unreserve(this); // tell next signal? // and switch to red if(sch0->has_signal()) { signal_t* sig = gr->find<signal_t>(); if(sig) { sig->set_state(roadsign_t::rot); } } } } } } void rail_vehicle_t::enter_tile(grund_t* gr) { vehicle_t::enter_tile(gr); if( schiene_t *sch0 = (schiene_t *) gr->get_weg(get_waytype()) ) { // way statistics const int cargo = get_total_cargo(); sch0->book(cargo, WAY_STAT_GOODS); if(leading) { sch0->book(1, WAY_STAT_CONVOIS); sch0->reserve( cnv->self, get_direction() ); } } } schedule_t * rail_vehicle_t::generate_new_schedule() const { return desc->get_waytype()==tram_wt ? new tram_schedule_t() : new train_schedule_t(); } schedule_t * monorail_vehicle_t::generate_new_schedule() const { return new monorail_schedule_t(); } schedule_t * maglev_vehicle_t::generate_new_schedule() const { return new maglev_schedule_t(); } schedule_t * narrowgauge_vehicle_t::generate_new_schedule() const { return new narrowgauge_schedule_t(); } water_vehicle_t::water_vehicle_t(koord3d pos, const vehicle_desc_t* desc, player_t* player, convoi_t* cn) : vehicle_t(pos, desc, player) { cnv = cn; } water_vehicle_t::water_vehicle_t(loadsave_t *file, bool is_first, bool is_last) : vehicle_t() { vehicle_t::rdwr_from_convoi(file); if( file->is_loading() ) { static const vehicle_desc_t *last_desc = NULL; if(is_first) { last_desc = NULL; } // try to find a matching vehicle if(desc==NULL) { dbg->warning("water_vehicle_t::water_vehicle_t()", "try to find a fitting vehicle for %s.", !fracht.empty() ? fracht.front().get_name() : "passengers"); desc = vehicle_builder_t::get_best_matching(water_wt, 0, fracht.empty() ? 0 : 30, 100, 40, !fracht.empty() ? fracht.front().get_desc() : goods_manager_t::passengers, true, last_desc, is_last ); if(desc) { calc_image(); } } // update last desc if( desc ) { last_desc = desc; } } } void water_vehicle_t::enter_tile(grund_t* gr) { vehicle_t::enter_tile(gr); if( weg_t *ch = gr->get_weg(water_wt) ) { // we are in a channel, so book statistics ch->book(get_total_cargo(), WAY_STAT_GOODS); if (leading) { ch->book(1, WAY_STAT_CONVOIS); } } } bool water_vehicle_t::check_next_tile(const grund_t *bd) const { if( bd->is_water() ) { return true; } // channel can have more stuff to check const weg_t *w = bd->get_weg(water_wt); #if ENABLE_WATERWAY_SIGNS if( w && w->has_sign() ) { const roadsign_t* rs = bd->find<roadsign_t>(); if( rs->get_desc()->get_wtyp()==get_waytype() ) { if( cnv !=NULL && rs->get_desc()->get_min_speed() > 0 && rs->get_desc()->get_min_speed() > cnv->get_min_top_speed() ) { // below speed limit return false; } if( rs->get_desc()->is_private_way() && (rs->get_player_mask() & (1<<get_player_nr()) ) == 0 ) { // private road return false; } } } #endif return (w && w->get_max_speed()>0); } /** Since slopes are handled different for ships */ void water_vehicle_t::calc_friction(const grund_t *gr) { // or a hill? if(gr->get_weg_hang()) { // hill up or down => in lock => decelerate current_friction = 16; } else { // flat track current_friction = 1; } if(previous_direction != direction) { // curve: higher friction current_friction *= 2; } } bool water_vehicle_t::can_enter_tile(const grund_t *gr, sint32 &restart_speed, uint8) { restart_speed = -1; if(leading) { assert(gr); if( gr->get_top()>251 ) { // too many ships already here .. return false; } weg_t *w = gr->get_weg(water_wt); if(w && w->is_crossing()) { // ok, here is a draw/turn-bridge ... crossing_t* cr = gr->find<crossing_t>(); if(!cr->request_crossing(this)) { restart_speed = 0; return false; } } } return true; } schedule_t * water_vehicle_t::generate_new_schedule() const { return new ship_schedule_t(); } /**** from here on planes ***/ // for flying things, everywhere is good ... // another function only called during route searching ribi_t::ribi air_vehicle_t::get_ribi(const grund_t *gr) const { switch(state) { case taxiing: case looking_for_parking: return gr->get_weg_ribi(air_wt); case taxiing_to_halt: { // we must invert all one way signs here, since we start from the target position here! weg_t *w = gr->get_weg(air_wt); if(w) { ribi_t::ribi r = w->get_ribi_unmasked(); if( ribi_t::ribi mask = w->get_ribi_maske() ) { r &= mask; } return r; } return ribi_t::none; } case landing: case departing: { ribi_t::ribi dir = gr->get_weg_ribi(air_wt); if(dir==0) { return ribi_t::all; } return dir; } case flying: case circling: return ribi_t::all; } return ribi_t::none; } // how expensive to go here (for way search) int air_vehicle_t::get_cost(const grund_t *, const weg_t *w, const sint32, ribi_t::ribi) const { // first favor faster ways int costs = 0; if(state==flying) { if(w==NULL) { costs += 1; } else { if(w->get_desc()->get_styp()==type_flat) { costs += 25; } } } else { // only, if not flying ... const runway_t *rw =(const runway_t *)w; // if we are on a runway, then take into account how many convois are already going there if( rw->get_desc()->get_styp()==1 ) { costs += rw->get_reservation_count()*9; // encourage detours even during take off } if(w->get_desc()->get_styp()==type_flat) { costs += 3; } else { costs += 2; } } return costs; } // whether the ground is drivable or not depends on the current state of the airplane bool air_vehicle_t::check_next_tile(const grund_t *bd) const { switch (state) { case taxiing: case taxiing_to_halt: case looking_for_parking: //DBG_MESSAGE("check_next_tile()","at %i,%i",bd->get_pos().x,bd->get_pos().y); return (bd->hat_weg(air_wt) && bd->get_weg(air_wt)->get_max_speed()>0); case landing: case departing: case flying: case circling: { //DBG_MESSAGE("air_vehicle_t::check_next_tile()","(cnv %i) in idx %i",cnv->self.get_id(),route_index ); // here a height check could avoid too high mountains return true; } } return false; } // this routine is called by find_route, to determined if we reached a destination bool air_vehicle_t::is_target(const grund_t *gr,const grund_t *) const { if(state!=looking_for_parking || !target_halt.is_bound()) { // search for the end of the runway const weg_t *w=gr->get_weg(air_wt); if(w && w->get_desc()->get_styp()==type_runway) { // ok here is a runway ribi_t::ribi ribi= w->get_ribi_unmasked(); if(ribi_t::is_single(ribi) && (ribi&approach_dir)!=0) { // pointing in our direction // here we should check for length, but we assume everything is ok return true; } } } else { // otherwise we just check, if we reached a free stop position of this halt if(gr->get_halt()==target_halt && target_halt->is_reservable(gr,cnv->self)) { return true; } } return false; } /* finds a free stop, calculates a route and reserve the position * else return false */ bool air_vehicle_t::find_route_to_stop_position() { if(target_halt.is_bound()) { //DBG_MESSAGE("aircraft_t::find_route_to_stop_position()","bound! (cnv %i)",cnv->self.get_id()); return true; // already searched with success } // check for skipping circle route_t *rt=cnv->access_route(); //DBG_MESSAGE("aircraft_t::find_route_to_stop_position()","can approach? (cnv %i)",cnv->self.get_id()); grund_t const* const last = welt->lookup(rt->back()); target_halt = last ? last->get_halt() : halthandle_t(); if(!target_halt.is_bound()) { return true; // no halt to search } // then: check if the search point is still on a runway (otherwise just proceed) grund_t const* const target = welt->lookup(rt->at(search_for_stop)); if(target==NULL || !target->hat_weg(air_wt)) { target_halt = halthandle_t(); block_reserver( search_for_stop, 0xFFFFu, false ); // unreserve all tiles DBG_MESSAGE("aircraft_t::find_route_to_stop_position()","no runway found at (%s)",rt->at(search_for_stop).get_str()); return true; // no runway any more ... } // is our target occupied? // DBG_MESSAGE("aircraft_t::find_route_to_stop_position()","state %i",state); if(!target_halt->find_free_position(air_wt,cnv->self,obj_t::air_vehicle) ) { target_halt = halthandle_t(); DBG_MESSAGE("aircraft_t::find_route_to_stop_position()","no free position found!"); return false; } else { // calculate route to free position: // if we fail, we will wait in a step, much more simulation friendly // and the route finder is not re-entrant! if(!cnv->is_waiting()) { target_halt = halthandle_t(); return false; } // now search a route //DBG_MESSAGE("aircraft_t::find_route_to_stop_position()","some free: find route from index %i",suchen); route_t target_rt; flight_state prev_state = state; state = looking_for_parking; if(!target_rt.find_route( welt, rt->at(search_for_stop), this, 500, ribi_t::all, welt->get_settings().get_max_choose_route_steps() )) { DBG_MESSAGE("aircraft_t::find_route_to_stop_position()","found no route to free one"); // just make sure, that there is a route at all, otherwise start route search again for( uint32 i=search_for_stop; i<rt->get_count(); i++ ) { grund_t const* const target = welt->lookup( rt->at( i ) ); if( target == NULL || !target->hat_weg( air_wt ) ) { DBG_MESSAGE( "aircraft_t::find_route_to_stop_position()", "no runway found at (%s)", rt->at( search_for_stop ).get_str() ); get_convoi()->set_state(convoi_t::ROUTING_1); block_reserver( search_for_stop, 0xFFFFu, false ); // unreserve all tiles return false; // find new route } } // circle slowly another round ... target_halt = halthandle_t(); state = prev_state; return false; } state = prev_state; // now reserve our choice ... target_halt->reserve_position(welt->lookup(target_rt.back()), cnv->self); //DBG_MESSAGE("aircraft_t::find_route_to_stop_position()", "found free stop near %i,%i,%i", target_rt.back().x, target_rt.back().y, target_rt.back().z); rt->remove_koord_from(search_for_stop); rt->append( &target_rt ); return true; } } // main routine: searches the new route in up to three steps // must also take care of stops under traveling and the like bool air_vehicle_t::calc_route(koord3d start, koord3d ziel, sint32 max_speed, route_t* route) { //DBG_MESSAGE("aircraft_t::calc_route()","search route from %i,%i,%i to %i,%i,%i",start.x,start.y,start.z,ziel.x,ziel.y,ziel.z); if(leading && cnv) { // free target reservation if( target_halt.is_bound() ) { if (grund_t* const target = welt->lookup(cnv->get_route()->back())) { target_halt->unreserve_position(target,cnv->self); } } // free runway reservation block_reserver( route_index, route->get_count(), false ); } target_halt = halthandle_t(); // no block reserved const weg_t *w=welt->lookup(start)->get_weg(air_wt); bool start_in_the_air = (w==NULL); bool end_in_air=false; search_for_stop = takeoff = touchdown = 0x7ffffffful; if(!start_in_the_air) { // see, if we find a direct route: We are finished state = taxiing; if(route->calc_route( welt, start, ziel, this, max_speed, 0 )) { // ok, we can taxi to our location return true; } } if(start_in_the_air || (w->get_desc()->get_styp()==type_runway && ribi_t::is_single(w->get_ribi())) ) { // we start here, if we are in the air or at the end of a runway search_start = start; start_in_the_air = true; route->clear(); //DBG_MESSAGE("aircraft_t::calc_route()","start in air at %i,%i,%i",search_start.x,search_start.y,search_start.z); } else { // not found and we are not on the takeoff tile (where the route search will fail too) => we try to calculate a complete route, starting with the way to the runway // second: find start runway end state = taxiing; #ifdef USE_DIFFERENT_WIND approach_dir = get_approach_ribi( ziel, start ); // reverse //DBG_MESSAGE("aircraft_t::calc_route()","search runway start near %i,%i,%i with corner in %x",start.x,start.y,start.z, approach_dir); #else approach_dir = ribi_t::northeast; // reverse DBG_MESSAGE("aircraft_t::calc_route()","search runway start near (%s)",start.get_str()); #endif if(!route->find_route( welt, start, this, max_speed, ribi_t::all, 100 )) { DBG_MESSAGE("aircraft_t::calc_route()","failed"); return false; } // save the route search_start = route->back(); //DBG_MESSAGE("aircraft_t::calc_route()","start at ground (%s)",search_start.get_str()); } // second: find target runway end state = taxiing_to_halt; // only used for search #ifdef USE_DIFFERENT_WIND approach_dir = get_approach_ribi( start, ziel ); // reverse //DBG_MESSAGE("aircraft_t::calc_route()","search runway target near %i,%i,%i in corners %x",ziel.x,ziel.y,ziel.z,approach_dir); #else approach_dir = ribi_t::southwest; // reverse //DBG_MESSAGE("aircraft_t::calc_route()","search runway target near %i,%i,%i in corners %x",ziel.x,ziel.y,ziel.z); #endif route_t end_route; if(!end_route.find_route( welt, ziel, this, max_speed, ribi_t::all, welt->get_settings().get_max_choose_route_steps() )) { // well, probably this is a waypoint if( grund_t *target = welt->lookup(ziel) ) { if( !target->get_weg(air_wt) ) { end_in_air = true; search_end = ziel; } else { // we have a taxiway/illegal runway here we cannot reach return false; // no route! } } else { // illegal coordinates? return false; } } else { // save target route search_end = end_route.back(); } //DBG_MESSAGE("aircraft_t::calc_route()","end at ground (%s)",search_end.get_str()); // create target route if(!start_in_the_air) { takeoff = route->get_count()-1; koord start_dir(welt->lookup(search_start)->get_weg_ribi(air_wt)); if(start_dir!=koord(0,0)) { // add the start ribi_t::ribi start_ribi = ribi_t::backward(ribi_type(start_dir)); const grund_t *gr=NULL; // add the start int endi = 1; int over = 3; // now add all runway + 3 ... do { if(!welt->is_within_limits(search_start.get_2d()+(start_dir*endi)) ) { break; } gr = welt->lookup_kartenboden(search_start.get_2d()+(start_dir*endi)); if(over<3 || (gr->get_weg_ribi(air_wt)&start_ribi)==0) { over --; } endi ++; route->append(gr->get_pos()); } while( over>0 ); // out of map if(gr==NULL) { dbg->error("aircraft_t::calc_route()","out of map!"); return false; } // need some extra step to avoid 180 deg turns if( start_dir.x!=0 && sgn(start_dir.x)!=sgn(search_end.x-search_start.x) ) { route->append( welt->lookup_kartenboden(gr->get_pos().get_2d()+koord(0,(search_end.y>search_start.y) ? 1 : -1 ) )->get_pos() ); route->append( welt->lookup_kartenboden(gr->get_pos().get_2d()+koord(0,(search_end.y>search_start.y) ? 2 : -2 ) )->get_pos() ); } else if( start_dir.y!=0 && sgn(start_dir.y)!=sgn(search_end.y-search_start.y) ) { route->append( welt->lookup_kartenboden(gr->get_pos().get_2d()+koord((search_end.x>search_start.x) ? 1 : -1 ,0) )->get_pos() ); route->append( welt->lookup_kartenboden(gr->get_pos().get_2d()+koord((search_end.x>search_start.x) ? 2 : -2 ,0) )->get_pos() ); } } else { // init with startpos dbg->error("aircraft_t::calc_route()","Invalid route calculation: start is on a single direction field ..."); } state = taxiing; flying_height = 0; target_height = (sint16)get_pos().z*TILE_HEIGHT_STEP; } else { // init with current pos (in air ... ) route->clear(); route->append( start ); state = flying; if(flying_height==0) { flying_height = 3*TILE_HEIGHT_STEP; } takeoff = 0; target_height = ((sint16)get_pos().z+3)*TILE_HEIGHT_STEP; } //DBG_MESSAGE("aircraft_t::calc_route()","take off ok"); koord3d landing_start=search_end; if(!end_in_air) { // now find way to start of landing pos ribi_t::ribi end_ribi = welt->lookup(search_end)->get_weg_ribi(air_wt); koord end_dir(end_ribi); end_ribi = ribi_t::backward(end_ribi); if(end_dir!=koord(0,0)) { // add the start const grund_t *gr; int endi = 1; int over = 3; // now add all runway + 3 ... do { if(!welt->is_within_limits(search_end.get_2d()+(end_dir*endi)) ) { break; } gr = welt->lookup_kartenboden(search_end.get_2d()+(end_dir*endi)); if(over<3 || (gr->get_weg_ribi(air_wt)&end_ribi)==0) { over --; } endi ++; landing_start = gr->get_pos(); } while( over>0 ); } } else { search_for_stop = touchdown = 0x7FFFFFFFul; } // just some straight routes ... if(!route->append_straight_route(welt,landing_start)) { // should never fail ... dbg->error( "aircraft_t::calc_route()", "No straight route found!" ); return false; } if(!end_in_air) { // find starting direction int offset = 0; switch(welt->lookup(search_end)->get_weg_ribi(air_wt)) { case ribi_t::north: offset = 0; break; case ribi_t::west: offset = 4; break; case ribi_t::south: offset = 8; break; case ribi_t::east: offset = 12; break; } // now make a curve koord circlepos=landing_start.get_2d(); static const koord circle_koord[16]={ koord(0,1), koord(0,1), koord(1,0), koord(0,1), koord(1,0), koord(1,0), koord(0,-1), koord(1,0), koord(0,-1), koord(0,-1), koord(-1,0), koord(0,-1), koord(-1,0), koord(-1,0), koord(0,1), koord(-1,0) }; // circle to the left for( int i=0; i<16; i++ ) { circlepos += circle_koord[(offset+i+16)%16]; if(welt->is_within_limits(circlepos)) { route->append( welt->lookup_kartenboden(circlepos)->get_pos() ); } else { // could only happen during loading old savegames; // in new versions it should not possible to build a runway here route->clear(); dbg->error("aircraft_t::calc_route()","airport too close to the edge! (Cannot go to %i,%i!)",circlepos.x,circlepos.y); return false; } } touchdown = route->get_count()+2; route->append_straight_route(welt,search_end); // now the route reach point (+1, since it will check before entering the tile ...) search_for_stop = route->get_count()-1; // now we just append the rest for( int i=end_route.get_count()-2; i>=0; i-- ) { route->append(end_route.at(i)); } } //DBG_MESSAGE("aircraft_t::calc_route()","departing=%i touchdown=%i suchen=%i total=%i state=%i",takeoff, touchdown, suchen, route->get_count()-1, state ); return true; } /* reserves runways (reserve true) or removes the reservation * finishes when reaching end tile or leaving the ground (end of runway) * @return true if the reservation is successful */ bool air_vehicle_t::block_reserver( uint32 start, uint32 end, bool reserve ) const { bool start_now = false; bool success = true; const route_t *route = cnv->get_route(); if(route->empty()) { return false; } for( uint32 i=start; success && i<end && i<route->get_count(); i++) { grund_t *gr = welt->lookup(route->at(i)); runway_t *sch1 = gr ? (runway_t *)gr->get_weg(air_wt) : NULL; if( !sch1 ) { if(reserve) { if(!start_now) { // touched down here start = i; } else { // most likely left the ground here ... end = i; break; } } } else { // we un-reserve also nonexistent tiles! (may happen during deletion) if(reserve) { start_now = true; sch1->add_convoi_reservation(cnv->self); if( !sch1->reserve(cnv->self,ribi_t::none) ) { // unsuccessful => must un-reserve all success = false; end = i; break; } // end of runway? if( i > start && (ribi_t::is_single( sch1->get_ribi_unmasked() ) || sch1->get_desc()->get_styp() != type_runway) ) { end = i; break; } } else { // we always unreserve everything sch1->unreserve(cnv->self); } } } // un-reserve if not successful if( !success && reserve ) { for( uint32 i=start; i<end; i++ ) { grund_t *gr = welt->lookup(route->at(i)); if (gr) { runway_t* sch1 = (runway_t *)gr->get_weg(air_wt); if (sch1) { sch1->unreserve(cnv->self); } } } return false; } if( reserve && end<touchdown ) { // reserve runway for landing for load balancing for( uint32 i=touchdown; i<route->get_count(); i++ ) { if( grund_t *gr = welt->lookup(route->at(i)) ) { if( runway_t* sch1 = (runway_t *)gr->get_weg(air_wt) ) { if( sch1->get_desc()->get_styp()!=type_runway ) { break; } sch1->add_convoi_reservation( cnv->self ); } } } } return success; } // handles all the decisions on the ground an in the air bool air_vehicle_t::can_enter_tile(const grund_t *gr, sint32 &restart_speed, uint8) { restart_speed = -1; assert(gr); if(gr->get_top()>250) { // too many objects here return false; } if( route_index < takeoff && route_index > 1 && takeoff<cnv->get_route()->get_count()-1 ) { // check, if tile occupied by a plane on ground if( route_index > 1 ) { for( uint8 i = 1; i<gr->get_top(); i++ ) { obj_t *obj = gr->obj_bei(i); if( obj->get_typ()==obj_t::air_vehicle && ((air_vehicle_t *)obj)->is_on_ground() ) { restart_speed = 0; return false; } } } // need to reserve runway? runway_t *rw = (runway_t *)gr->get_weg(air_wt); if(rw==NULL) { cnv->suche_neue_route(); return false; } // next tile a runway => then reserve if(rw->get_desc()->get_styp()==type_runway) { // try to reserve the runway if(!block_reserver(takeoff,takeoff+100,true)) { // runway already blocked ... restart_speed = 0; return false; } } return true; } if( state == taxiing ) { // enforce on ground for taxiing flying_height = 0; // we may need to unreserve the runway after leaving it if( route_index >= touchdown ) { runway_t *rw = (runway_t *)gr->get_weg(air_wt); // next tile a not runway => then unreserve if( rw == NULL || rw->get_desc()->get_styp() != type_runway || gr->is_halt() ) { block_reserver( touchdown, search_for_stop+1, false ); } } } if( route_index == takeoff && state == taxiing ) { // try to reserve the runway if not already done if(route_index==2 && !block_reserver(takeoff,takeoff+100,true)) { // runway blocked, wait at start of runway restart_speed = 0; return false; } // stop shortly at the end of the runway state = departing; restart_speed = 0; return false; } //DBG_MESSAGE("aircraft_t::ist_weg_frei()","index %i<>%i",route_index,touchdown); // check for another circle ... if( route_index==(touchdown-3) ) { if( !block_reserver( touchdown, search_for_stop+1, true ) ) { route_index -= 16; return true; } state = landing; return true; } if( route_index==touchdown-16-3 && state!=circling ) { // just check, if the end of runway is free; we will wait there if( block_reserver( touchdown, search_for_stop+1, true ) ) { route_index += 16; // can land => set landing height state = landing; } else { // circle slowly next round state = circling; cnv->must_recalc_data(); if( leading ) { cnv->must_recalc_data_front(); } } } if(route_index==search_for_stop && state==landing && !target_halt.is_bound()) { // if we fail, we will wait in a step, much more simulation friendly // and the route finder is not re-entrant! if(!cnv->is_waiting()) { return false; } // nothing free here? if(find_route_to_stop_position()) { // stop reservation successful state = taxiing; return true; } restart_speed = 0; return false; } if(state==looking_for_parking) { state = taxiing; } if(state == taxiing && gr->is_halt() && gr->find<air_vehicle_t>()) { // the next step is a parking position. We do not enter, if occupied! restart_speed = 0; return false; } return true; } // this must also change the internal modes for the calculation void air_vehicle_t::enter_tile(grund_t* gr) { vehicle_t::enter_tile(gr); if( this->is_on_ground() ) { runway_t *w=(runway_t *)gr->get_weg(air_wt); if(w) { const int cargo = get_total_cargo(); w->book(cargo, WAY_STAT_GOODS); if (leading) { w->book(1, WAY_STAT_CONVOIS); } } } } air_vehicle_t::air_vehicle_t(loadsave_t *file, bool is_first, bool is_last) : vehicle_t() { rdwr_from_convoi(file); if( file->is_loading() ) { static const vehicle_desc_t *last_desc = NULL; if(is_first) { last_desc = NULL; } // try to find a matching vehicle if(desc==NULL) { dbg->warning("aircraft_t::aircraft_t()", "try to find a fitting vehicle for %s.", !fracht.empty() ? fracht.front().get_name() : "passengers"); desc = vehicle_builder_t::get_best_matching(air_wt, 0, 101, 1000, 800, !fracht.empty() ? fracht.front().get_desc() : goods_manager_t::passengers, true, last_desc, is_last ); if(desc) { calc_image(); } } // update last desc if( desc ) { last_desc = desc; } } } air_vehicle_t::air_vehicle_t(koord3d pos, const vehicle_desc_t* desc, player_t* player, convoi_t* cn) : vehicle_t(pos, desc, player) { cnv = cn; state = taxiing; flying_height = 0; target_height = pos.z; } air_vehicle_t::~air_vehicle_t() { // mark aircraft (after_image) dirty, since we have no "real" image const int raster_width = get_current_tile_raster_width(); sint16 yoff = tile_raster_scale_y(-flying_height-get_hoff()-2, raster_width); mark_image_dirty( image, yoff); mark_image_dirty( image, 0 ); } void air_vehicle_t::set_convoi(convoi_t *c) { DBG_MESSAGE("aircraft_t::set_convoi()","%p",c); if(leading && (unsigned long)cnv > 1) { // free stop reservation route_t const& r = *cnv->get_route(); if(target_halt.is_bound()) { target_halt->unreserve_position(welt->lookup(r.back()), cnv->self); target_halt = halthandle_t(); } if (!r.empty()) { // free runway reservation if(route_index>=takeoff && route_index<touchdown-4 && state!=flying) { block_reserver( takeoff, takeoff+100, false ); } else if(route_index>=touchdown-1 && state!=taxiing) { block_reserver( touchdown, search_for_stop+1, false ); } } } // maybe need to restore state? if(c!=NULL) { bool target=(bool)cnv; vehicle_t::set_convoi(c); if(leading) { if(target) { // reinitialize the target halt grund_t* const target=welt->lookup(cnv->get_route()->back()); target_halt = target->get_halt(); if(target_halt.is_bound()) { target_halt->reserve_position(target,cnv->self); } } // restore reservation if( grund_t *gr = welt->lookup(get_pos()) ) { if( weg_t *weg = gr->get_weg(air_wt) ) { if( weg->get_desc()->get_styp()==type_runway ) { // but only if we are on a runway ... if( route_index>=takeoff && route_index<touchdown-21 && state!=flying ) { block_reserver( takeoff, takeoff+100, true ); } else if( route_index>=touchdown-1 && state!=taxiing ) { block_reserver( touchdown, search_for_stop+1, true ); } } } } } } else { vehicle_t::set_convoi(NULL); } } schedule_t *air_vehicle_t::generate_new_schedule() const { return new airplane_schedule_t(); } void air_vehicle_t::rdwr_from_convoi(loadsave_t *file) { xml_tag_t t( file, "aircraft_t" ); // initialize as vehicle_t::rdwr_from_convoi calls get_image() if (file->is_loading()) { state = taxiing; flying_height = 0; } vehicle_t::rdwr_from_convoi(file); file->rdwr_enum(state); file->rdwr_short(flying_height); flying_height &= ~(TILE_HEIGHT_STEP-1); file->rdwr_short(target_height); file->rdwr_long(search_for_stop); file->rdwr_long(touchdown); file->rdwr_long(takeoff); } #ifdef USE_DIFFERENT_WIND // well lots of code to make sure, we have at least two different directions for the runway search uint8 air_vehicle_t::get_approach_ribi( koord3d start, koord3d ziel ) { uint8 dir = ribi_type(start, ziel); // reverse // make sure, there are at last two directions to choose, or you might en up with not route if(ribi_t::is_single(dir)) { dir |= (dir<<1); if(dir>16) { dir += 1; } } return dir&0x0F; } #endif void air_vehicle_t::hop(grund_t* gr) { sint32 new_speed_limit = SPEED_UNLIMITED; sint32 new_friction = 0; // take care of in-flight height ... const sint16 h_cur = (sint16)get_pos().z*TILE_HEIGHT_STEP; const sint16 h_next = (sint16)pos_next.z*TILE_HEIGHT_STEP; switch(state) { case departing: { flying_height = 0; target_height = h_cur; new_friction = max( 1, 28/(1+(route_index-takeoff)*2) ); // 9 5 4 3 2 2 1 1... // take off, when a) end of runway or b) last tile of runway or c) fast enough weg_t *weg=welt->lookup(get_pos())->get_weg(air_wt); if( (weg==NULL || // end of runway (broken runway) weg->get_desc()->get_styp()!=type_runway || // end of runway (grass now ... ) (route_index>takeoff+1 && ribi_t::is_single(weg->get_ribi_unmasked())) ) || // single ribi at end of runway cnv->get_akt_speed()>kmh_to_speed(desc->get_topspeed())/3 // fast enough ) { state = flying; new_friction = 1; block_reserver( takeoff, touchdown-1, false ); flying_height = h_cur - h_next; target_height = h_cur+TILE_HEIGHT_STEP*3; } break; } case circling: { new_speed_limit = kmh_to_speed(desc->get_topspeed())/3; new_friction = 4; // do not change height any more while circling flying_height += h_cur; flying_height -= h_next; break; } case flying: { // since we are at a tile border, round up to the nearest value flying_height += h_cur; if( flying_height < target_height ) { flying_height = (flying_height+TILE_HEIGHT_STEP) & ~(TILE_HEIGHT_STEP-1); } else if( flying_height > target_height ) { flying_height = (flying_height-TILE_HEIGHT_STEP); } flying_height -= h_next; // did we have to change our flight height? if( target_height-h_next > TILE_HEIGHT_STEP*5 ) { // Move down target_height -= TILE_HEIGHT_STEP*2; } else if( target_height-h_next < TILE_HEIGHT_STEP*2 ) { // Move up target_height += TILE_HEIGHT_STEP*2; } break; } case landing: { new_speed_limit = kmh_to_speed(desc->get_topspeed())/3; // ==approach speed new_friction = 8; flying_height += h_cur; if( flying_height < target_height ) { flying_height = (flying_height+TILE_HEIGHT_STEP) & ~(TILE_HEIGHT_STEP-1); } else if( flying_height > target_height ) { flying_height = (flying_height-TILE_HEIGHT_STEP); } if (route_index >= touchdown) { // come down, now! target_height = h_next; // touchdown! if (flying_height==h_next) { const sint32 taxi_speed = kmh_to_speed( min( 60, desc->get_topspeed()/4 ) ); if( cnv->get_akt_speed() <= taxi_speed ) { new_speed_limit = taxi_speed; new_friction = 16; } else { const sint32 runway_left = search_for_stop - route_index; new_speed_limit = min( new_speed_limit, runway_left*runway_left*taxi_speed ); // ...approach 540 240 60 60 const sint32 runway_left_fr = max( 0, 6-runway_left ); new_friction = max( new_friction, min( desc->get_topspeed()/12, 4 + 4*(runway_left_fr*runway_left_fr+1) )); // ...8 8 12 24 44 72 108 152 } } } else { // runway is on this height const sint16 runway_height = cnv->get_route()->at(touchdown).z*TILE_HEIGHT_STEP; // we are too low, ascent asap if (flying_height < runway_height + TILE_HEIGHT_STEP) { target_height = runway_height + TILE_HEIGHT_STEP; } // too high, descent else if (flying_height + h_next - h_cur > runway_height + (sint16)(touchdown-route_index-1)*TILE_HEIGHT_STEP) { target_height = runway_height + (touchdown-route_index-1)*TILE_HEIGHT_STEP; } } flying_height -= h_next; break; } default: { new_speed_limit = kmh_to_speed( min( 60, desc->get_topspeed()/4 ) ); new_friction = 16; flying_height = 0; target_height = h_next; break; } } // hop to next tile vehicle_t::hop(gr); speed_limit = new_speed_limit; current_friction = new_friction; // friction factors and speed limit may have changed // TODO use the same logic as in vehicle_t::hop cnv->must_recalc_data(); } // this routine will display the aircraft (if in flight) #ifdef MULTI_THREAD void air_vehicle_t::display_after(int xpos_org, int ypos_org, const sint8 clip_num) const #else void air_vehicle_t::display_after(int xpos_org, int ypos_org, bool is_global) const #endif { if( image != IMG_EMPTY && !is_on_ground() ) { int xpos = xpos_org, ypos = ypos_org; const int raster_width = get_current_tile_raster_width(); const sint16 z = get_pos().z; if( z + flying_height/TILE_HEIGHT_STEP - 1 > grund_t::underground_level ) { return; } const sint16 target = target_height - ((sint16)z*TILE_HEIGHT_STEP); sint16 current_flughohe = flying_height; if( current_flughohe < target ) { current_flughohe += (steps*TILE_HEIGHT_STEP) >> 8; } else if( current_flughohe > target ) { current_flughohe -= (steps*TILE_HEIGHT_STEP) >> 8; } sint8 hoff = get_hoff(); ypos += tile_raster_scale_y(get_yoff()-current_flughohe-hoff-2, raster_width); xpos += tile_raster_scale_x(get_xoff(), raster_width); get_screen_offset( xpos, ypos, raster_width ); display_swap_clip_wh(CLIP_NUM_VAR); // will be dirty // the aircraft!!! display_color( image, xpos, ypos, get_player_nr(), true, true/*get_flag(obj_t::dirty)*/ CLIP_NUM_PAR); #ifndef MULTI_THREAD vehicle_t::display_after( xpos_org, ypos_org - tile_raster_scale_y( current_flughohe - hoff - 2, raster_width ), is_global ); #endif display_swap_clip_wh(CLIP_NUM_VAR); } #ifdef MULTI_THREAD } void air_vehicle_t::display_overlay(int xpos_org, int ypos_org) const { if( image != IMG_EMPTY && !is_on_ground() ) { const int raster_width = get_current_tile_raster_width(); const sint16 z = get_pos().z; if( z + flying_height/TILE_HEIGHT_STEP - 1 > grund_t::underground_level ) { return; } const sint16 target = target_height - ((sint16)z*TILE_HEIGHT_STEP); sint16 current_flughohe = flying_height; if( current_flughohe < target ) { current_flughohe += (steps*TILE_HEIGHT_STEP) >> 8; } else if( current_flughohe > target ) { current_flughohe -= (steps*TILE_HEIGHT_STEP) >> 8; } vehicle_t::display_overlay( xpos_org, ypos_org - tile_raster_scale_y( current_flughohe - get_hoff() - 2, raster_width ) ); } #endif else if( is_on_ground() ) { // show loading tooltips on ground #ifdef MULTI_THREAD vehicle_t::display_overlay( xpos_org, ypos_org ); #else vehicle_t::display_after( xpos_org, ypos_org, is_global ); #endif } } const char *air_vehicle_t::is_deletable(const player_t *player) { if (is_on_ground()) { return vehicle_t::is_deletable(player); } return NULL; }
30.415935
358
0.66203
vinijabes
8b2a5fa7caab27fd1b4932f587ff704a2a67c126
6,262
cpp
C++
ur_calibration/src/calibration_correction.cpp
mowito/Universal_Robots_ROS2_Driver
a5fbbb2e52b9d1111c46bb172c74f9f0063dabbd
[ "BSD-3-Clause" ]
null
null
null
ur_calibration/src/calibration_correction.cpp
mowito/Universal_Robots_ROS2_Driver
a5fbbb2e52b9d1111c46bb172c74f9f0063dabbd
[ "BSD-3-Clause" ]
null
null
null
ur_calibration/src/calibration_correction.cpp
mowito/Universal_Robots_ROS2_Driver
a5fbbb2e52b9d1111c46bb172c74f9f0063dabbd
[ "BSD-3-Clause" ]
null
null
null
// -- BEGIN LICENSE BLOCK ---------------------------------------------- // Created on behalf of Universal Robots A/S // Copyright 2019 FZI Forschungszentrum Informatik // // 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 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. // -- END LICENSE BLOCK ------------------------------------------------ //---------------------------------------------------------------------- /*!\file * * \author Felix Exner exner@fzi.de * \date 2019-01-10 * \author Lovro Ivanov lovro.ivanov@gmail.com * \date 2021-09-22 * */ //---------------------------------------------------------------------- #include "ur_calibration/calibration_consumer.hpp" #include <filesystem> #include <memory> #include <string> #include "ur_client_library/comm/parser.h" #include "ur_client_library/comm/pipeline.h" #include "ur_client_library/comm/producer.h" #include "ur_client_library/comm/stream.h" #include "ur_client_library/primary/package_header.h" #include "ur_client_library/primary/primary_parser.h" #include "ur_robot_driver/urcl_log_handler.hpp" #include "ament_index_cpp/get_package_share_directory.hpp" #include "rclcpp/exceptions/exceptions.hpp" #include "sensor_msgs/msg/joint_state.hpp" #include "tf2_ros/transform_listener.h" namespace fs = std::filesystem; using urcl::UrException; using urcl::comm::INotifier; using urcl::comm::Pipeline; using urcl::comm::URProducer; using urcl::comm::URStream; using urcl::primary_interface::PrimaryPackage; using urcl::primary_interface::PrimaryParser; using urcl::primary_interface::UR_PRIMARY_PORT; using ur_calibration::CalibrationConsumer; class CalibrationCorrection : public rclcpp::Node { public: CalibrationCorrection() : Node( "ur_calibration", rclcpp::NodeOptions().allow_undeclared_parameters(true).automatically_declare_parameters_from_overrides(true)) { std::string output_package_name; try { // The robot's IP address robot_ip_ = this->get_parameter("robot_ip").as_string(); // The target file where the calibration data is written to output_filename_ = this->get_parameter("output_filename").as_string(); } catch (rclcpp::exceptions::ParameterNotDeclaredException& e) { RCLCPP_FATAL_STREAM(this->get_logger(), e.what()); exit(1); } } virtual ~CalibrationCorrection() = default; void run() { URStream<PrimaryPackage> stream(robot_ip_, UR_PRIMARY_PORT); PrimaryParser parser; URProducer<PrimaryPackage> prod(stream, parser); CalibrationConsumer consumer; INotifier notifier; Pipeline<PrimaryPackage> pipeline(prod, &consumer, "Pipeline", notifier); pipeline.run(); while (!consumer.isCalibrated()) { rclcpp::sleep_for(rclcpp::Duration::from_seconds(0.1).to_chrono<std::chrono::nanoseconds>()); } calibration_data_.reset(new YAML::Node); *calibration_data_ = consumer.getCalibrationParameters(); } bool writeCalibrationData() { if (calibration_data_ == nullptr) { RCLCPP_ERROR_STREAM(this->get_logger(), "Calibration data not yet set."); return false; } fs::path out_path = fs::absolute(output_filename_); fs::path dst_path = out_path.parent_path(); if (!fs::exists(dst_path)) { RCLCPP_ERROR_STREAM(this->get_logger(), "Parent folder " << dst_path << " does not exist."); return false; } RCLCPP_INFO_STREAM(this->get_logger(), "Writing calibration data to " << out_path); if (fs::exists(output_filename_)) { RCLCPP_WARN_STREAM(this->get_logger(), "Output file " << output_filename_ << " already exists. Overwriting."); } std::ofstream file(output_filename_); if (file.is_open()) { file << *calibration_data_; } else { RCLCPP_ERROR_STREAM(this->get_logger(), "Failed writing the file. Do you have the correct rights?"); return false; } RCLCPP_INFO_STREAM(this->get_logger(), "Wrote output."); return true; } private: std::string robot_ip_; std::string output_filename_; std::shared_ptr<YAML::Node> calibration_data_; }; int main(int argc, char* argv[]) { rclcpp::init(argc, argv); ur_robot_driver::registerUrclLogHandler(); try { auto calib_node = std::make_shared<CalibrationCorrection>(); calib_node->run(); if (!calib_node->writeCalibrationData()) { RCLCPP_ERROR_STREAM(calib_node->get_logger(), "Failed writing calibration data. See errors above for details."); return -1; } RCLCPP_INFO_STREAM(calib_node->get_logger(), "Calibration correction done"); } catch (const UrException& e) { RCLCPP_ERROR_STREAM(rclcpp::get_logger("ur_calibration"), e.what()); } catch (const std::exception& e) { RCLCPP_ERROR_STREAM(rclcpp::get_logger("ur_calibration"), e.what()); } rclcpp::shutdown(); return 0; }
35.179775
120
0.696583
mowito
8b2cba9ce1f1cb5957716f26a7ad3f9a843f575f
84,153
hpp
C++
modules/dnn/include/opencv2/dnn/dnn.hpp
Synkar/opencv
266835cd2eb5e0d66eeb2e11bb9add8a3f2e74ae
[ "Apache-2.0" ]
1
2022-01-28T09:14:05.000Z
2022-01-28T09:14:05.000Z
modules/dnn/include/opencv2/dnn/dnn.hpp
Synkar/opencv
266835cd2eb5e0d66eeb2e11bb9add8a3f2e74ae
[ "Apache-2.0" ]
null
null
null
modules/dnn/include/opencv2/dnn/dnn.hpp
Synkar/opencv
266835cd2eb5e0d66eeb2e11bb9add8a3f2e74ae
[ "Apache-2.0" ]
null
null
null
/*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) 2013, OpenCV Foundation, 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*/ #ifndef OPENCV_DNN_DNN_HPP #define OPENCV_DNN_DNN_HPP #include <vector> #include <opencv2/core.hpp> #include "opencv2/core/async.hpp" #include "../dnn/version.hpp" #include <opencv2/dnn/dict.hpp> namespace cv { namespace dnn { CV__DNN_INLINE_NS_BEGIN //! @addtogroup dnn //! @{ typedef std::vector<int> MatShape; /** * @brief Enum of computation backends supported by layers. * @see Net::setPreferableBackend */ enum Backend { //! DNN_BACKEND_DEFAULT equals to DNN_BACKEND_INFERENCE_ENGINE if //! OpenCV is built with Intel's Inference Engine library or //! DNN_BACKEND_OPENCV otherwise. DNN_BACKEND_DEFAULT = 0, DNN_BACKEND_HALIDE, DNN_BACKEND_INFERENCE_ENGINE, //!< Intel's Inference Engine computational backend //!< @sa setInferenceEngineBackendType DNN_BACKEND_OPENCV, DNN_BACKEND_VKCOM, DNN_BACKEND_CUDA, DNN_BACKEND_WEBNN, #ifdef __OPENCV_BUILD DNN_BACKEND_INFERENCE_ENGINE_NGRAPH = 1000000, // internal - use DNN_BACKEND_INFERENCE_ENGINE + setInferenceEngineBackendType() DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019, // internal - use DNN_BACKEND_INFERENCE_ENGINE + setInferenceEngineBackendType() #endif }; /** * @brief Enum of target devices for computations. * @see Net::setPreferableTarget */ enum Target { DNN_TARGET_CPU = 0, DNN_TARGET_OPENCL, DNN_TARGET_OPENCL_FP16, DNN_TARGET_MYRIAD, DNN_TARGET_VULKAN, DNN_TARGET_FPGA, //!< FPGA device with CPU fallbacks using Inference Engine's Heterogeneous plugin. DNN_TARGET_CUDA, DNN_TARGET_CUDA_FP16, DNN_TARGET_HDDL }; CV_EXPORTS std::vector< std::pair<Backend, Target> > getAvailableBackends(); CV_EXPORTS_W std::vector<Target> getAvailableTargets(dnn::Backend be); /** * @brief Enables detailed logging of the DNN model loading with CV DNN API. * @param[in] isDiagnosticsMode Indicates whether diagnostic mode should be set. * * Diagnostic mode provides detailed logging of the model loading stage to explore * potential problems (ex.: not implemented layer type). * * @note In diagnostic mode series of assertions will be skipped, it can lead to the * expected application crash. */ CV_EXPORTS void enableModelDiagnostics(bool isDiagnosticsMode); /** @brief This class provides all data needed to initialize layer. * * It includes dictionary with scalar params (which can be read by using Dict interface), * blob params #blobs and optional meta information: #name and #type of layer instance. */ class CV_EXPORTS LayerParams : public Dict { public: //TODO: Add ability to name blob params std::vector<Mat> blobs; //!< List of learned parameters stored as blobs. String name; //!< Name of the layer instance (optional, can be used internal purposes). String type; //!< Type name which was used for creating layer by layer factory (optional). }; /** * @brief Derivatives of this class encapsulates functions of certain backends. */ class BackendNode { public: explicit BackendNode(int backendId); virtual ~BackendNode(); //!< Virtual destructor to make polymorphism. int backendId; //!< Backend identifier. }; /** * @brief Derivatives of this class wraps cv::Mat for different backends and targets. */ class BackendWrapper { public: BackendWrapper(int backendId, int targetId); /** * @brief Wrap cv::Mat for specific backend and target. * @param[in] targetId Target identifier. * @param[in] m cv::Mat for wrapping. * * Make CPU->GPU data transfer if it's require for the target. */ BackendWrapper(int targetId, const cv::Mat& m); /** * @brief Make wrapper for reused cv::Mat. * @param[in] base Wrapper of cv::Mat that will be reused. * @param[in] shape Specific shape. * * Initialize wrapper from another one. It'll wrap the same host CPU * memory and mustn't allocate memory on device(i.e. GPU). It might * has different shape. Use in case of CPU memory reusing for reuse * associated memory on device too. */ BackendWrapper(const Ptr<BackendWrapper>& base, const MatShape& shape); virtual ~BackendWrapper(); //!< Virtual destructor to make polymorphism. /** * @brief Transfer data to CPU host memory. */ virtual void copyToHost() = 0; /** * @brief Indicate that an actual data is on CPU. */ virtual void setHostDirty() = 0; int backendId; //!< Backend identifier. int targetId; //!< Target identifier. }; class CV_EXPORTS ActivationLayer; /** @brief This interface class allows to build new Layers - are building blocks of networks. * * Each class, derived from Layer, must implement allocate() methods to declare own outputs and forward() to compute outputs. * Also before using the new layer into networks you must register your layer by using one of @ref dnnLayerFactory "LayerFactory" macros. */ class CV_EXPORTS_W Layer : public Algorithm { public: //! List of learned parameters must be stored here to allow read them by using Net::getParam(). CV_PROP_RW std::vector<Mat> blobs; /** @brief Computes and sets internal parameters according to inputs, outputs and blobs. * @deprecated Use Layer::finalize(InputArrayOfArrays, OutputArrayOfArrays) instead * @param[in] input vector of already allocated input blobs * @param[out] output vector of already allocated output blobs * * If this method is called after network has allocated all memory for input and output blobs * and before inferencing. */ CV_DEPRECATED_EXTERNAL virtual void finalize(const std::vector<Mat*> &input, std::vector<Mat> &output); /** @brief Computes and sets internal parameters according to inputs, outputs and blobs. * @param[in] inputs vector of already allocated input blobs * @param[out] outputs vector of already allocated output blobs * * If this method is called after network has allocated all memory for input and output blobs * and before inferencing. */ CV_WRAP virtual void finalize(InputArrayOfArrays inputs, OutputArrayOfArrays outputs); /** @brief Given the @p input blobs, computes the output @p blobs. * @deprecated Use Layer::forward(InputArrayOfArrays, OutputArrayOfArrays, OutputArrayOfArrays) instead * @param[in] input the input blobs. * @param[out] output allocated output blobs, which will store results of the computation. * @param[out] internals allocated internal blobs */ CV_DEPRECATED_EXTERNAL virtual void forward(std::vector<Mat*> &input, std::vector<Mat> &output, std::vector<Mat> &internals); /** @brief Given the @p input blobs, computes the output @p blobs. * @param[in] inputs the input blobs. * @param[out] outputs allocated output blobs, which will store results of the computation. * @param[out] internals allocated internal blobs */ virtual void forward(InputArrayOfArrays inputs, OutputArrayOfArrays outputs, OutputArrayOfArrays internals); /** @brief Tries to quantize the given layer and compute the quantization parameters required for fixed point implementation. * @param[in] scales input and output scales. * @param[in] zeropoints input and output zeropoints. * @param[out] params Quantized parameters required for fixed point implementation of that layer. * @returns True if layer can be quantized. */ virtual bool tryQuantize(const std::vector<std::vector<float> > &scales, const std::vector<std::vector<int> > &zeropoints, LayerParams& params); /** @brief Given the @p input blobs, computes the output @p blobs. * @param[in] inputs the input blobs. * @param[out] outputs allocated output blobs, which will store results of the computation. * @param[out] internals allocated internal blobs */ void forward_fallback(InputArrayOfArrays inputs, OutputArrayOfArrays outputs, OutputArrayOfArrays internals); /** @brief * @overload * @deprecated Use Layer::finalize(InputArrayOfArrays, OutputArrayOfArrays) instead */ CV_DEPRECATED_EXTERNAL void finalize(const std::vector<Mat> &inputs, CV_OUT std::vector<Mat> &outputs); /** @brief * @overload * @deprecated Use Layer::finalize(InputArrayOfArrays, OutputArrayOfArrays) instead */ CV_DEPRECATED std::vector<Mat> finalize(const std::vector<Mat> &inputs); /** @brief Allocates layer and computes output. * @deprecated This method will be removed in the future release. */ CV_DEPRECATED CV_WRAP void run(const std::vector<Mat> &inputs, CV_OUT std::vector<Mat> &outputs, CV_IN_OUT std::vector<Mat> &internals); /** @brief Returns index of input blob into the input array. * @param inputName label of input blob * * Each layer input and output can be labeled to easily identify them using "%<layer_name%>[.output_name]" notation. * This method maps label of input blob to its index into input vector. */ virtual int inputNameToIndex(String inputName); // FIXIT const /** @brief Returns index of output blob in output array. * @see inputNameToIndex() */ CV_WRAP virtual int outputNameToIndex(const String& outputName); // FIXIT const /** * @brief Ask layer if it support specific backend for doing computations. * @param[in] backendId computation backend identifier. * @see Backend */ virtual bool supportBackend(int backendId); // FIXIT const /** * @brief Returns Halide backend node. * @param[in] inputs Input Halide buffers. * @see BackendNode, BackendWrapper * * Input buffers should be exactly the same that will be used in forward invocations. * Despite we can use Halide::ImageParam based on input shape only, * it helps prevent some memory management issues (if something wrong, * Halide tests will be failed). */ virtual Ptr<BackendNode> initHalide(const std::vector<Ptr<BackendWrapper> > &inputs); virtual Ptr<BackendNode> initInfEngine(const std::vector<Ptr<BackendWrapper> > &inputs); virtual Ptr<BackendNode> initNgraph(const std::vector<Ptr<BackendWrapper> > &inputs, const std::vector<Ptr<BackendNode> >& nodes); virtual Ptr<BackendNode> initVkCom(const std::vector<Ptr<BackendWrapper> > &inputs); virtual Ptr<BackendNode> initWebnn(const std::vector<Ptr<BackendWrapper> > &inputs, const std::vector<Ptr<BackendNode> >& nodes); /** * @brief Returns a CUDA backend node * * @param context void pointer to CSLContext object * @param inputs layer inputs * @param outputs layer outputs */ virtual Ptr<BackendNode> initCUDA( void *context, const std::vector<Ptr<BackendWrapper>>& inputs, const std::vector<Ptr<BackendWrapper>>& outputs ); /** * @brief Automatic Halide scheduling based on layer hyper-parameters. * @param[in] node Backend node with Halide functions. * @param[in] inputs Blobs that will be used in forward invocations. * @param[in] outputs Blobs that will be used in forward invocations. * @param[in] targetId Target identifier * @see BackendNode, Target * * Layer don't use own Halide::Func members because we can have applied * layers fusing. In this way the fused function should be scheduled. */ virtual void applyHalideScheduler(Ptr<BackendNode>& node, const std::vector<Mat*> &inputs, const std::vector<Mat> &outputs, int targetId) const; /** * @brief Implement layers fusing. * @param[in] node Backend node of bottom layer. * @see BackendNode * * Actual for graph-based backends. If layer attached successfully, * returns non-empty cv::Ptr to node of the same backend. * Fuse only over the last function. */ virtual Ptr<BackendNode> tryAttach(const Ptr<BackendNode>& node); /** * @brief Tries to attach to the layer the subsequent activation layer, i.e. do the layer fusion in a partial case. * @param[in] layer The subsequent activation layer. * * Returns true if the activation layer has been attached successfully. */ virtual bool setActivation(const Ptr<ActivationLayer>& layer); /** * @brief Try to fuse current layer with a next one * @param[in] top Next layer to be fused. * @returns True if fusion was performed. */ virtual bool tryFuse(Ptr<Layer>& top); /** * @brief Returns parameters of layers with channel-wise multiplication and addition. * @param[out] scale Channel-wise multipliers. Total number of values should * be equal to number of channels. * @param[out] shift Channel-wise offsets. Total number of values should * be equal to number of channels. * * Some layers can fuse their transformations with further layers. * In example, convolution + batch normalization. This way base layer * use weights from layer after it. Fused layer is skipped. * By default, @p scale and @p shift are empty that means layer has no * element-wise multiplications or additions. */ virtual void getScaleShift(Mat& scale, Mat& shift) const; /** * @brief Returns scale and zeropoint of layers * @param[out] scale Output scale * @param[out] zeropoint Output zeropoint * * By default, @p scale is 1 and @p zeropoint is 0. */ virtual void getScaleZeropoint(float& scale, int& zeropoint) const; /** * @brief "Deattaches" all the layers, attached to particular layer. */ virtual void unsetAttached(); virtual bool getMemoryShapes(const std::vector<MatShape> &inputs, const int requiredOutputs, std::vector<MatShape> &outputs, std::vector<MatShape> &internals) const; virtual int64 getFLOPS(const std::vector<MatShape> &inputs, const std::vector<MatShape> &outputs) const {CV_UNUSED(inputs); CV_UNUSED(outputs); return 0;} virtual bool updateMemoryShapes(const std::vector<MatShape> &inputs); CV_PROP String name; //!< Name of the layer instance, can be used for logging or other internal purposes. CV_PROP String type; //!< Type name which was used for creating layer by layer factory. CV_PROP int preferableTarget; //!< prefer target for layer forwarding Layer(); explicit Layer(const LayerParams &params); //!< Initializes only #name, #type and #blobs fields. void setParamsFrom(const LayerParams &params); //!< Initializes only #name, #type and #blobs fields. virtual ~Layer(); }; /** @brief This class allows to create and manipulate comprehensive artificial neural networks. * * Neural network is presented as directed acyclic graph (DAG), where vertices are Layer instances, * and edges specify relationships between layers inputs and outputs. * * Each network layer has unique integer id and unique string name inside its network. * LayerId can store either layer name or layer id. * * This class supports reference counting of its instances, i. e. copies point to the same instance. */ class CV_EXPORTS_W_SIMPLE Net { public: CV_WRAP Net(); //!< Default constructor. CV_WRAP ~Net(); //!< Destructor frees the net only if there aren't references to the net anymore. /** @brief Create a network from Intel's Model Optimizer intermediate representation (IR). * @param[in] xml XML configuration file with network's topology. * @param[in] bin Binary file with trained weights. * Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine * backend. */ CV_WRAP static Net readFromModelOptimizer(const String& xml, const String& bin); /** @brief Create a network from Intel's Model Optimizer in-memory buffers with intermediate representation (IR). * @param[in] bufferModelConfig buffer with model's configuration. * @param[in] bufferWeights buffer with model's trained weights. * @returns Net object. */ CV_WRAP static Net readFromModelOptimizer(const std::vector<uchar>& bufferModelConfig, const std::vector<uchar>& bufferWeights); /** @brief Create a network from Intel's Model Optimizer in-memory buffers with intermediate representation (IR). * @param[in] bufferModelConfigPtr buffer pointer of model's configuration. * @param[in] bufferModelConfigSize buffer size of model's configuration. * @param[in] bufferWeightsPtr buffer pointer of model's trained weights. * @param[in] bufferWeightsSize buffer size of model's trained weights. * @returns Net object. */ static Net readFromModelOptimizer(const uchar* bufferModelConfigPtr, size_t bufferModelConfigSize, const uchar* bufferWeightsPtr, size_t bufferWeightsSize); /** Returns true if there are no layers in the network. */ CV_WRAP bool empty() const; /** @brief Dump net to String * @returns String with structure, hyperparameters, backend, target and fusion * Call method after setInput(). To see correct backend, target and fusion run after forward(). */ CV_WRAP String dump(); /** @brief Dump net structure, hyperparameters, backend, target and fusion to dot file * @param path path to output file with .dot extension * @see dump() */ CV_WRAP void dumpToFile(const String& path); /** @brief Adds new layer to the net. * @param name unique name of the adding layer. * @param type typename of the adding layer (type must be registered in LayerRegister). * @param dtype datatype of output blobs. * @param params parameters which will be used to initialize the creating layer. * @returns unique identifier of created layer, or -1 if a failure will happen. */ int addLayer(const String &name, const String &type, const int &dtype, LayerParams &params); /** @overload Datatype of output blobs set to default CV_32F */ int addLayer(const String &name, const String &type, LayerParams &params); /** @brief Adds new layer and connects its first input to the first output of previously added layer. * @see addLayer() */ int addLayerToPrev(const String &name, const String &type, const int &dtype, LayerParams &params); /** @overload */ int addLayerToPrev(const String &name, const String &type, LayerParams &params); /** @brief Converts string name of the layer to the integer identifier. * @returns id of the layer, or -1 if the layer wasn't found. */ CV_WRAP int getLayerId(const String &layer) const; CV_WRAP std::vector<String> getLayerNames() const; /** @brief Container for strings and integers. * * @deprecated Use getLayerId() with int result. */ typedef DictValue LayerId; /** @brief Returns pointer to layer with specified id or name which the network use. */ CV_WRAP Ptr<Layer> getLayer(int layerId) const; /** @overload * @deprecated Use int getLayerId(const String &layer) */ CV_WRAP inline Ptr<Layer> getLayer(const String& layerName) const { return getLayer(getLayerId(layerName)); } /** @overload * @deprecated to be removed */ CV_WRAP Ptr<Layer> getLayer(const LayerId& layerId) const; /** @brief Returns pointers to input layers of specific layer. */ std::vector<Ptr<Layer> > getLayerInputs(int layerId) const; // FIXIT: CV_WRAP /** @brief Connects output of the first layer to input of the second layer. * @param outPin descriptor of the first layer output. * @param inpPin descriptor of the second layer input. * * Descriptors have the following template <DFN>&lt;layer_name&gt;[.input_number]</DFN>: * - the first part of the template <DFN>layer_name</DFN> is string name of the added layer. * If this part is empty then the network input pseudo layer will be used; * - the second optional part of the template <DFN>input_number</DFN> * is either number of the layer input, either label one. * If this part is omitted then the first layer input will be used. * * @see setNetInputs(), Layer::inputNameToIndex(), Layer::outputNameToIndex() */ CV_WRAP void connect(String outPin, String inpPin); /** @brief Connects #@p outNum output of the first layer to #@p inNum input of the second layer. * @param outLayerId identifier of the first layer * @param outNum number of the first layer output * @param inpLayerId identifier of the second layer * @param inpNum number of the second layer input */ void connect(int outLayerId, int outNum, int inpLayerId, int inpNum); /** @brief Sets outputs names of the network input pseudo layer. * * Each net always has special own the network input pseudo layer with id=0. * This layer stores the user blobs only and don't make any computations. * In fact, this layer provides the only way to pass user data into the network. * As any other layer, this layer can label its outputs and this function provides an easy way to do this. */ CV_WRAP void setInputsNames(const std::vector<String> &inputBlobNames); /** @brief Specify shape of network input. */ CV_WRAP void setInputShape(const String &inputName, const MatShape& shape); /** @brief Runs forward pass to compute output of layer with name @p outputName. * @param outputName name for layer which output is needed to get * @return blob for first output of specified layer. * @details By default runs forward pass for the whole network. */ CV_WRAP Mat forward(const String& outputName = String()); /** @brief Runs forward pass to compute output of layer with name @p outputName. * @param outputName name for layer which output is needed to get * @details By default runs forward pass for the whole network. * * This is an asynchronous version of forward(const String&). * dnn::DNN_BACKEND_INFERENCE_ENGINE backend is required. */ CV_WRAP AsyncArray forwardAsync(const String& outputName = String()); /** @brief Runs forward pass to compute output of layer with name @p outputName. * @param outputBlobs contains all output blobs for specified layer. * @param outputName name for layer which output is needed to get * @details If @p outputName is empty, runs forward pass for the whole network. */ CV_WRAP void forward(OutputArrayOfArrays outputBlobs, const String& outputName = String()); /** @brief Runs forward pass to compute outputs of layers listed in @p outBlobNames. * @param outputBlobs contains blobs for first outputs of specified layers. * @param outBlobNames names for layers which outputs are needed to get */ CV_WRAP void forward(OutputArrayOfArrays outputBlobs, const std::vector<String>& outBlobNames); /** @brief Runs forward pass to compute outputs of layers listed in @p outBlobNames. * @param outputBlobs contains all output blobs for each layer specified in @p outBlobNames. * @param outBlobNames names for layers which outputs are needed to get */ CV_WRAP_AS(forwardAndRetrieve) void forward(CV_OUT std::vector<std::vector<Mat> >& outputBlobs, const std::vector<String>& outBlobNames); /** @brief Returns a quantized Net from a floating-point Net. * @param calibData Calibration data to compute the quantization parameters. * @param inputsDtype Datatype of quantized net's inputs. Can be CV_32F or CV_8S. * @param outputsDtype Datatype of quantized net's outputs. Can be CV_32F or CV_8S. */ CV_WRAP Net quantize(InputArrayOfArrays calibData, int inputsDtype, int outputsDtype); /** @brief Returns input scale and zeropoint for a quantized Net. * @param scales output parameter for returning input scales. * @param zeropoints output parameter for returning input zeropoints. */ CV_WRAP void getInputDetails(CV_OUT std::vector<float>& scales, CV_OUT std::vector<int>& zeropoints) const; /** @brief Returns output scale and zeropoint for a quantized Net. * @param scales output parameter for returning output scales. * @param zeropoints output parameter for returning output zeropoints. */ CV_WRAP void getOutputDetails(CV_OUT std::vector<float>& scales, CV_OUT std::vector<int>& zeropoints) const; /** * @brief Compile Halide layers. * @param[in] scheduler Path to YAML file with scheduling directives. * @see setPreferableBackend * * Schedule layers that support Halide backend. Then compile them for * specific target. For layers that not represented in scheduling file * or if no manual scheduling used at all, automatic scheduling will be applied. */ CV_WRAP void setHalideScheduler(const String& scheduler); /** * @brief Ask network to use specific computation backend where it supported. * @param[in] backendId backend identifier. * @see Backend * * If OpenCV is compiled with Intel's Inference Engine library, DNN_BACKEND_DEFAULT * means DNN_BACKEND_INFERENCE_ENGINE. Otherwise it equals to DNN_BACKEND_OPENCV. */ CV_WRAP void setPreferableBackend(int backendId); /** * @brief Ask network to make computations on specific target device. * @param[in] targetId target identifier. * @see Target * * List of supported combinations backend / target: * | | DNN_BACKEND_OPENCV | DNN_BACKEND_INFERENCE_ENGINE | DNN_BACKEND_HALIDE | DNN_BACKEND_CUDA | * |------------------------|--------------------|------------------------------|--------------------|-------------------| * | DNN_TARGET_CPU | + | + | + | | * | DNN_TARGET_OPENCL | + | + | + | | * | DNN_TARGET_OPENCL_FP16 | + | + | | | * | DNN_TARGET_MYRIAD | | + | | | * | DNN_TARGET_FPGA | | + | | | * | DNN_TARGET_CUDA | | | | + | * | DNN_TARGET_CUDA_FP16 | | | | + | * | DNN_TARGET_HDDL | | + | | | */ CV_WRAP void setPreferableTarget(int targetId); /** @brief Sets the new input value for the network * @param blob A new blob. Should have CV_32F or CV_8U depth. * @param name A name of input layer. * @param scalefactor An optional normalization scale. * @param mean An optional mean subtraction values. * @see connect(String, String) to know format of the descriptor. * * If scale or mean values are specified, a final input blob is computed * as: * \f[input(n,c,h,w) = scalefactor \times (blob(n,c,h,w) - mean_c)\f] */ CV_WRAP void setInput(InputArray blob, const String& name = "", double scalefactor = 1.0, const Scalar& mean = Scalar()); /** @brief Sets the new value for the learned param of the layer. * @param layer name or id of the layer. * @param numParam index of the layer parameter in the Layer::blobs array. * @param blob the new value. * @see Layer::blobs * @note If shape of the new blob differs from the previous shape, * then the following forward pass may fail. */ CV_WRAP void setParam(int layer, int numParam, const Mat &blob); CV_WRAP inline void setParam(const String& layerName, int numParam, const Mat &blob) { return setParam(getLayerId(layerName), numParam, blob); } /** @brief Returns parameter blob of the layer. * @param layer name or id of the layer. * @param numParam index of the layer parameter in the Layer::blobs array. * @see Layer::blobs */ CV_WRAP Mat getParam(int layer, int numParam = 0) const; CV_WRAP inline Mat getParam(const String& layerName, int numParam = 0) const { return getParam(getLayerId(layerName), numParam); } /** @brief Returns indexes of layers with unconnected outputs. */ CV_WRAP std::vector<int> getUnconnectedOutLayers() const; /** @brief Returns names of layers with unconnected outputs. */ CV_WRAP std::vector<String> getUnconnectedOutLayersNames() const; /** @brief Returns input and output shapes for all layers in loaded model; * preliminary inferencing isn't necessary. * @param netInputShapes shapes for all input blobs in net input layer. * @param layersIds output parameter for layer IDs. * @param inLayersShapes output parameter for input layers shapes; * order is the same as in layersIds * @param outLayersShapes output parameter for output layers shapes; * order is the same as in layersIds */ CV_WRAP void getLayersShapes(const std::vector<MatShape>& netInputShapes, CV_OUT std::vector<int>& layersIds, CV_OUT std::vector<std::vector<MatShape> >& inLayersShapes, CV_OUT std::vector<std::vector<MatShape> >& outLayersShapes) const; /** @overload */ CV_WRAP void getLayersShapes(const MatShape& netInputShape, CV_OUT std::vector<int>& layersIds, CV_OUT std::vector<std::vector<MatShape> >& inLayersShapes, CV_OUT std::vector<std::vector<MatShape> >& outLayersShapes) const; /** @brief Returns input and output shapes for layer with specified * id in loaded model; preliminary inferencing isn't necessary. * @param netInputShape shape input blob in net input layer. * @param layerId id for layer. * @param inLayerShapes output parameter for input layers shapes; * order is the same as in layersIds * @param outLayerShapes output parameter for output layers shapes; * order is the same as in layersIds */ void getLayerShapes(const MatShape& netInputShape, const int layerId, CV_OUT std::vector<MatShape>& inLayerShapes, CV_OUT std::vector<MatShape>& outLayerShapes) const; // FIXIT: CV_WRAP /** @overload */ void getLayerShapes(const std::vector<MatShape>& netInputShapes, const int layerId, CV_OUT std::vector<MatShape>& inLayerShapes, CV_OUT std::vector<MatShape>& outLayerShapes) const; // FIXIT: CV_WRAP /** @brief Computes FLOP for whole loaded model with specified input shapes. * @param netInputShapes vector of shapes for all net inputs. * @returns computed FLOP. */ CV_WRAP int64 getFLOPS(const std::vector<MatShape>& netInputShapes) const; /** @overload */ CV_WRAP int64 getFLOPS(const MatShape& netInputShape) const; /** @overload */ CV_WRAP int64 getFLOPS(const int layerId, const std::vector<MatShape>& netInputShapes) const; /** @overload */ CV_WRAP int64 getFLOPS(const int layerId, const MatShape& netInputShape) const; /** @brief Returns list of types for layer used in model. * @param layersTypes output parameter for returning types. */ CV_WRAP void getLayerTypes(CV_OUT std::vector<String>& layersTypes) const; /** @brief Returns count of layers of specified type. * @param layerType type. * @returns count of layers */ CV_WRAP int getLayersCount(const String& layerType) const; /** @brief Computes bytes number which are required to store * all weights and intermediate blobs for model. * @param netInputShapes vector of shapes for all net inputs. * @param weights output parameter to store resulting bytes for weights. * @param blobs output parameter to store resulting bytes for intermediate blobs. */ void getMemoryConsumption(const std::vector<MatShape>& netInputShapes, CV_OUT size_t& weights, CV_OUT size_t& blobs) const; // FIXIT: CV_WRAP /** @overload */ CV_WRAP void getMemoryConsumption(const MatShape& netInputShape, CV_OUT size_t& weights, CV_OUT size_t& blobs) const; /** @overload */ CV_WRAP void getMemoryConsumption(const int layerId, const std::vector<MatShape>& netInputShapes, CV_OUT size_t& weights, CV_OUT size_t& blobs) const; /** @overload */ CV_WRAP void getMemoryConsumption(const int layerId, const MatShape& netInputShape, CV_OUT size_t& weights, CV_OUT size_t& blobs) const; /** @brief Computes bytes number which are required to store * all weights and intermediate blobs for each layer. * @param netInputShapes vector of shapes for all net inputs. * @param layerIds output vector to save layer IDs. * @param weights output parameter to store resulting bytes for weights. * @param blobs output parameter to store resulting bytes for intermediate blobs. */ void getMemoryConsumption(const std::vector<MatShape>& netInputShapes, CV_OUT std::vector<int>& layerIds, CV_OUT std::vector<size_t>& weights, CV_OUT std::vector<size_t>& blobs) const; // FIXIT: CV_WRAP /** @overload */ void getMemoryConsumption(const MatShape& netInputShape, CV_OUT std::vector<int>& layerIds, CV_OUT std::vector<size_t>& weights, CV_OUT std::vector<size_t>& blobs) const; // FIXIT: CV_WRAP /** @brief Enables or disables layer fusion in the network. * @param fusion true to enable the fusion, false to disable. The fusion is enabled by default. */ CV_WRAP void enableFusion(bool fusion); /** @brief Returns overall time for inference and timings (in ticks) for layers. * * Indexes in returned vector correspond to layers ids. Some layers can be fused with others, * in this case zero ticks count will be return for that skipped layers. Supported by DNN_BACKEND_OPENCV on DNN_TARGET_CPU only. * * @param[out] timings vector for tick timings for all layers. * @return overall ticks for model inference. */ CV_WRAP int64 getPerfProfile(CV_OUT std::vector<double>& timings); private: struct Impl; Ptr<Impl> impl; }; /** @brief Reads a network model stored in <a href="https://pjreddie.com/darknet/">Darknet</a> model files. * @param cfgFile path to the .cfg file with text description of the network architecture. * @param darknetModel path to the .weights file with learned network. * @returns Network object that ready to do forward, throw an exception in failure cases. * @returns Net object. */ CV_EXPORTS_W Net readNetFromDarknet(const String &cfgFile, const String &darknetModel = String()); /** @brief Reads a network model stored in <a href="https://pjreddie.com/darknet/">Darknet</a> model files. * @param bufferCfg A buffer contains a content of .cfg file with text description of the network architecture. * @param bufferModel A buffer contains a content of .weights file with learned network. * @returns Net object. */ CV_EXPORTS_W Net readNetFromDarknet(const std::vector<uchar>& bufferCfg, const std::vector<uchar>& bufferModel = std::vector<uchar>()); /** @brief Reads a network model stored in <a href="https://pjreddie.com/darknet/">Darknet</a> model files. * @param bufferCfg A buffer contains a content of .cfg file with text description of the network architecture. * @param lenCfg Number of bytes to read from bufferCfg * @param bufferModel A buffer contains a content of .weights file with learned network. * @param lenModel Number of bytes to read from bufferModel * @returns Net object. */ CV_EXPORTS Net readNetFromDarknet(const char *bufferCfg, size_t lenCfg, const char *bufferModel = NULL, size_t lenModel = 0); /** @brief Reads a network model stored in <a href="http://caffe.berkeleyvision.org">Caffe</a> framework's format. * @param prototxt path to the .prototxt file with text description of the network architecture. * @param caffeModel path to the .caffemodel file with learned network. * @returns Net object. */ CV_EXPORTS_W Net readNetFromCaffe(const String &prototxt, const String &caffeModel = String()); /** @brief Reads a network model stored in Caffe model in memory. * @param bufferProto buffer containing the content of the .prototxt file * @param bufferModel buffer containing the content of the .caffemodel file * @returns Net object. */ CV_EXPORTS_W Net readNetFromCaffe(const std::vector<uchar>& bufferProto, const std::vector<uchar>& bufferModel = std::vector<uchar>()); /** @brief Reads a network model stored in Caffe model in memory. * @details This is an overloaded member function, provided for convenience. * It differs from the above function only in what argument(s) it accepts. * @param bufferProto buffer containing the content of the .prototxt file * @param lenProto length of bufferProto * @param bufferModel buffer containing the content of the .caffemodel file * @param lenModel length of bufferModel * @returns Net object. */ CV_EXPORTS Net readNetFromCaffe(const char *bufferProto, size_t lenProto, const char *bufferModel = NULL, size_t lenModel = 0); /** @brief Reads a network model stored in <a href="https://www.tensorflow.org/">TensorFlow</a> framework's format. * @param model path to the .pb file with binary protobuf description of the network architecture * @param config path to the .pbtxt file that contains text graph definition in protobuf format. * Resulting Net object is built by text graph using weights from a binary one that * let us make it more flexible. * @returns Net object. */ CV_EXPORTS_W Net readNetFromTensorflow(const String &model, const String &config = String()); /** @brief Reads a network model stored in <a href="https://www.tensorflow.org/">TensorFlow</a> framework's format. * @param bufferModel buffer containing the content of the pb file * @param bufferConfig buffer containing the content of the pbtxt file * @returns Net object. */ CV_EXPORTS_W Net readNetFromTensorflow(const std::vector<uchar>& bufferModel, const std::vector<uchar>& bufferConfig = std::vector<uchar>()); /** @brief Reads a network model stored in <a href="https://www.tensorflow.org/">TensorFlow</a> framework's format. * @details This is an overloaded member function, provided for convenience. * It differs from the above function only in what argument(s) it accepts. * @param bufferModel buffer containing the content of the pb file * @param lenModel length of bufferModel * @param bufferConfig buffer containing the content of the pbtxt file * @param lenConfig length of bufferConfig */ CV_EXPORTS Net readNetFromTensorflow(const char *bufferModel, size_t lenModel, const char *bufferConfig = NULL, size_t lenConfig = 0); /** * @brief Reads a network model stored in <a href="http://torch.ch">Torch7</a> framework's format. * @param model path to the file, dumped from Torch by using torch.save() function. * @param isBinary specifies whether the network was serialized in ascii mode or binary. * @param evaluate specifies testing phase of network. If true, it's similar to evaluate() method in Torch. * @returns Net object. * * @note Ascii mode of Torch serializer is more preferable, because binary mode extensively use `long` type of C language, * which has various bit-length on different systems. * * The loading file must contain serialized <a href="https://github.com/torch/nn/blob/master/doc/module.md">nn.Module</a> object * with importing network. Try to eliminate a custom objects from serialazing data to avoid importing errors. * * List of supported layers (i.e. object instances derived from Torch nn.Module class): * - nn.Sequential * - nn.Parallel * - nn.Concat * - nn.Linear * - nn.SpatialConvolution * - nn.SpatialMaxPooling, nn.SpatialAveragePooling * - nn.ReLU, nn.TanH, nn.Sigmoid * - nn.Reshape * - nn.SoftMax, nn.LogSoftMax * * Also some equivalents of these classes from cunn, cudnn, and fbcunn may be successfully imported. */ CV_EXPORTS_W Net readNetFromTorch(const String &model, bool isBinary = true, bool evaluate = true); /** * @brief Read deep learning network represented in one of the supported formats. * @param[in] model Binary file contains trained weights. The following file * extensions are expected for models from different frameworks: * * `*.caffemodel` (Caffe, http://caffe.berkeleyvision.org/) * * `*.pb` (TensorFlow, https://www.tensorflow.org/) * * `*.t7` | `*.net` (Torch, http://torch.ch/) * * `*.weights` (Darknet, https://pjreddie.com/darknet/) * * `*.bin` (DLDT, https://software.intel.com/openvino-toolkit) * * `*.onnx` (ONNX, https://onnx.ai/) * @param[in] config Text file contains network configuration. It could be a * file with the following extensions: * * `*.prototxt` (Caffe, http://caffe.berkeleyvision.org/) * * `*.pbtxt` (TensorFlow, https://www.tensorflow.org/) * * `*.cfg` (Darknet, https://pjreddie.com/darknet/) * * `*.xml` (DLDT, https://software.intel.com/openvino-toolkit) * @param[in] framework Explicit framework name tag to determine a format. * @returns Net object. * * This function automatically detects an origin framework of trained model * and calls an appropriate function such @ref readNetFromCaffe, @ref readNetFromTensorflow, * @ref readNetFromTorch or @ref readNetFromDarknet. An order of @p model and @p config * arguments does not matter. */ CV_EXPORTS_W Net readNet(const String& model, const String& config = "", const String& framework = ""); /** * @brief Read deep learning network represented in one of the supported formats. * @details This is an overloaded member function, provided for convenience. * It differs from the above function only in what argument(s) it accepts. * @param[in] framework Name of origin framework. * @param[in] bufferModel A buffer with a content of binary file with weights * @param[in] bufferConfig A buffer with a content of text file contains network configuration. * @returns Net object. */ CV_EXPORTS_W Net readNet(const String& framework, const std::vector<uchar>& bufferModel, const std::vector<uchar>& bufferConfig = std::vector<uchar>()); /** @brief Loads blob which was serialized as torch.Tensor object of Torch7 framework. * @warning This function has the same limitations as readNetFromTorch(). */ CV_EXPORTS_W Mat readTorchBlob(const String &filename, bool isBinary = true); /** @brief Load a network from Intel's Model Optimizer intermediate representation. * @param[in] xml XML configuration file with network's topology. * @param[in] bin Binary file with trained weights. * @returns Net object. * Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine * backend. */ CV_EXPORTS_W Net readNetFromModelOptimizer(const String &xml, const String &bin); /** @brief Load a network from Intel's Model Optimizer intermediate representation. * @param[in] bufferModelConfig Buffer contains XML configuration with network's topology. * @param[in] bufferWeights Buffer contains binary data with trained weights. * @returns Net object. * Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine * backend. */ CV_EXPORTS_W Net readNetFromModelOptimizer(const std::vector<uchar>& bufferModelConfig, const std::vector<uchar>& bufferWeights); /** @brief Load a network from Intel's Model Optimizer intermediate representation. * @param[in] bufferModelConfigPtr Pointer to buffer which contains XML configuration with network's topology. * @param[in] bufferModelConfigSize Binary size of XML configuration data. * @param[in] bufferWeightsPtr Pointer to buffer which contains binary data with trained weights. * @param[in] bufferWeightsSize Binary size of trained weights data. * @returns Net object. * Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine * backend. */ CV_EXPORTS Net readNetFromModelOptimizer(const uchar* bufferModelConfigPtr, size_t bufferModelConfigSize, const uchar* bufferWeightsPtr, size_t bufferWeightsSize); /** @brief Reads a network model <a href="https://onnx.ai/">ONNX</a>. * @param onnxFile path to the .onnx file with text description of the network architecture. * @returns Network object that ready to do forward, throw an exception in failure cases. */ CV_EXPORTS_W Net readNetFromONNX(const String &onnxFile); /** @brief Reads a network model from <a href="https://onnx.ai/">ONNX</a> * in-memory buffer. * @param buffer memory address of the first byte of the buffer. * @param sizeBuffer size of the buffer. * @returns Network object that ready to do forward, throw an exception * in failure cases. */ CV_EXPORTS Net readNetFromONNX(const char* buffer, size_t sizeBuffer); /** @brief Reads a network model from <a href="https://onnx.ai/">ONNX</a> * in-memory buffer. * @param buffer in-memory buffer that stores the ONNX model bytes. * @returns Network object that ready to do forward, throw an exception * in failure cases. */ CV_EXPORTS_W Net readNetFromONNX(const std::vector<uchar>& buffer); /** @brief Creates blob from .pb file. * @param path to the .pb file with input tensor. * @returns Mat. */ CV_EXPORTS_W Mat readTensorFromONNX(const String& path); /** @brief Creates 4-dimensional blob from image. Optionally resizes and crops @p image from center, * subtract @p mean values, scales values by @p scalefactor, swap Blue and Red channels. * @param image input image (with 1-, 3- or 4-channels). * @param size spatial size for output image * @param mean scalar with mean values which are subtracted from channels. Values are intended * to be in (mean-R, mean-G, mean-B) order if @p image has BGR ordering and @p swapRB is true. * @param scalefactor multiplier for @p image values. * @param swapRB flag which indicates that swap first and last channels * in 3-channel image is necessary. * @param crop flag which indicates whether image will be cropped after resize or not * @param ddepth Depth of output blob. Choose CV_32F or CV_8U. * @details if @p crop is true, input image is resized so one side after resize is equal to corresponding * dimension in @p size and another one is equal or larger. Then, crop from the center is performed. * If @p crop is false, direct resize without cropping and preserving aspect ratio is performed. * @returns 4-dimensional Mat with NCHW dimensions order. */ CV_EXPORTS_W Mat blobFromImage(InputArray image, double scalefactor=1.0, const Size& size = Size(), const Scalar& mean = Scalar(), bool swapRB=false, bool crop=false, int ddepth=CV_32F); /** @brief Creates 4-dimensional blob from image. * @details This is an overloaded member function, provided for convenience. * It differs from the above function only in what argument(s) it accepts. */ CV_EXPORTS void blobFromImage(InputArray image, OutputArray blob, double scalefactor=1.0, const Size& size = Size(), const Scalar& mean = Scalar(), bool swapRB=false, bool crop=false, int ddepth=CV_32F); /** @brief Creates 4-dimensional blob from series of images. Optionally resizes and * crops @p images from center, subtract @p mean values, scales values by @p scalefactor, * swap Blue and Red channels. * @param images input images (all with 1-, 3- or 4-channels). * @param size spatial size for output image * @param mean scalar with mean values which are subtracted from channels. Values are intended * to be in (mean-R, mean-G, mean-B) order if @p image has BGR ordering and @p swapRB is true. * @param scalefactor multiplier for @p images values. * @param swapRB flag which indicates that swap first and last channels * in 3-channel image is necessary. * @param crop flag which indicates whether image will be cropped after resize or not * @param ddepth Depth of output blob. Choose CV_32F or CV_8U. * @details if @p crop is true, input image is resized so one side after resize is equal to corresponding * dimension in @p size and another one is equal or larger. Then, crop from the center is performed. * If @p crop is false, direct resize without cropping and preserving aspect ratio is performed. * @returns 4-dimensional Mat with NCHW dimensions order. */ CV_EXPORTS_W Mat blobFromImages(InputArrayOfArrays images, double scalefactor=1.0, Size size = Size(), const Scalar& mean = Scalar(), bool swapRB=false, bool crop=false, int ddepth=CV_32F); /** @brief Creates 4-dimensional blob from series of images. * @details This is an overloaded member function, provided for convenience. * It differs from the above function only in what argument(s) it accepts. */ CV_EXPORTS void blobFromImages(InputArrayOfArrays images, OutputArray blob, double scalefactor=1.0, Size size = Size(), const Scalar& mean = Scalar(), bool swapRB=false, bool crop=false, int ddepth=CV_32F); /** @brief Parse a 4D blob and output the images it contains as 2D arrays through a simpler data structure * (std::vector<cv::Mat>). * @param[in] blob_ 4 dimensional array (images, channels, height, width) in floating point precision (CV_32F) from * which you would like to extract the images. * @param[out] images_ array of 2D Mat containing the images extracted from the blob in floating point precision * (CV_32F). They are non normalized neither mean added. The number of returned images equals the first dimension * of the blob (batch size). Every image has a number of channels equals to the second dimension of the blob (depth). */ CV_EXPORTS_W void imagesFromBlob(const cv::Mat& blob_, OutputArrayOfArrays images_); /** @brief Convert all weights of Caffe network to half precision floating point. * @param src Path to origin model from Caffe framework contains single * precision floating point weights (usually has `.caffemodel` extension). * @param dst Path to destination model with updated weights. * @param layersTypes Set of layers types which parameters will be converted. * By default, converts only Convolutional and Fully-Connected layers' * weights. * * @note Shrinked model has no origin float32 weights so it can't be used * in origin Caffe framework anymore. However the structure of data * is taken from NVidia's Caffe fork: https://github.com/NVIDIA/caffe. * So the resulting model may be used there. */ CV_EXPORTS_W void shrinkCaffeModel(const String& src, const String& dst, const std::vector<String>& layersTypes = std::vector<String>()); /** @brief Create a text representation for a binary network stored in protocol buffer format. * @param[in] model A path to binary network. * @param[in] output A path to output text file to be created. * * @note To reduce output file size, trained weights are not included. */ CV_EXPORTS_W void writeTextGraph(const String& model, const String& output); /** @brief Performs non maximum suppression given boxes and corresponding scores. * @param bboxes a set of bounding boxes to apply NMS. * @param scores a set of corresponding confidences. * @param score_threshold a threshold used to filter boxes by score. * @param nms_threshold a threshold used in non maximum suppression. * @param indices the kept indices of bboxes after NMS. * @param eta a coefficient in adaptive threshold formula: \f$nms\_threshold_{i+1}=eta\cdot nms\_threshold_i\f$. * @param top_k if `>0`, keep at most @p top_k picked indices. */ CV_EXPORTS void NMSBoxes(const std::vector<Rect>& bboxes, const std::vector<float>& scores, const float score_threshold, const float nms_threshold, CV_OUT std::vector<int>& indices, const float eta = 1.f, const int top_k = 0); CV_EXPORTS_W void NMSBoxes(const std::vector<Rect2d>& bboxes, const std::vector<float>& scores, const float score_threshold, const float nms_threshold, CV_OUT std::vector<int>& indices, const float eta = 1.f, const int top_k = 0); CV_EXPORTS_AS(NMSBoxesRotated) void NMSBoxes(const std::vector<RotatedRect>& bboxes, const std::vector<float>& scores, const float score_threshold, const float nms_threshold, CV_OUT std::vector<int>& indices, const float eta = 1.f, const int top_k = 0); /** * @brief Enum of Soft NMS methods. * @see softNMSBoxes */ enum class SoftNMSMethod { SOFTNMS_LINEAR = 1, SOFTNMS_GAUSSIAN = 2 }; /** @brief Performs soft non maximum suppression given boxes and corresponding scores. * Reference: https://arxiv.org/abs/1704.04503 * @param bboxes a set of bounding boxes to apply Soft NMS. * @param scores a set of corresponding confidences. * @param updated_scores a set of corresponding updated confidences. * @param score_threshold a threshold used to filter boxes by score. * @param nms_threshold a threshold used in non maximum suppression. * @param indices the kept indices of bboxes after NMS. * @param top_k keep at most @p top_k picked indices. * @param sigma parameter of Gaussian weighting. * @param method Gaussian or linear. * @see SoftNMSMethod */ CV_EXPORTS_W void softNMSBoxes(const std::vector<Rect>& bboxes, const std::vector<float>& scores, CV_OUT std::vector<float>& updated_scores, const float score_threshold, const float nms_threshold, CV_OUT std::vector<int>& indices, size_t top_k = 0, const float sigma = 0.5, SoftNMSMethod method = SoftNMSMethod::SOFTNMS_GAUSSIAN); /** @brief This class is presented high-level API for neural networks. * * Model allows to set params for preprocessing input image. * Model creates net from file with trained weights and config, * sets preprocessing input and runs forward pass. */ class CV_EXPORTS_W_SIMPLE Model { public: CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) Model(); Model(const Model&) = default; Model(Model&&) = default; Model& operator=(const Model&) = default; Model& operator=(Model&&) = default; /** * @brief Create model from deep learning network represented in one of the supported formats. * An order of @p model and @p config arguments does not matter. * @param[in] model Binary file contains trained weights. * @param[in] config Text file contains network configuration. */ CV_WRAP Model(const String& model, const String& config = ""); /** * @brief Create model from deep learning network. * @param[in] network Net object. */ CV_WRAP Model(const Net& network); /** @brief Set input size for frame. * @param[in] size New input size. * @note If shape of the new blob less than 0, then frame size not change. */ CV_WRAP Model& setInputSize(const Size& size); /** @overload * @param[in] width New input width. * @param[in] height New input height. */ CV_WRAP inline Model& setInputSize(int width, int height) { return setInputSize(Size(width, height)); } /** @brief Set mean value for frame. * @param[in] mean Scalar with mean values which are subtracted from channels. */ CV_WRAP Model& setInputMean(const Scalar& mean); /** @brief Set scalefactor value for frame. * @param[in] scale Multiplier for frame values. */ CV_WRAP Model& setInputScale(double scale); /** @brief Set flag crop for frame. * @param[in] crop Flag which indicates whether image will be cropped after resize or not. */ CV_WRAP Model& setInputCrop(bool crop); /** @brief Set flag swapRB for frame. * @param[in] swapRB Flag which indicates that swap first and last channels. */ CV_WRAP Model& setInputSwapRB(bool swapRB); /** @brief Set preprocessing parameters for frame. * @param[in] size New input size. * @param[in] mean Scalar with mean values which are subtracted from channels. * @param[in] scale Multiplier for frame values. * @param[in] swapRB Flag which indicates that swap first and last channels. * @param[in] crop Flag which indicates whether image will be cropped after resize or not. * blob(n, c, y, x) = scale * resize( frame(y, x, c) ) - mean(c) ) */ CV_WRAP void setInputParams(double scale = 1.0, const Size& size = Size(), const Scalar& mean = Scalar(), bool swapRB = false, bool crop = false); /** @brief Given the @p input frame, create input blob, run net and return the output @p blobs. * @param[in] frame The input image. * @param[out] outs Allocated output blobs, which will store results of the computation. */ CV_WRAP void predict(InputArray frame, OutputArrayOfArrays outs) const; // ============================== Net proxy methods ============================== // Never expose methods with network implementation details, like: // - addLayer, addLayerToPrev, connect, setInputsNames, setInputShape, setParam, getParam // - getLayer*, getUnconnectedOutLayers, getUnconnectedOutLayersNames, getLayersShapes // - forward* methods, setInput /// @sa Net::setPreferableBackend CV_WRAP Model& setPreferableBackend(dnn::Backend backendId); /// @sa Net::setPreferableTarget CV_WRAP Model& setPreferableTarget(dnn::Target targetId); CV_DEPRECATED_EXTERNAL operator Net&() const { return getNetwork_(); } //protected: - internal/tests usage only Net& getNetwork_() const; inline Net& getNetwork_() { return const_cast<const Model*>(this)->getNetwork_(); } struct Impl; inline Impl* getImpl() const { return impl.get(); } inline Impl& getImplRef() const { CV_DbgAssert(impl); return *impl.get(); } protected: Ptr<Impl> impl; }; /** @brief This class represents high-level API for classification models. * * ClassificationModel allows to set params for preprocessing input image. * ClassificationModel creates net from file with trained weights and config, * sets preprocessing input, runs forward pass and return top-1 prediction. */ class CV_EXPORTS_W_SIMPLE ClassificationModel : public Model { public: /** * @brief Create classification model from network represented in one of the supported formats. * An order of @p model and @p config arguments does not matter. * @param[in] model Binary file contains trained weights. * @param[in] config Text file contains network configuration. */ CV_WRAP ClassificationModel(const String& model, const String& config = ""); /** * @brief Create model from deep learning network. * @param[in] network Net object. */ CV_WRAP ClassificationModel(const Net& network); /** @brief Given the @p input frame, create input blob, run net and return top-1 prediction. * @param[in] frame The input image. */ std::pair<int, float> classify(InputArray frame); /** @overload */ CV_WRAP void classify(InputArray frame, CV_OUT int& classId, CV_OUT float& conf); }; /** @brief This class represents high-level API for keypoints models * * KeypointsModel allows to set params for preprocessing input image. * KeypointsModel creates net from file with trained weights and config, * sets preprocessing input, runs forward pass and returns the x and y coordinates of each detected keypoint */ class CV_EXPORTS_W_SIMPLE KeypointsModel: public Model { public: /** * @brief Create keypoints model from network represented in one of the supported formats. * An order of @p model and @p config arguments does not matter. * @param[in] model Binary file contains trained weights. * @param[in] config Text file contains network configuration. */ CV_WRAP KeypointsModel(const String& model, const String& config = ""); /** * @brief Create model from deep learning network. * @param[in] network Net object. */ CV_WRAP KeypointsModel(const Net& network); /** @brief Given the @p input frame, create input blob, run net * @param[in] frame The input image. * @param thresh minimum confidence threshold to select a keypoint * @returns a vector holding the x and y coordinates of each detected keypoint * */ CV_WRAP std::vector<Point2f> estimate(InputArray frame, float thresh=0.5); }; /** @brief This class represents high-level API for segmentation models * * SegmentationModel allows to set params for preprocessing input image. * SegmentationModel creates net from file with trained weights and config, * sets preprocessing input, runs forward pass and returns the class prediction for each pixel. */ class CV_EXPORTS_W_SIMPLE SegmentationModel: public Model { public: /** * @brief Create segmentation model from network represented in one of the supported formats. * An order of @p model and @p config arguments does not matter. * @param[in] model Binary file contains trained weights. * @param[in] config Text file contains network configuration. */ CV_WRAP SegmentationModel(const String& model, const String& config = ""); /** * @brief Create model from deep learning network. * @param[in] network Net object. */ CV_WRAP SegmentationModel(const Net& network); /** @brief Given the @p input frame, create input blob, run net * @param[in] frame The input image. * @param[out] mask Allocated class prediction for each pixel */ CV_WRAP void segment(InputArray frame, OutputArray mask); }; /** @brief This class represents high-level API for object detection networks. * * DetectionModel allows to set params for preprocessing input image. * DetectionModel creates net from file with trained weights and config, * sets preprocessing input, runs forward pass and return result detections. * For DetectionModel SSD, Faster R-CNN, YOLO topologies are supported. */ class CV_EXPORTS_W_SIMPLE DetectionModel : public Model { public: /** * @brief Create detection model from network represented in one of the supported formats. * An order of @p model and @p config arguments does not matter. * @param[in] model Binary file contains trained weights. * @param[in] config Text file contains network configuration. */ CV_WRAP DetectionModel(const String& model, const String& config = ""); /** * @brief Create model from deep learning network. * @param[in] network Net object. */ CV_WRAP DetectionModel(const Net& network); CV_DEPRECATED_EXTERNAL // avoid using in C++ code (need to fix bindings first) DetectionModel(); /** * @brief nmsAcrossClasses defaults to false, * such that when non max suppression is used during the detect() function, it will do so per-class. * This function allows you to toggle this behaviour. * @param[in] value The new value for nmsAcrossClasses */ CV_WRAP DetectionModel& setNmsAcrossClasses(bool value); /** * @brief Getter for nmsAcrossClasses. This variable defaults to false, * such that when non max suppression is used during the detect() function, it will do so only per-class */ CV_WRAP bool getNmsAcrossClasses(); /** @brief Given the @p input frame, create input blob, run net and return result detections. * @param[in] frame The input image. * @param[out] classIds Class indexes in result detection. * @param[out] confidences A set of corresponding confidences. * @param[out] boxes A set of bounding boxes. * @param[in] confThreshold A threshold used to filter boxes by confidences. * @param[in] nmsThreshold A threshold used in non maximum suppression. */ CV_WRAP void detect(InputArray frame, CV_OUT std::vector<int>& classIds, CV_OUT std::vector<float>& confidences, CV_OUT std::vector<Rect>& boxes, float confThreshold = 0.5f, float nmsThreshold = 0.0f); }; /** @brief This class represents high-level API for text recognition networks. * * TextRecognitionModel allows to set params for preprocessing input image. * TextRecognitionModel creates net from file with trained weights and config, * sets preprocessing input, runs forward pass and return recognition result. * For TextRecognitionModel, CRNN-CTC is supported. */ class CV_EXPORTS_W_SIMPLE TextRecognitionModel : public Model { public: CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) TextRecognitionModel(); /** * @brief Create Text Recognition model from deep learning network * Call setDecodeType() and setVocabulary() after constructor to initialize the decoding method * @param[in] network Net object */ CV_WRAP TextRecognitionModel(const Net& network); /** * @brief Create text recognition model from network represented in one of the supported formats * Call setDecodeType() and setVocabulary() after constructor to initialize the decoding method * @param[in] model Binary file contains trained weights * @param[in] config Text file contains network configuration */ CV_WRAP inline TextRecognitionModel(const std::string& model, const std::string& config = "") : TextRecognitionModel(readNet(model, config)) { /* nothing */ } /** * @brief Set the decoding method of translating the network output into string * @param[in] decodeType The decoding method of translating the network output into string, currently supported type: * - `"CTC-greedy"` greedy decoding for the output of CTC-based methods * - `"CTC-prefix-beam-search"` Prefix beam search decoding for the output of CTC-based methods */ CV_WRAP TextRecognitionModel& setDecodeType(const std::string& decodeType); /** * @brief Get the decoding method * @return the decoding method */ CV_WRAP const std::string& getDecodeType() const; /** * @brief Set the decoding method options for `"CTC-prefix-beam-search"` decode usage * @param[in] beamSize Beam size for search * @param[in] vocPruneSize Parameter to optimize big vocabulary search, * only take top @p vocPruneSize tokens in each search step, @p vocPruneSize <= 0 stands for disable this prune. */ CV_WRAP TextRecognitionModel& setDecodeOptsCTCPrefixBeamSearch(int beamSize, int vocPruneSize = 0); /** * @brief Set the vocabulary for recognition. * @param[in] vocabulary the associated vocabulary of the network. */ CV_WRAP TextRecognitionModel& setVocabulary(const std::vector<std::string>& vocabulary); /** * @brief Get the vocabulary for recognition. * @return vocabulary the associated vocabulary */ CV_WRAP const std::vector<std::string>& getVocabulary() const; /** * @brief Given the @p input frame, create input blob, run net and return recognition result * @param[in] frame The input image * @return The text recognition result */ CV_WRAP std::string recognize(InputArray frame) const; /** * @brief Given the @p input frame, create input blob, run net and return recognition result * @param[in] frame The input image * @param[in] roiRects List of text detection regions of interest (cv::Rect, CV_32SC4). ROIs is be cropped as the network inputs * @param[out] results A set of text recognition results. */ CV_WRAP void recognize(InputArray frame, InputArrayOfArrays roiRects, CV_OUT std::vector<std::string>& results) const; }; /** @brief Base class for text detection networks */ class CV_EXPORTS_W_SIMPLE TextDetectionModel : public Model { protected: CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) TextDetectionModel(); public: /** @brief Performs detection * * Given the input @p frame, prepare network input, run network inference, post-process network output and return result detections. * * Each result is quadrangle's 4 points in this order: * - bottom-left * - top-left * - top-right * - bottom-right * * Use cv::getPerspectiveTransform function to retrive image region without perspective transformations. * * @note If DL model doesn't support that kind of output then result may be derived from detectTextRectangles() output. * * @param[in] frame The input image * @param[out] detections array with detections' quadrangles (4 points per result) * @param[out] confidences array with detection confidences */ CV_WRAP void detect( InputArray frame, CV_OUT std::vector< std::vector<Point> >& detections, CV_OUT std::vector<float>& confidences ) const; /** @overload */ CV_WRAP void detect( InputArray frame, CV_OUT std::vector< std::vector<Point> >& detections ) const; /** @brief Performs detection * * Given the input @p frame, prepare network input, run network inference, post-process network output and return result detections. * * Each result is rotated rectangle. * * @note Result may be inaccurate in case of strong perspective transformations. * * @param[in] frame the input image * @param[out] detections array with detections' RotationRect results * @param[out] confidences array with detection confidences */ CV_WRAP void detectTextRectangles( InputArray frame, CV_OUT std::vector<cv::RotatedRect>& detections, CV_OUT std::vector<float>& confidences ) const; /** @overload */ CV_WRAP void detectTextRectangles( InputArray frame, CV_OUT std::vector<cv::RotatedRect>& detections ) const; }; /** @brief This class represents high-level API for text detection DL networks compatible with EAST model. * * Configurable parameters: * - (float) confThreshold - used to filter boxes by confidences, default: 0.5f * - (float) nmsThreshold - used in non maximum suppression, default: 0.0f */ class CV_EXPORTS_W_SIMPLE TextDetectionModel_EAST : public TextDetectionModel { public: CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) TextDetectionModel_EAST(); /** * @brief Create text detection algorithm from deep learning network * @param[in] network Net object */ CV_WRAP TextDetectionModel_EAST(const Net& network); /** * @brief Create text detection model from network represented in one of the supported formats. * An order of @p model and @p config arguments does not matter. * @param[in] model Binary file contains trained weights. * @param[in] config Text file contains network configuration. */ CV_WRAP inline TextDetectionModel_EAST(const std::string& model, const std::string& config = "") : TextDetectionModel_EAST(readNet(model, config)) { /* nothing */ } /** * @brief Set the detection confidence threshold * @param[in] confThreshold A threshold used to filter boxes by confidences */ CV_WRAP TextDetectionModel_EAST& setConfidenceThreshold(float confThreshold); /** * @brief Get the detection confidence threshold */ CV_WRAP float getConfidenceThreshold() const; /** * @brief Set the detection NMS filter threshold * @param[in] nmsThreshold A threshold used in non maximum suppression */ CV_WRAP TextDetectionModel_EAST& setNMSThreshold(float nmsThreshold); /** * @brief Get the detection confidence threshold */ CV_WRAP float getNMSThreshold() const; }; /** @brief This class represents high-level API for text detection DL networks compatible with DB model. * * Related publications: @cite liao2020real * Paper: https://arxiv.org/abs/1911.08947 * For more information about the hyper-parameters setting, please refer to https://github.com/MhLiao/DB * * Configurable parameters: * - (float) binaryThreshold - The threshold of the binary map. It is usually set to 0.3. * - (float) polygonThreshold - The threshold of text polygons. It is usually set to 0.5, 0.6, and 0.7. Default is 0.5f * - (double) unclipRatio - The unclip ratio of the detected text region, which determines the output size. It is usually set to 2.0. * - (int) maxCandidates - The max number of the output results. */ class CV_EXPORTS_W_SIMPLE TextDetectionModel_DB : public TextDetectionModel { public: CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) TextDetectionModel_DB(); /** * @brief Create text detection algorithm from deep learning network. * @param[in] network Net object. */ CV_WRAP TextDetectionModel_DB(const Net& network); /** * @brief Create text detection model from network represented in one of the supported formats. * An order of @p model and @p config arguments does not matter. * @param[in] model Binary file contains trained weights. * @param[in] config Text file contains network configuration. */ CV_WRAP inline TextDetectionModel_DB(const std::string& model, const std::string& config = "") : TextDetectionModel_DB(readNet(model, config)) { /* nothing */ } CV_WRAP TextDetectionModel_DB& setBinaryThreshold(float binaryThreshold); CV_WRAP float getBinaryThreshold() const; CV_WRAP TextDetectionModel_DB& setPolygonThreshold(float polygonThreshold); CV_WRAP float getPolygonThreshold() const; CV_WRAP TextDetectionModel_DB& setUnclipRatio(double unclipRatio); CV_WRAP double getUnclipRatio() const; CV_WRAP TextDetectionModel_DB& setMaxCandidates(int maxCandidates); CV_WRAP int getMaxCandidates() const; }; //! @} CV__DNN_INLINE_NS_END } } #include <opencv2/dnn/layer.hpp> #include <opencv2/dnn/dnn.inl.hpp> /// @deprecated Include this header directly from application. Automatic inclusion will be removed #include <opencv2/dnn/utils/inference_engine.hpp> #endif /* OPENCV_DNN_DNN_HPP */
49.212281
152
0.637886
Synkar
8b2ccb74852ea6ae8c292a1df0f9b3b34a0f725b
127,016
cpp
C++
src/lib/core/tests/TestCHIPTLV.cpp
simonlingoogle/connectedhomeip
47e8b60c0a903b385accde9f49635187646dd577
[ "Apache-2.0" ]
2
2021-05-21T23:15:07.000Z
2021-12-04T03:53:03.000Z
src/lib/core/tests/TestCHIPTLV.cpp
simonlingoogle/connectedhomeip
47e8b60c0a903b385accde9f49635187646dd577
[ "Apache-2.0" ]
null
null
null
src/lib/core/tests/TestCHIPTLV.cpp
simonlingoogle/connectedhomeip
47e8b60c0a903b385accde9f49635187646dd577
[ "Apache-2.0" ]
null
null
null
/* * * Copyright (c) 2020 Project CHIP Authors * Copyright (c) 2013-2017 Nest Labs, Inc. * 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. */ /** * @file * This file implements unit tests for the CHIP TLV implementation. * */ #include "TestCore.h" #include <nlbyteorder.h> #include <nlunit-test.h> #include <core/CHIPCircularTLVBuffer.h> #include <core/CHIPCore.h> #include <core/CHIPTLV.h> #include <core/CHIPTLVData.hpp> #include <core/CHIPTLVDebug.hpp> #include <core/CHIPTLVUtilities.hpp> #include <support/CodeUtils.h> #include <support/RandUtils.h> #include <support/TestUtils.h> #include <string.h> using namespace chip; using namespace chip::TLV; enum { TestProfile_1 = 0xAABBCCDD, TestProfile_2 = 0x11223344 }; // clang-format off static const char sLargeString [] = "START..." "!123456789ABCDEF@123456789ABCDEF#123456789ABCDEF$123456789ABCDEF%123456789ABCDEF^123456789ABCDEF&123456789ABCDEF*123456789ABCDEF" "01234567(9ABCDEF01234567)9ABCDEF01234567-9ABCDEF01234567=9ABCDEF01234567[9ABCDEF01234567]9ABCDEF01234567;9ABCDEF01234567'9ABCDEF" "...END"; // clang-format on void TestAndOpenContainer(nlTestSuite * inSuite, TLVReader & reader, TLVType type, uint64_t tag, TLVReader & containerReader) { NL_TEST_ASSERT(inSuite, reader.GetType() == type); NL_TEST_ASSERT(inSuite, reader.GetTag() == tag); NL_TEST_ASSERT(inSuite, reader.GetLength() == 0); CHIP_ERROR err = reader.OpenContainer(containerReader); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, containerReader.GetContainerType() == type); } template <class T> void TestAndEnterContainer(nlTestSuite * inSuite, T & t, TLVType type, uint64_t tag, TLVType & outerContainerType) { NL_TEST_ASSERT(inSuite, t.GetType() == type); NL_TEST_ASSERT(inSuite, t.GetTag() == tag); NL_TEST_ASSERT(inSuite, t.GetLength() == 0); TLVType expectedContainerType = t.GetContainerType(); CHIP_ERROR err = t.EnterContainer(outerContainerType); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, outerContainerType == expectedContainerType); NL_TEST_ASSERT(inSuite, t.GetContainerType() == type); } template <class T> void TestNext(nlTestSuite * inSuite, T & t) { CHIP_ERROR err = t.Next(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } void TestSkip(nlTestSuite * inSuite, TLVReader & reader) { CHIP_ERROR err = reader.Skip(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } void TestMove(nlTestSuite * inSuite, TLVUpdater & updater) { CHIP_ERROR err = updater.Move(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } template <class T> void TestEnd(nlTestSuite * inSuite, T & t) { CHIP_ERROR err; err = t.Next(); NL_TEST_ASSERT(inSuite, err == CHIP_END_OF_TLV); } void TestEndAndCloseContainer(nlTestSuite * inSuite, TLVReader & reader, TLVReader & containerReader) { CHIP_ERROR err; TestEnd<TLVReader>(inSuite, containerReader); err = reader.CloseContainer(containerReader); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } template <class T> void TestEndAndExitContainer(nlTestSuite * inSuite, T & t, TLVType outerContainerType) { CHIP_ERROR err; TestEnd<T>(inSuite, t); err = t.ExitContainer(outerContainerType); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, t.GetContainerType() == outerContainerType); } template <class S, class T> void TestGet(nlTestSuite * inSuite, S & s, TLVType type, uint64_t tag, T expectedVal) { NL_TEST_ASSERT(inSuite, s.GetType() == type); NL_TEST_ASSERT(inSuite, s.GetTag() == tag); NL_TEST_ASSERT(inSuite, s.GetLength() == 0); T val; CHIP_ERROR err = s.Get(val); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, val == expectedVal); } void ForEachElement(nlTestSuite * inSuite, TLVReader & reader, void * context, void (*cb)(nlTestSuite * inSuite, TLVReader & reader, void * context)) { CHIP_ERROR err; while (true) { err = reader.Next(); if (err == CHIP_END_OF_TLV) { return; } NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); if (cb != nullptr) { cb(inSuite, reader, context); } if (TLVTypeIsContainer(reader.GetType())) { TLVType outerContainerType; err = reader.EnterContainer(outerContainerType); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); ForEachElement(inSuite, reader, context, cb); err = reader.ExitContainer(outerContainerType); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } } } /** * context */ struct TestTLVContext { nlTestSuite * mSuite; int mEvictionCount; int mEvictedBytes; }; void TestNull(nlTestSuite * inSuite, TLVReader & reader, uint64_t tag) { NL_TEST_ASSERT(inSuite, reader.GetType() == kTLVType_Null); NL_TEST_ASSERT(inSuite, reader.GetTag() == tag); NL_TEST_ASSERT(inSuite, reader.GetLength() == 0); } void TestString(nlTestSuite * inSuite, TLVReader & reader, uint64_t tag, const char * expectedVal) { NL_TEST_ASSERT(inSuite, reader.GetType() == kTLVType_UTF8String); NL_TEST_ASSERT(inSuite, reader.GetTag() == tag); uint32_t expectedLen = strlen(expectedVal); NL_TEST_ASSERT(inSuite, reader.GetLength() == expectedLen); char * val = (char *) malloc(expectedLen + 1); CHIP_ERROR err = reader.GetString(val, expectedLen + 1); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, memcmp(val, expectedVal, expectedLen + 1) == 0); free(val); } void TestDupString(nlTestSuite * inSuite, TLVReader & reader, uint64_t tag, const char * expectedVal) { NL_TEST_ASSERT(inSuite, reader.GetType() == kTLVType_UTF8String); NL_TEST_ASSERT(inSuite, reader.GetTag() == tag); uint32_t expectedLen = strlen(expectedVal); NL_TEST_ASSERT(inSuite, reader.GetLength() == expectedLen); char * val = (char *) malloc(expectedLen + 1); CHIP_ERROR err = reader.DupString(val); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, memcmp(val, expectedVal, expectedLen + 1) == 0); free(val); } void TestDupBytes(nlTestSuite * inSuite, TLVReader & reader, uint64_t tag, const uint8_t * expectedVal, uint32_t expectedLen) { NL_TEST_ASSERT(inSuite, reader.GetType() == kTLVType_UTF8String); NL_TEST_ASSERT(inSuite, reader.GetTag() == tag); NL_TEST_ASSERT(inSuite, reader.GetLength() == expectedLen); uint8_t * val = (uint8_t *) malloc(expectedLen); CHIP_ERROR err = reader.DupBytes(val, expectedLen); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, memcmp(val, expectedVal, expectedLen) == 0); free(val); } void TestBufferContents(nlTestSuite * inSuite, PacketBuffer * buf, const uint8_t * expectedVal, uint32_t expectedLen) { while (buf != nullptr) { uint16_t len = buf->DataLength(); NL_TEST_ASSERT(inSuite, len <= expectedLen); NL_TEST_ASSERT(inSuite, memcmp(buf->Start(), expectedVal, len) == 0); expectedVal += len; expectedLen -= len; buf = buf->Next(); } NL_TEST_ASSERT(inSuite, expectedLen == 0); } // clang-format off static const uint8_t Encoding1[] = { 0xD5, 0xBB, 0xAA, 0xDD, 0xCC, 0x01, 0x00, 0xC9, 0xBB, 0xAA, 0xDD, 0xCC, 0x02, 0x00, 0x88, 0x02, 0x00, 0x36, 0x00, 0x00, 0x2A, 0x00, 0xEF, 0x02, 0xF0, 0x67, 0xFD, 0xFF, 0x07, 0x00, 0x90, 0x2F, 0x50, 0x09, 0x00, 0x00, 0x00, 0x15, 0x18, 0x17, 0xD4, 0xBB, 0xAA, 0xDD, 0xCC, 0x11, 0x00, 0xB4, 0xA0, 0xBB, 0x0D, 0x00, 0x14, 0xB5, 0x00, 0x28, 0x6B, 0xEE, 0x6D, 0x70, 0x11, 0x01, 0x00, 0x0E, 0x01, 0x53, 0x54, 0x41, 0x52, 0x54, 0x2E, 0x2E, 0x2E, 0x21, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x40, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x23, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x24, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x25, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x5E, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x26, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x2A, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x28, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x29, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x2D, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x3D, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x5B, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x5D, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x3B, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x27, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x2E, 0x2E, 0x2E, 0x45, 0x4E, 0x44, 0x18, 0x18, 0x18, 0xCC, 0xBB, 0xAA, 0xDD, 0xCC, 0x05, 0x00, 0x0E, 0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x61, 0x20, 0x74, 0x65, 0x73, 0x74, 0x8A, 0xFF, 0xFF, 0x33, 0x33, 0x8F, 0x41, 0xAB, 0x00, 0x00, 0x01, 0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0xE6, 0x31, 0x40, 0x18 }; // clang-format on // clang-format off static const uint8_t Encoding1_DataMacro [] = { CHIP_TLV_STRUCTURE(CHIP_TLV_TAG_FULLY_QUALIFIED_6Bytes(TestProfile_1, 1)), CHIP_TLV_BOOL(CHIP_TLV_TAG_FULLY_QUALIFIED_6Bytes(TestProfile_1, 2), true), CHIP_TLV_BOOL(CHIP_TLV_TAG_IMPLICIT_PROFILE_2Bytes(2), false), CHIP_TLV_ARRAY(CHIP_TLV_TAG_CONTEXT_SPECIFIC(0)), CHIP_TLV_INT8(CHIP_TLV_TAG_ANONYMOUS, 42), CHIP_TLV_INT8(CHIP_TLV_TAG_ANONYMOUS, -17), CHIP_TLV_INT32(CHIP_TLV_TAG_ANONYMOUS, -170000), CHIP_TLV_UINT64(CHIP_TLV_TAG_ANONYMOUS, 40000000000ULL), CHIP_TLV_STRUCTURE(CHIP_TLV_TAG_ANONYMOUS), CHIP_TLV_END_OF_CONTAINER, CHIP_TLV_PATH(CHIP_TLV_TAG_ANONYMOUS), CHIP_TLV_NULL(CHIP_TLV_TAG_FULLY_QUALIFIED_6Bytes(TestProfile_1, 17)), CHIP_TLV_NULL(CHIP_TLV_TAG_IMPLICIT_PROFILE_4Bytes(900000)), CHIP_TLV_NULL(CHIP_TLV_TAG_ANONYMOUS), CHIP_TLV_STRUCTURE(CHIP_TLV_TAG_IMPLICIT_PROFILE_4Bytes(4000000000ULL)), CHIP_TLV_UTF8_STRING_2ByteLength(CHIP_TLV_TAG_COMMON_PROFILE_4Bytes(70000), sizeof(sLargeString) - 1, 'S', 'T', 'A', 'R', 'T', '.', '.', '.', '!', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', '@', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', '#', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', '$', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', '%', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', '^', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', '&', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', '*', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', '0', '1', '2', '3', '4', '5', '6', '7', '(', '9', 'A', 'B', 'C', 'D', 'E', 'F', '0', '1', '2', '3', '4', '5', '6', '7', ')', '9', 'A', 'B', 'C', 'D', 'E', 'F', '0', '1', '2', '3', '4', '5', '6', '7', '-', '9', 'A', 'B', 'C', 'D', 'E', 'F', '0', '1', '2', '3', '4', '5', '6', '7', '=', '9', 'A', 'B', 'C', 'D', 'E', 'F', '0', '1', '2', '3', '4', '5', '6', '7', '[', '9', 'A', 'B', 'C', 'D', 'E', 'F', '0', '1', '2', '3', '4', '5', '6', '7', ']', '9', 'A', 'B', 'C', 'D', 'E', 'F', '0', '1', '2', '3', '4', '5', '6', '7', ';', '9', 'A', 'B', 'C', 'D', 'E', 'F', '0', '1', '2', '3', '4', '5', '6', '7', '\'', '9', 'A', 'B', 'C', 'D', 'E', 'F', '.', '.', '.', 'E', 'N', 'D'), CHIP_TLV_END_OF_CONTAINER, CHIP_TLV_END_OF_CONTAINER, CHIP_TLV_END_OF_CONTAINER, CHIP_TLV_UTF8_STRING_1ByteLength(CHIP_TLV_TAG_FULLY_QUALIFIED_6Bytes(TestProfile_1, 5), sizeof("This is a test") - 1, 'T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't'), CHIP_TLV_FLOAT32(CHIP_TLV_TAG_IMPLICIT_PROFILE_2Bytes(65535), 0x33, 0x33, 0x8f, 0x41), // (float)17.9 CHIP_TLV_FLOAT64(CHIP_TLV_TAG_IMPLICIT_PROFILE_4Bytes(65536), 0x66, 0x66, 0x66, 0x66, 0x66, 0xE6, 0x31, 0x40), // (double)17.9 CHIP_TLV_END_OF_CONTAINER }; // clang-format on void WriteEncoding1(nlTestSuite * inSuite, TLVWriter & writer) { CHIP_ERROR err; TLVWriter writer2; err = writer.OpenContainer(ProfileTag(TestProfile_1, 1), kTLVType_Structure, writer2); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.PutBoolean(ProfileTag(TestProfile_1, 2), true); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.PutBoolean(ProfileTag(TestProfile_2, 2), false); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); { TLVWriter writer3; err = writer2.OpenContainer(ContextTag(0), kTLVType_Array, writer3); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // TODO(#1306): expand coverage of inttype encoding tests. err = writer3.Put(AnonymousTag, static_cast<int32_t>(42)); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer3.Put(AnonymousTag, static_cast<int32_t>(-17)); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer3.Put(AnonymousTag, static_cast<int32_t>(-170000)); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer3.Put(AnonymousTag, static_cast<uint64_t>(40000000000ULL)); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); { TLVWriter writer4; err = writer3.OpenContainer(AnonymousTag, kTLVType_Structure, writer4); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer3.CloseContainer(writer4); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } { TLVWriter writer5; err = writer3.OpenContainer(AnonymousTag, kTLVType_Path, writer5); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer5.PutNull(ProfileTag(TestProfile_1, 17)); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer5.PutNull(ProfileTag(TestProfile_2, 900000)); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer5.PutNull(AnonymousTag); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); { TLVType outerContainerType; err = writer5.StartContainer(ProfileTag(TestProfile_2, 4000000000ULL), kTLVType_Structure, outerContainerType); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer5.PutString(CommonTag(70000), sLargeString); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer5.EndContainer(outerContainerType); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } err = writer3.CloseContainer(writer5); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } err = writer2.CloseContainer(writer3); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } err = writer2.PutString(ProfileTag(TestProfile_1, 5), "This is a test"); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.Put(ProfileTag(TestProfile_2, 65535), (float) 17.9); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.Put(ProfileTag(TestProfile_2, 65536), (double) 17.9); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.CloseContainer(writer2); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.Finalize(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } void WriteEmptyEncoding(nlTestSuite * inSuite, TLVWriter & writer) { CHIP_ERROR err; TLVWriter writer2; err = writer.OpenContainer(ProfileTag(TestProfile_1, 1), kTLVType_Structure, writer2); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); { TLVWriter writer3; err = writer2.OpenContainer(ProfileTag(TestProfile_1, 256), kTLVType_Array, writer3); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.CloseContainer(writer3); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } err = writer.CloseContainer(writer2); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.Finalize(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } void ReadEncoding1(nlTestSuite * inSuite, TLVReader & reader) { TestNext<TLVReader>(inSuite, reader); { TLVReader reader2; TestAndOpenContainer(inSuite, reader, kTLVType_Structure, ProfileTag(TestProfile_1, 1), reader2); TestNext<TLVReader>(inSuite, reader2); TestGet<TLVReader, bool>(inSuite, reader2, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); TestNext<TLVReader>(inSuite, reader2); TestGet<TLVReader, bool>(inSuite, reader2, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); TestNext<TLVReader>(inSuite, reader2); { TLVReader reader3; TestAndOpenContainer(inSuite, reader2, kTLVType_Array, ContextTag(0), reader3); TestNext<TLVReader>(inSuite, reader3); TestGet<TLVReader, int8_t>(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag, 42); TestGet<TLVReader, int16_t>(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag, 42); TestGet<TLVReader, int32_t>(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag, 42); TestGet<TLVReader, int64_t>(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag, 42); TestGet<TLVReader, uint8_t>(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag, 42); TestGet<TLVReader, uint16_t>(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag, 42); TestGet<TLVReader, uint32_t>(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag, 42); TestGet<TLVReader, uint64_t>(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag, 42); TestNext<TLVReader>(inSuite, reader3); TestGet<TLVReader, int8_t>(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag, -17); TestGet<TLVReader, int16_t>(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag, -17); TestGet<TLVReader, int32_t>(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag, -17); TestGet<TLVReader, int64_t>(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag, -17); TestNext<TLVReader>(inSuite, reader3); TestGet<TLVReader, int32_t>(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag, -170000); TestGet<TLVReader, int64_t>(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag, -170000); TestNext<TLVReader>(inSuite, reader3); TestGet<TLVReader, int64_t>(inSuite, reader3, kTLVType_UnsignedInteger, AnonymousTag, 40000000000ULL); TestGet<TLVReader, uint64_t>(inSuite, reader3, kTLVType_UnsignedInteger, AnonymousTag, 40000000000ULL); TestNext<TLVReader>(inSuite, reader3); { TLVReader reader4; TestAndOpenContainer(inSuite, reader3, kTLVType_Structure, AnonymousTag, reader4); TestEndAndCloseContainer(inSuite, reader3, reader4); } TestNext<TLVReader>(inSuite, reader3); { TLVReader reader5; TestAndOpenContainer(inSuite, reader3, kTLVType_Path, AnonymousTag, reader5); TestNext<TLVReader>(inSuite, reader5); TestNull(inSuite, reader5, ProfileTag(TestProfile_1, 17)); TestNext<TLVReader>(inSuite, reader5); TestNull(inSuite, reader5, ProfileTag(TestProfile_2, 900000)); TestNext<TLVReader>(inSuite, reader5); TestNull(inSuite, reader5, AnonymousTag); TestNext<TLVReader>(inSuite, reader5); { TLVType outerContainerType; TestAndEnterContainer<TLVReader>(inSuite, reader5, kTLVType_Structure, ProfileTag(TestProfile_2, 4000000000ULL), outerContainerType); TestNext<TLVReader>(inSuite, reader5); TestString(inSuite, reader5, CommonTag(70000), sLargeString); TestEndAndExitContainer<TLVReader>(inSuite, reader5, outerContainerType); } TestEndAndCloseContainer(inSuite, reader3, reader5); } TestEndAndCloseContainer(inSuite, reader2, reader3); } TestNext<TLVReader>(inSuite, reader2); TestString(inSuite, reader2, ProfileTag(TestProfile_1, 5), "This is a test"); TestNext<TLVReader>(inSuite, reader2); TestGet<TLVReader, double>(inSuite, reader2, kTLVType_FloatingPointNumber, ProfileTag(TestProfile_2, 65535), (float) 17.9); TestNext<TLVReader>(inSuite, reader2); TestGet<TLVReader, double>(inSuite, reader2, kTLVType_FloatingPointNumber, ProfileTag(TestProfile_2, 65536), (double) 17.9); TestEndAndCloseContainer(inSuite, reader, reader2); } TestEnd<TLVReader>(inSuite, reader); } void WriteEncoding2(nlTestSuite * inSuite, TLVWriter & writer) { CHIP_ERROR err; { // Container 1 TLVWriter writer1; err = writer.OpenContainer(ProfileTag(TestProfile_1, 1), kTLVType_Structure, writer1); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer1.PutBoolean(ProfileTag(TestProfile_1, 2), true); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer1.PutBoolean(ProfileTag(TestProfile_2, 2), false); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.CloseContainer(writer1); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } { // Container 2 TLVWriter writer1; err = writer.OpenContainer(ProfileTag(TestProfile_2, 1), kTLVType_Structure, writer1); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer1.PutBoolean(ProfileTag(TestProfile_2, 2), false); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer1.PutBoolean(ProfileTag(TestProfile_1, 2), true); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.CloseContainer(writer1); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } err = writer.Finalize(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } void WriteEncoding3(nlTestSuite * inSuite, TLVWriter & writer) { CHIP_ERROR err; { // Container 1 TLVWriter writer1; err = writer.OpenContainer(ProfileTag(TestProfile_1, 1), kTLVType_Structure, writer1); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer1.PutBoolean(ProfileTag(TestProfile_2, 2), false); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.CloseContainer(writer1); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } err = writer.Finalize(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } void ReadEncoding3(nlTestSuite * inSuite, TLVReader & reader) { TLVReader reader2; TestAndOpenContainer(inSuite, reader, kTLVType_Structure, ProfileTag(TestProfile_1, 1), reader2); TestNext<TLVReader>(inSuite, reader2); TestGet<TLVReader, bool>(inSuite, reader2, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); TestEndAndCloseContainer(inSuite, reader, reader2); } // clang-format off static const uint8_t Encoding5_DataMacro [] = { CHIP_TLV_STRUCTURE(CHIP_TLV_TAG_FULLY_QUALIFIED_6Bytes(TestProfile_1, 1)), CHIP_TLV_BOOL(CHIP_TLV_TAG_FULLY_QUALIFIED_6Bytes(TestProfile_1, 2), true), CHIP_TLV_BOOL(CHIP_TLV_TAG_IMPLICIT_PROFILE_2Bytes(2), false), CHIP_TLV_BOOL(CHIP_TLV_TAG_FULLY_QUALIFIED_6Bytes(TestProfile_1, 2), false), CHIP_TLV_BOOL(CHIP_TLV_TAG_IMPLICIT_PROFILE_2Bytes(2), true), CHIP_TLV_STRUCTURE(CHIP_TLV_TAG_FULLY_QUALIFIED_6Bytes(TestProfile_1, 1)), CHIP_TLV_BOOL(CHIP_TLV_TAG_FULLY_QUALIFIED_6Bytes(TestProfile_1, 2), true), CHIP_TLV_BOOL(CHIP_TLV_TAG_IMPLICIT_PROFILE_2Bytes(2), false), CHIP_TLV_END_OF_CONTAINER, CHIP_TLV_STRUCTURE(CHIP_TLV_TAG_IMPLICIT_PROFILE_2Bytes(1)), CHIP_TLV_BOOL(CHIP_TLV_TAG_IMPLICIT_PROFILE_2Bytes(2), false), CHIP_TLV_BOOL(CHIP_TLV_TAG_FULLY_QUALIFIED_6Bytes(TestProfile_1, 2), true), CHIP_TLV_END_OF_CONTAINER, CHIP_TLV_END_OF_CONTAINER, CHIP_TLV_STRUCTURE(CHIP_TLV_TAG_IMPLICIT_PROFILE_2Bytes(1)), CHIP_TLV_BOOL(CHIP_TLV_TAG_IMPLICIT_PROFILE_2Bytes(2), false), CHIP_TLV_BOOL(CHIP_TLV_TAG_FULLY_QUALIFIED_6Bytes(TestProfile_1, 2), true), CHIP_TLV_END_OF_CONTAINER, }; // clang-format on void WriteEncoding5(nlTestSuite * inSuite, TLVWriter & writer) { CHIP_ERROR err; { // Container 1 TLVWriter writer1; err = writer.OpenContainer(ProfileTag(TestProfile_1, 1), kTLVType_Structure, writer1); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer1.PutBoolean(ProfileTag(TestProfile_1, 2), true); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer1.PutBoolean(ProfileTag(TestProfile_2, 2), false); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer1.PutBoolean(ProfileTag(TestProfile_1, 2), false); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer1.PutBoolean(ProfileTag(TestProfile_2, 2), true); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); { // Inner Container 1 TLVWriter writer2; err = writer1.OpenContainer(ProfileTag(TestProfile_1, 1), kTLVType_Structure, writer2); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.PutBoolean(ProfileTag(TestProfile_1, 2), true); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.PutBoolean(ProfileTag(TestProfile_2, 2), false); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer1.CloseContainer(writer2); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } { // Inner Container 2 TLVWriter writer2; err = writer1.OpenContainer(ProfileTag(TestProfile_2, 1), kTLVType_Structure, writer2); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.PutBoolean(ProfileTag(TestProfile_2, 2), false); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.PutBoolean(ProfileTag(TestProfile_1, 2), true); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer1.CloseContainer(writer2); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } err = writer.CloseContainer(writer1); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } { // Container 2 TLVWriter writer1; err = writer.OpenContainer(ProfileTag(TestProfile_2, 1), kTLVType_Structure, writer1); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer1.PutBoolean(ProfileTag(TestProfile_2, 2), false); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer1.PutBoolean(ProfileTag(TestProfile_1, 2), true); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.CloseContainer(writer1); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } err = writer.Finalize(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } /** * AppendEncoding2() * * This function appends two boolean types and two container types to the first * container. * * The boolean types are- * <TestProfile_1, 2, false> * <TestProfile_2, 2, true> * * The two new container types are- * <TestProfile_1, 1, kTLVType_Structure, <TestProfile_1, 2, true> <TestProfile_2, 2, false> >, * <TestProfile_2, 1, kTLVType_Structure, <TestProfile_2, 2, false> <TestProfile_1, 2, true> > */ void AppendEncoding2(nlTestSuite * inSuite, uint8_t * buf, uint32_t dataLen, uint32_t maxLen, uint32_t & updatedLen) { CHIP_ERROR err; TLVUpdater updater; err = updater.Init(buf, dataLen, maxLen); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); updater.SetImplicitProfileId(TestProfile_2); TestNext<TLVUpdater>(inSuite, updater); { TLVType outerContainerType; TestAndEnterContainer<TLVUpdater>(inSuite, updater, kTLVType_Structure, ProfileTag(TestProfile_1, 1), outerContainerType); TestNext<TLVUpdater>(inSuite, updater); // Move the element without modification TestMove(inSuite, updater); TestNext<TLVUpdater>(inSuite, updater); // Read and copy the element with/without modification TestGet<TLVUpdater, bool>(inSuite, updater, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); err = updater.PutBoolean(ProfileTag(TestProfile_2, 2), false); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // TestEnd and add data at the end of the container TestEnd<TLVUpdater>(inSuite, updater); // Put new values in the encoding using the updater // Add <TestProfile_1, 2, false> err = updater.PutBoolean(ProfileTag(TestProfile_1, 2), false); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // Add <TestProfile_2, 2, true> err = updater.PutBoolean(ProfileTag(TestProfile_2, 2), true); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // Add a new container { TLVType outerContainerType1; err = updater.StartContainer(ProfileTag(TestProfile_1, 1), kTLVType_Structure, outerContainerType1); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // Add <TestProfile_1, 2, true> err = updater.PutBoolean(ProfileTag(TestProfile_1, 2), true); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // Add <TestProfile_1, 2, true> err = updater.PutBoolean(ProfileTag(TestProfile_2, 2), false); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // Close the container err = updater.EndContainer(outerContainerType1); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } // Add another new container { TLVType outerContainerType1; err = updater.StartContainer(ProfileTag(TestProfile_2, 1), kTLVType_Structure, outerContainerType1); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // Add <TestProfile_2, 2, false> err = updater.PutBoolean(ProfileTag(TestProfile_2, 2), false); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // Add <TestProfile_1, 2, true> err = updater.PutBoolean(ProfileTag(TestProfile_1, 2), true); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // Close the container err = updater.EndContainer(outerContainerType1); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } TestEndAndExitContainer<TLVUpdater>(inSuite, updater, outerContainerType); } TestNext<TLVUpdater>(inSuite, updater); // Move the container unmodified TestMove(inSuite, updater); TestEnd<TLVUpdater>(inSuite, updater); err = updater.Finalize(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); updatedLen = updater.GetLengthWritten(); } /** * FindAppendEncoding2() * * This function appends two boolean types and two container types to the first * container. It is very similar to AppendEncoding2() above except for the fact * that it uses TLVUtilities::Find() to find the element of interest before * appending new data. * * The boolean types are- * <TestProfile_1, 2, false> * <TestProfile_2, 2, true> * * The two new container types are- * <TestProfile_1, 1, kTLVType_Structure, <TestProfile_1, 2, true> <TestProfile_2, 2, false> >, * <TestProfile_2, 1, kTLVType_Structure, <TestProfile_2, 2, false> <TestProfile_1, 2, true> > */ void FindAppendEncoding2(nlTestSuite * inSuite, uint8_t * buf, uint32_t dataLen, uint32_t maxLen, uint32_t & updatedLen, bool findContainer) { CHIP_ERROR err; TLVReader reader; TLVUpdater updater; // Initialize a reader reader.Init(buf, dataLen); reader.ImplicitProfileId = TestProfile_2; if (findContainer) { // Find the container TLVReader tagReader; TLVType outerContainerType; err = chip::TLV::Utilities::Find(reader, ProfileTag(TestProfile_1, 1), tagReader); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = tagReader.EnterContainer(outerContainerType); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); do { err = tagReader.Next(); } while (err != CHIP_END_OF_TLV); TestEnd<TLVReader>(inSuite, tagReader); // Init a TLVUpdater using the TLVReader err = updater.Init(tagReader, maxLen - dataLen); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } else { // Find TLVReader tagReader; err = chip::TLV::Utilities::Find(reader, ProfileTag(TestProfile_2, 2), tagReader); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // Test Find(recurse = true) TLVReader tagReader2; err = chip::TLV::Utilities::Find(reader, ProfileTag(TestProfile_2, 2), tagReader2, true); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // // Test Find(recurse = false) TLVReader tagReader3; err = chip::TLV::Utilities::Find(reader, ProfileTag(TestProfile_2, 2), tagReader3, false); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_TLV_TAG_NOT_FOUND); // Init a TLVUpdater using the TLVReader err = updater.Init(tagReader, maxLen - dataLen); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); TestNext<TLVUpdater>(inSuite, updater); // Move the element without modification TestMove(inSuite, updater); } // Put new values in the encoding using the updater // Add <TestProfile_1, 2, false> err = updater.PutBoolean(ProfileTag(TestProfile_1, 2), false); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // Add <TestProfile_2, 2, true> err = updater.PutBoolean(ProfileTag(TestProfile_2, 2), true); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // Add a new container { TLVType outerContainerType1; err = updater.StartContainer(ProfileTag(TestProfile_1, 1), kTLVType_Structure, outerContainerType1); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // Add <TestProfile_1, 2, true> err = updater.PutBoolean(ProfileTag(TestProfile_1, 2), true); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // Add <TestProfile_1, 2, true> err = updater.PutBoolean(ProfileTag(TestProfile_2, 2), false); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // Close the container err = updater.EndContainer(outerContainerType1); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } // Add another new container { TLVType outerContainerType1; err = updater.StartContainer(ProfileTag(TestProfile_2, 1), kTLVType_Structure, outerContainerType1); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // Add <TestProfile_2, 2, false> err = updater.PutBoolean(ProfileTag(TestProfile_2, 2), false); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // Add <TestProfile_1, 2, true> err = updater.PutBoolean(ProfileTag(TestProfile_1, 2), true); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // Close the container err = updater.EndContainer(outerContainerType1); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } // Move everything else unmodified updater.MoveUntilEnd(); TestEnd<TLVUpdater>(inSuite, updater); err = updater.Finalize(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); updatedLen = updater.GetLengthWritten(); } void AppendEncoding3(nlTestSuite * inSuite, uint8_t * buf, uint32_t dataLen, uint32_t maxLen, uint32_t & updatedLen) { CHIP_ERROR err; TLVUpdater updater; err = updater.Init(buf, dataLen, maxLen); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); updater.SetImplicitProfileId(TestProfile_2); TestNext<TLVUpdater>(inSuite, updater); { TLVType outerContainerType; TestAndEnterContainer<TLVUpdater>(inSuite, updater, kTLVType_Structure, ProfileTag(TestProfile_1, 1), outerContainerType); TestNext<TLVUpdater>(inSuite, updater); // Move the element without modification TestMove(inSuite, updater); // Put new value in the encoding using the updater // Add <TestProfile_2, 2, true> err = updater.PutBoolean(ProfileTag(TestProfile_2, 2), true); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); TestEndAndExitContainer<TLVUpdater>(inSuite, updater, outerContainerType); } TestEnd<TLVUpdater>(inSuite, updater); err = updater.Finalize(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); updatedLen = updater.GetLengthWritten(); } void AppendEncoding4(nlTestSuite * inSuite, uint8_t * buf, uint32_t dataLen, uint32_t maxLen, uint32_t & updatedLen) { CHIP_ERROR err; TLVUpdater updater; err = updater.Init(buf, dataLen, maxLen); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); updater.SetImplicitProfileId(TestProfile_2); // Add a new container { TLVType outerContainerType; err = updater.StartContainer(ProfileTag(TestProfile_1, 1), kTLVType_Structure, outerContainerType); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // Add <TestProfile_1, 2, true> err = updater.PutBoolean(ProfileTag(TestProfile_2, 2), false); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // Close the container err = updater.EndContainer(outerContainerType); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } err = updater.Finalize(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); updatedLen = updater.GetLengthWritten(); } void DeleteEncoding5(nlTestSuite * inSuite, uint8_t * buf, uint32_t dataLen, uint32_t maxLen, uint32_t & updatedLen) { CHIP_ERROR err; TLVUpdater updater; err = updater.Init(buf, dataLen, maxLen); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); updater.SetImplicitProfileId(TestProfile_2); TestNext<TLVUpdater>(inSuite, updater); { TLVType outerContainerType; TestAndEnterContainer<TLVUpdater>(inSuite, updater, kTLVType_Structure, ProfileTag(TestProfile_1, 1), outerContainerType); TestNext<TLVUpdater>(inSuite, updater); TestMove(inSuite, updater); TestNext<TLVUpdater>(inSuite, updater); TestMove(inSuite, updater); TestNext<TLVUpdater>(inSuite, updater); // Get the value to inspect and skip writing it TestGet<TLVUpdater, bool>(inSuite, updater, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), false); TestNext<TLVUpdater>(inSuite, updater); // Skip the next boolean type and don't copy by doing nothing TestNext<TLVUpdater>(inSuite, updater); // Read ahead into the next container and decide whether to skip or // not based on elements in the container { TLVReader reader; TLVType containerType; updater.GetReader(reader); TestAndEnterContainer<TLVReader>(inSuite, reader, kTLVType_Structure, ProfileTag(TestProfile_1, 1), containerType); TestNext<TLVReader>(inSuite, reader); // If the container's first element has the tag <TestProfile_1, 2> // skip the whole container, and if NOT copy the container if (reader.GetTag() != ProfileTag(TestProfile_1, 2)) TestMove(inSuite, updater); } TestNext<TLVUpdater>(inSuite, updater); // Skip the next container and don't copy by doing nothing TestEndAndExitContainer<TLVUpdater>(inSuite, updater, outerContainerType); } // Move everything else unmodified updater.MoveUntilEnd(); TestEnd<TLVUpdater>(inSuite, updater); err = updater.Finalize(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); updatedLen = updater.GetLengthWritten(); } void ReadAppendedEncoding2(nlTestSuite * inSuite, TLVReader & reader) { TestNext<TLVReader>(inSuite, reader); { // Container 1 TLVReader reader1; TestAndOpenContainer(inSuite, reader, kTLVType_Structure, ProfileTag(TestProfile_1, 1), reader1); TestNext<TLVReader>(inSuite, reader1); TestGet<TLVReader, bool>(inSuite, reader1, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); TestNext<TLVReader>(inSuite, reader1); TestGet<TLVReader, bool>(inSuite, reader1, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); TestNext<TLVReader>(inSuite, reader1); TestGet<TLVReader, bool>(inSuite, reader1, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), false); TestNext<TLVReader>(inSuite, reader1); TestGet<TLVReader, bool>(inSuite, reader1, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), true); TestNext<TLVReader>(inSuite, reader1); { TLVReader reader2; TestAndOpenContainer(inSuite, reader1, kTLVType_Structure, ProfileTag(TestProfile_1, 1), reader2); TestNext<TLVReader>(inSuite, reader2); TestGet<TLVReader, bool>(inSuite, reader2, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); TestNext<TLVReader>(inSuite, reader2); TestGet<TLVReader, bool>(inSuite, reader2, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); TestEndAndCloseContainer(inSuite, reader1, reader2); } TestNext<TLVReader>(inSuite, reader1); { TLVReader reader2; TestAndOpenContainer(inSuite, reader1, kTLVType_Structure, ProfileTag(TestProfile_2, 1), reader2); TestNext<TLVReader>(inSuite, reader2); TestGet<TLVReader, bool>(inSuite, reader2, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); TestNext<TLVReader>(inSuite, reader2); TestGet<TLVReader, bool>(inSuite, reader2, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); TestEndAndCloseContainer(inSuite, reader1, reader2); } TestEndAndCloseContainer(inSuite, reader, reader1); } TestNext<TLVReader>(inSuite, reader); { // Container 2 TLVReader reader1; TestAndOpenContainer(inSuite, reader, kTLVType_Structure, ProfileTag(TestProfile_2, 1), reader1); TestNext<TLVReader>(inSuite, reader1); TestGet<TLVReader, bool>(inSuite, reader1, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); TestNext<TLVReader>(inSuite, reader1); TestGet<TLVReader, bool>(inSuite, reader1, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); TestEndAndCloseContainer(inSuite, reader, reader1); } TestEnd<TLVReader>(inSuite, reader); } void ReadAppendedEncoding3(nlTestSuite * inSuite, TLVReader & reader) { TestNext<TLVReader>(inSuite, reader); { // Container 1 TLVReader reader1; TestAndOpenContainer(inSuite, reader, kTLVType_Structure, ProfileTag(TestProfile_1, 1), reader1); TestNext<TLVReader>(inSuite, reader1); TestGet<TLVReader, bool>(inSuite, reader1, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); TestNext<TLVReader>(inSuite, reader1); TestGet<TLVReader, bool>(inSuite, reader1, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), true); TestEndAndCloseContainer(inSuite, reader, reader1); } TestEnd<TLVReader>(inSuite, reader); } void ReadAppendedEncoding4(nlTestSuite * inSuite, TLVReader & reader) { TestNext<TLVReader>(inSuite, reader); { // Container 1 TLVReader reader1; TestAndOpenContainer(inSuite, reader, kTLVType_Structure, ProfileTag(TestProfile_1, 1), reader1); TestNext<TLVReader>(inSuite, reader1); TestGet<TLVReader, bool>(inSuite, reader1, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); TestEndAndCloseContainer(inSuite, reader, reader1); } TestEnd<TLVReader>(inSuite, reader); } void ReadDeletedEncoding5(nlTestSuite * inSuite, TLVReader & reader) { TestNext<TLVReader>(inSuite, reader); { // Container 1 TLVReader reader1; TestAndOpenContainer(inSuite, reader, kTLVType_Structure, ProfileTag(TestProfile_1, 1), reader1); TestNext<TLVReader>(inSuite, reader1); TestGet<TLVReader, bool>(inSuite, reader1, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); TestNext<TLVReader>(inSuite, reader1); TestGet<TLVReader, bool>(inSuite, reader1, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); TestEndAndCloseContainer(inSuite, reader, reader1); } TestNext<TLVReader>(inSuite, reader); { // Container 2 TLVReader reader1; TestAndOpenContainer(inSuite, reader, kTLVType_Structure, ProfileTag(TestProfile_2, 1), reader1); TestNext<TLVReader>(inSuite, reader1); TestGet<TLVReader, bool>(inSuite, reader1, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); TestNext<TLVReader>(inSuite, reader1); TestGet<TLVReader, bool>(inSuite, reader1, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); TestEndAndCloseContainer(inSuite, reader, reader1); } TestEnd<TLVReader>(inSuite, reader); } /** * Test Simple Write and Reader */ void CheckSimpleWriteRead(nlTestSuite * inSuite, void * inContext) { uint8_t buf[2048]; TLVWriter writer; TLVReader reader; writer.Init(buf, sizeof(buf)); writer.ImplicitProfileId = TestProfile_2; WriteEncoding1(inSuite, writer); uint32_t encodedLen = writer.GetLengthWritten(); #ifdef DUMP_ENCODING for (uint32_t i = 0; i < encodedLen; i++) { if (i != 0 && i % 16 == 0) printf("\n"); printf("0x%02X, ", buf[i]); } printf("\n"); #endif NL_TEST_ASSERT(inSuite, encodedLen == sizeof(Encoding1)); NL_TEST_ASSERT(inSuite, memcmp(buf, Encoding1, encodedLen) == 0); reader.Init(buf, encodedLen); reader.ImplicitProfileId = TestProfile_2; ReadEncoding1(inSuite, reader); } /** * Log the specified message in the form of @a aFormat. * * @param[in] aFormat A pointer to a NULL-terminated C string with * C Standard Library-style format specifiers * containing the log message to be formatted and * logged. * @param[in] ... An argument list whose elements should correspond * to the format specifiers in @a aFormat. * */ void SimpleDumpWriter(const char * aFormat, ...) { va_list args; va_start(args, aFormat); vprintf(aFormat, args); va_end(args); } /** * Test Pretty Printer */ void CheckPrettyPrinter(nlTestSuite * inSuite, void * inContext) { uint8_t buf[2048]; TLVWriter writer; TLVReader reader; writer.Init(buf, sizeof(buf)); writer.ImplicitProfileId = TestProfile_2; WriteEncoding1(inSuite, writer); uint32_t encodedLen = writer.GetLengthWritten(); NL_TEST_ASSERT(inSuite, encodedLen == sizeof(Encoding1)); NL_TEST_ASSERT(inSuite, memcmp(buf, Encoding1, encodedLen) == 0); reader.Init(buf, encodedLen); reader.ImplicitProfileId = TestProfile_2; chip::TLV::Debug::Dump(reader, SimpleDumpWriter); } /** * Test Data Macros */ void CheckDataMacro(nlTestSuite * inSuite, void * inContext) { NL_TEST_ASSERT(inSuite, sizeof(Encoding1_DataMacro) == sizeof(Encoding1)); NL_TEST_ASSERT(inSuite, memcmp(Encoding1, Encoding1_DataMacro, sizeof(Encoding1)) == 0); uint8_t buf[2048]; TLVWriter writer; writer.Init(buf, sizeof(buf)); writer.ImplicitProfileId = TestProfile_2; WriteEncoding5(inSuite, writer); uint32_t encodedLen = writer.GetLengthWritten(); NL_TEST_ASSERT(inSuite, sizeof(Encoding5_DataMacro) == encodedLen); NL_TEST_ASSERT(inSuite, memcmp(buf, Encoding5_DataMacro, encodedLen) == 0); } static CHIP_ERROR NullIterateHandler(const TLVReader & aReader, size_t aDepth, void * aContext) { (void) aReader; (void) aDepth; (void) aContext; return CHIP_NO_ERROR; } static CHIP_ERROR FindContainerWithElement(const TLVReader & aReader, size_t aDepth, void * aContext) { TLVReader reader; TLVReader result; uint64_t * tag = static_cast<uint64_t *>(aContext); CHIP_ERROR err = CHIP_NO_ERROR; TLVType containerType; reader.Init(aReader); if (TLVTypeIsContainer(reader.GetType())) { err = reader.EnterContainer(containerType); SuccessOrExit(err); err = chip::TLV::Utilities::Find(reader, *tag, result, false); // Map a successful find (CHIP_NO_ERROR) onto a signal that the element has been found. if (err == CHIP_NO_ERROR) { err = CHIP_ERROR_MAX; } // Map a failed find attempt to NO_ERROR else if (err == CHIP_ERROR_TLV_TAG_NOT_FOUND) { err = CHIP_NO_ERROR; } } exit: return err; } /** * Test CHIP TLV Utilities */ void CheckCHIPTLVUtilities(nlTestSuite * inSuite, void * inContext) { uint8_t buf[2048]; TLVWriter writer; TLVReader reader, reader1; CHIP_ERROR err = CHIP_NO_ERROR; writer.Init(buf, sizeof(buf)); writer.ImplicitProfileId = TestProfile_2; WriteEncoding1(inSuite, writer); uint32_t encodedLen = writer.GetLengthWritten(); NL_TEST_ASSERT(inSuite, encodedLen == sizeof(Encoding1)); NL_TEST_ASSERT(inSuite, memcmp(buf, Encoding1, encodedLen) == 0); reader.Init(buf, encodedLen); reader.ImplicitProfileId = TestProfile_2; reader1.Init(reader); err = reader1.Next(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // Find a tag TLVReader tagReader; err = chip::TLV::Utilities::Find(reader, ProfileTag(TestProfile_2, 65536), tagReader); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // Find with reader positioned "on" the element of interest err = chip::TLV::Utilities::Find(reader1, ProfileTag(TestProfile_1, 1), tagReader); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // Find a tag that's not present err = chip::TLV::Utilities::Find(reader, ProfileTag(TestProfile_2, 1024), tagReader); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_TLV_TAG_NOT_FOUND); // Find with a predicate { uint8_t buf1[74]; writer.Init(buf1, sizeof(buf1)); writer.ImplicitProfileId = TestProfile_2; WriteEncoding2(inSuite, writer); // Initialize a reader reader1.Init(buf1, writer.GetLengthWritten()); reader1.ImplicitProfileId = TestProfile_2; // position the reader on the first element reader1.Next(); uint64_t tag = ProfileTag(TestProfile_1, 1); err = chip::TLV::Utilities::Find(reader1, FindContainerWithElement, &tag, tagReader, false); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_TLV_TAG_NOT_FOUND); tag = ProfileTag(TestProfile_2, 2); err = chip::TLV::Utilities::Find(reader1, FindContainerWithElement, &tag, tagReader, false); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, tagReader.GetType() == kTLVType_Structure); NL_TEST_ASSERT(inSuite, tagReader.GetTag() == ProfileTag(TestProfile_1, 1)); // Position the reader on the second element reader1.Next(); err = chip::TLV::Utilities::Find(reader1, FindContainerWithElement, &tag, tagReader, false); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, tagReader.GetType() == kTLVType_Structure); NL_TEST_ASSERT(inSuite, tagReader.GetTag() == ProfileTag(TestProfile_2, 1)); } // Count size_t count; const size_t expectedCount = 18; reader1.Init(reader); reader1.Next(); err = chip::TLV::Utilities::Count(reader, count); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, count == expectedCount); // Count with reader already positioned "on" the first element in the encoding err = chip::TLV::Utilities::Count(reader1, count); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, count == expectedCount); // Iterate err = chip::TLV::Utilities::Iterate(reader, NullIterateHandler, nullptr); NL_TEST_ASSERT(inSuite, err == CHIP_END_OF_TLV); } /** * Test CHIP TLV Empty Find */ void CheckCHIPTLVEmptyFind(nlTestSuite * inSuite, void * inContext) { uint8_t buf[30]; TLVWriter writer; TLVReader reader; CHIP_ERROR err = CHIP_NO_ERROR; writer.Init(buf, sizeof(buf)); writer.ImplicitProfileId = TestProfile_2; WriteEmptyEncoding(inSuite, writer); uint32_t encodedLen = writer.GetLengthWritten(); reader.Init(buf, encodedLen); reader.ImplicitProfileId = TestProfile_2; // Find the empty container TLVReader tagReader; err = chip::TLV::Utilities::Find(reader, ProfileTag(TestProfile_1, 256), tagReader); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } // clang-format off uint8_t Encoding2[] = { // Container 1 0xD5, 0xBB, 0xAA, 0xDD, 0xCC, 0x01, 0x00, 0xC9, 0xBB, 0xAA, 0xDD, 0xCC, 0x02, 0x00, 0x88, 0x02, 0x00, 0x18, // Container 2 0x95, 0x01, 0x00, 0x88, 0x02, 0x00, 0xC9, 0xBB, 0xAA, 0xDD, 0xCC, 0x02, 0x00, 0x18 }; uint8_t AppendedEncoding2[] = { // Container 1 0xD5, 0xBB, 0xAA, 0xDD, 0xCC, 0x01, 0x00, 0xC9, 0xBB, 0xAA, 0xDD, 0xCC, 0x02, 0x00, 0x88, 0x02, 0x00, 0xC8, 0xBB, 0xAA, 0xDD, 0xCC, 0x02, 0x00, 0x89, 0x02, 0x00, 0xD5, 0xBB, 0xAA, 0xDD, 0xCC, 0x01, 0x00, 0xC9, 0xBB, 0xAA, 0xDD, 0xCC, 0x02, 0x00, 0x88, 0x02, 0x00, 0x18, 0x95, 0x01, 0x00, 0x88, 0x02, 0x00, 0xC9, 0xBB, 0xAA, 0xDD, 0xCC, 0x02, 0x00, 0x18, 0x18, // Container 2 0x95, 0x01, 0x00, 0x88, 0x02, 0x00, 0xC9, 0xBB, 0xAA, 0xDD, 0xCC, 0x02, 0x00, 0x18 }; // clang-format on void WriteAppendReadTest0(nlTestSuite * inSuite) { uint8_t buf[74]; uint32_t updatedLen; TLVWriter writer; TLVReader reader; writer.Init(buf, sizeof(buf)); writer.ImplicitProfileId = TestProfile_2; WriteEncoding2(inSuite, writer); uint32_t encodedLen = writer.GetLengthWritten(); #ifdef DUMP_ENCODING printf("Initial encoding:\n"); for (uint32_t i = 0; i < encodedLen; i++) { if (i != 0 && i % 16 == 0) printf("\n"); printf("0x%02X, ", buf[i]); } printf("\n"); #endif NL_TEST_ASSERT(inSuite, encodedLen == sizeof(Encoding2)); NL_TEST_ASSERT(inSuite, memcmp(buf, Encoding2, encodedLen) == 0); // Append new data into encoding AppendEncoding2(inSuite, buf, encodedLen, sizeof(buf), updatedLen); #ifdef DUMP_ENCODING printf("Updated encoding:\n"); for (uint32_t i = 0; i < updatedLen; i++) { if (i != 0 && i % 16 == 0) printf("\n"); printf("0x%02X, ", buf[i]); } printf("\n"); #endif NL_TEST_ASSERT(inSuite, updatedLen == sizeof(AppendedEncoding2)); NL_TEST_ASSERT(inSuite, memcmp(buf, AppendedEncoding2, updatedLen) == 0); reader.Init(buf, updatedLen); reader.ImplicitProfileId = TestProfile_2; ReadAppendedEncoding2(inSuite, reader); } void WriteFindAppendReadTest(nlTestSuite * inSuite, bool findContainer) { uint8_t buf[74]; uint32_t updatedLen; TLVWriter writer; TLVReader reader; writer.Init(buf, sizeof(buf)); writer.ImplicitProfileId = TestProfile_2; WriteEncoding2(inSuite, writer); uint32_t encodedLen = writer.GetLengthWritten(); #ifdef DUMP_ENCODING printf("Initial encoding:\n"); for (uint32_t i = 0; i < encodedLen; i++) { if (i != 0 && i % 16 == 0) printf("\n"); printf("0x%02X, ", buf[i]); } printf("\n"); #endif NL_TEST_ASSERT(inSuite, encodedLen == sizeof(Encoding2)); NL_TEST_ASSERT(inSuite, memcmp(buf, Encoding2, encodedLen) == 0); // Append new data into encoding FindAppendEncoding2(inSuite, buf, encodedLen, sizeof(buf), updatedLen, findContainer); #ifdef DUMP_ENCODING printf("Updated encoding:\n"); for (uint32_t i = 0; i < updatedLen; i++) { if (i != 0 && i % 16 == 0) printf("\n"); printf("0x%02X, ", buf[i]); } printf("\n"); #endif NL_TEST_ASSERT(inSuite, updatedLen == sizeof(AppendedEncoding2)); NL_TEST_ASSERT(inSuite, memcmp(buf, AppendedEncoding2, updatedLen) == 0); reader.Init(buf, updatedLen); reader.ImplicitProfileId = TestProfile_2; ReadAppendedEncoding2(inSuite, reader); } // clang-format off uint8_t Encoding3[] = { // Container 1 0xD5, 0xBB, 0xAA, 0xDD, 0xCC, 0x01, 0x00, 0x88, 0x02, 0x00, 0x18, }; uint8_t AppendedEncoding3[] = { // Container 1 0xD5, 0xBB, 0xAA, 0xDD, 0xCC, 0x01, 0x00, 0x88, 0x02, 0x00, 0x89, 0x02, 0x00, 0x18 }; // clang-format on void WriteAppendReadTest1(nlTestSuite * inSuite) { uint8_t buf[14]; uint32_t updatedLen; TLVWriter writer; TLVReader reader; writer.Init(buf, sizeof(buf)); writer.ImplicitProfileId = TestProfile_2; WriteEncoding3(inSuite, writer); uint32_t encodedLen = writer.GetLengthWritten(); #ifdef DUMP_ENCODING printf("Initial encoding:\n"); for (uint32_t i = 0; i < encodedLen; i++) { if (i != 0 && i % 16 == 0) printf("\n"); printf("0x%02X, ", buf[i]); } printf("\n"); #endif NL_TEST_ASSERT(inSuite, encodedLen == sizeof(Encoding3)); NL_TEST_ASSERT(inSuite, memcmp(buf, Encoding3, encodedLen) == 0); // Append new data into encoding AppendEncoding3(inSuite, buf, encodedLen, sizeof(buf), updatedLen); #ifdef DUMP_ENCODING printf("Updated encoding:\n"); for (uint32_t i = 0; i < updatedLen; i++) { if (i != 0 && i % 16 == 0) printf("\n"); printf("0x%02X, ", buf[i]); } printf("\n"); #endif NL_TEST_ASSERT(inSuite, updatedLen == sizeof(AppendedEncoding3)); NL_TEST_ASSERT(inSuite, memcmp(buf, AppendedEncoding3, updatedLen) == 0); reader.Init(buf, updatedLen); reader.ImplicitProfileId = TestProfile_2; ReadAppendedEncoding3(inSuite, reader); } // clang-format off uint8_t AppendedEncoding4[] = { // Container 1 0xD5, 0xBB, 0xAA, 0xDD, 0xCC, 0x01, 0x00, 0x88, 0x02, 0x00, 0x18, }; // clang-format on void AppendReadTest(nlTestSuite * inSuite) { uint8_t buf[11]; uint32_t updatedLen; memset(buf, 0, sizeof(buf)); #ifdef DUMP_ENCODING printf("Initial encoding:\n"); for (uint32_t i = 0; i < sizeof(buf); i++) { if (i != 0 && i % 16 == 0) printf("\n"); printf("0x%02X, ", buf[i]); } printf("\n"); #endif // Append new data to encoding AppendEncoding4(inSuite, buf, 0, sizeof(buf), updatedLen); #ifdef DUMP_ENCODING printf("Updated encoding:\n"); for (uint32_t i = 0; i < updatedLen; i++) { if (i != 0 && i % 16 == 0) printf("\n"); printf("0x%02X, ", buf[i]); } printf("\n"); #endif NL_TEST_ASSERT(inSuite, updatedLen == sizeof(AppendedEncoding4)); NL_TEST_ASSERT(inSuite, memcmp(buf, AppendedEncoding4, updatedLen) == 0); TLVReader reader; reader.Init(buf, updatedLen); reader.ImplicitProfileId = TestProfile_2; ReadAppendedEncoding4(inSuite, reader); } // clang-format off uint8_t Encoding5[] = { // Container 1 0xD5, 0xBB, 0xAA, 0xDD, 0xCC, 0x01, 0x00, 0xC9, 0xBB, 0xAA, 0xDD, 0xCC, 0x02, 0x00, 0x88, 0x02, 0x00, 0xC8, 0xBB, 0xAA, 0xDD, 0xCC, 0x02, 0x00, 0x89, 0x02, 0x00, 0xD5, 0xBB, 0xAA, 0xDD, 0xCC, 0x01, 0x00, 0xC9, 0xBB, 0xAA, 0xDD, 0xCC, 0x02, 0x00, 0x88, 0x02, 0x00, 0x18, 0x95, 0x01, 0x00, 0x88, 0x02, 0x00, 0xC9, 0xBB, 0xAA, 0xDD, 0xCC, 0x02, 0x00, 0x18, 0x18, // Container 2 0x95, 0x01, 0x00, 0x88, 0x02, 0x00, 0xC9, 0xBB, 0xAA, 0xDD, 0xCC, 0x02, 0x00, 0x18 }; uint8_t DeletedEncoding5[] = { // Container 1 0xD5, 0xBB, 0xAA, 0xDD, 0xCC, 0x01, 0x00, 0xC9, 0xBB, 0xAA, 0xDD, 0xCC, 0x02, 0x00, 0x88, 0x02, 0x00, 0x18, // Container 2 0x95, 0x01, 0x00, 0x88, 0x02, 0x00, 0xC9, 0xBB, 0xAA, 0xDD, 0xCC, 0x02, 0x00, 0x18 }; // clang-format on void WriteDeleteReadTest(nlTestSuite * inSuite) { uint8_t buf[74]; uint32_t updatedLen; TLVWriter writer; TLVReader reader; writer.Init(buf, sizeof(buf)); writer.ImplicitProfileId = TestProfile_2; WriteEncoding5(inSuite, writer); uint32_t encodedLen = writer.GetLengthWritten(); #ifdef DUMP_ENCODING for (uint32_t i = 0; i < encodedLen; i++) { if (i != 0 && i % 16 == 0) printf("\n"); printf("0x%02X, ", buf[i]); } printf("\n"); #endif NL_TEST_ASSERT(inSuite, encodedLen == sizeof(Encoding5)); NL_TEST_ASSERT(inSuite, memcmp(buf, Encoding5, encodedLen) == 0); // Delete some elements from the encoding DeleteEncoding5(inSuite, buf, encodedLen, sizeof(buf), updatedLen); NL_TEST_ASSERT(inSuite, updatedLen == sizeof(DeletedEncoding5)); NL_TEST_ASSERT(inSuite, memcmp(buf, DeletedEncoding5, updatedLen) == 0); reader.Init(buf, updatedLen); reader.ImplicitProfileId = TestProfile_2; ReadDeletedEncoding5(inSuite, reader); } /** * Test Packet Buffer */ void CheckPacketBuffer(nlTestSuite * inSuite, void * inContext) { PacketBuffer * buf = PacketBuffer::New(0); TLVWriter writer; TLVReader reader; writer.Init(buf); writer.ImplicitProfileId = TestProfile_2; WriteEncoding1(inSuite, writer); TestBufferContents(inSuite, buf, Encoding1, sizeof(Encoding1)); reader.Init(buf); reader.ImplicitProfileId = TestProfile_2; ReadEncoding1(inSuite, reader); reader.Init(buf, buf->MaxDataLength(), false); reader.ImplicitProfileId = TestProfile_2; ReadEncoding1(inSuite, reader); PacketBuffer::Free(buf); } CHIP_ERROR CountEvictedMembers(CHIPCircularTLVBuffer & inBuffer, void * inAppData, TLVReader & inReader) { TestTLVContext * context = static_cast<TestTLVContext *>(inAppData); CHIP_ERROR err; // "Process" the first element in the reader err = inReader.Next(); NL_TEST_ASSERT(context->mSuite, err == CHIP_NO_ERROR); err = inReader.Skip(); NL_TEST_ASSERT(context->mSuite, err == CHIP_NO_ERROR); context->mEvictionCount++; context->mEvictedBytes += inReader.GetLengthRead(); return CHIP_NO_ERROR; } void CheckCircularTLVBufferSimple(nlTestSuite * inSuite, void * inContext) { // Write 40 bytes as 4 separate events into a 30 byte buffer. On // completion of the test, the buffer should contain 2 elements // and 2 elements should have been evicted in the last call to // WriteEncoding. uint8_t backingStore[30]; CircularTLVWriter writer; CircularTLVReader reader; TestTLVContext * context = static_cast<TestTLVContext *>(inContext); CHIPCircularTLVBuffer buffer(backingStore, 30); writer.Init(&buffer); writer.ImplicitProfileId = TestProfile_2; context->mEvictionCount = 0; context->mEvictedBytes = 0; buffer.mProcessEvictedElement = CountEvictedMembers; buffer.mAppData = inContext; writer.PutBoolean(ProfileTag(TestProfile_1, 2), true); WriteEncoding3(inSuite, writer); WriteEncoding3(inSuite, writer); WriteEncoding3(inSuite, writer); NL_TEST_ASSERT(inSuite, context->mEvictionCount == 2); NL_TEST_ASSERT(inSuite, context->mEvictedBytes == 18); NL_TEST_ASSERT(inSuite, buffer.DataLength() == 22); NL_TEST_ASSERT(inSuite, (buffer.DataLength() + context->mEvictedBytes) == writer.GetLengthWritten()); // At this point the buffer should contain 2 instances of Encoding3. reader.Init(&buffer); reader.ImplicitProfileId = TestProfile_2; TestNext<TLVReader>(inSuite, reader); ReadEncoding3(inSuite, reader); TestNext<TLVReader>(inSuite, reader); ReadEncoding3(inSuite, reader); // Check that the reader is out of data TestEnd<TLVReader>(inSuite, reader); } void CheckCircularTLVBufferStartMidway(nlTestSuite * inSuite, void * inContext) { // Write 40 bytes as 4 separate events into a 30 byte buffer. On // completion of the test, the buffer should contain 2 elements // and 2 elements should have been evicted in the last call to // WriteEncoding. uint8_t backingStore[30]; CircularTLVWriter writer; CircularTLVReader reader; TestTLVContext * context = static_cast<TestTLVContext *>(inContext); CHIPCircularTLVBuffer buffer(backingStore, 30, &(backingStore[15])); writer.Init(&buffer); writer.ImplicitProfileId = TestProfile_2; context->mEvictionCount = 0; context->mEvictedBytes = 0; buffer.mProcessEvictedElement = CountEvictedMembers; buffer.mAppData = inContext; writer.PutBoolean(ProfileTag(TestProfile_1, 2), true); WriteEncoding3(inSuite, writer); WriteEncoding3(inSuite, writer); WriteEncoding3(inSuite, writer); NL_TEST_ASSERT(inSuite, context->mEvictionCount == 2); NL_TEST_ASSERT(inSuite, context->mEvictedBytes == 18); NL_TEST_ASSERT(inSuite, buffer.DataLength() == 22); NL_TEST_ASSERT(inSuite, (buffer.DataLength() + context->mEvictedBytes) == writer.GetLengthWritten()); // At this point the buffer should contain 2 instances of Encoding3. reader.Init(&buffer); reader.ImplicitProfileId = TestProfile_2; TestNext<TLVReader>(inSuite, reader); ReadEncoding3(inSuite, reader); TestNext<TLVReader>(inSuite, reader); ReadEncoding3(inSuite, reader); // Check that the reader is out of data TestEnd<TLVReader>(inSuite, reader); } void CheckCircularTLVBufferEvictStraddlingEvent(nlTestSuite * inSuite, void * inContext) { // Write 95 bytes to the buffer as 9 different TLV elements: 1 // 7-byte element and 8 11-byte elements. // On completion of the test, the buffer should contain 2 elements // and 7 elements should have been evicted in the last call to // WriteEncoding. TestTLVContext * context = static_cast<TestTLVContext *>(inContext); uint8_t backingStore[30]; CircularTLVWriter writer; CircularTLVReader reader; CHIPCircularTLVBuffer buffer(backingStore, 30); writer.Init(&buffer); writer.ImplicitProfileId = TestProfile_2; context->mEvictionCount = 0; context->mEvictedBytes = 0; buffer.mProcessEvictedElement = CountEvictedMembers; buffer.mAppData = inContext; writer.PutBoolean(ProfileTag(TestProfile_1, 2), true); WriteEncoding3(inSuite, writer); WriteEncoding3(inSuite, writer); WriteEncoding3(inSuite, writer); WriteEncoding3(inSuite, writer); // the write below will evict an element that straddles the buffer boundary. WriteEncoding3(inSuite, writer); WriteEncoding3(inSuite, writer); WriteEncoding3(inSuite, writer); WriteEncoding3(inSuite, writer); NL_TEST_ASSERT(inSuite, writer.GetLengthWritten() == (8 * 11 + 7)); // 8 writes of Encoding3 (11 bytes each) and 7 bytes for the initial boolean. NL_TEST_ASSERT(inSuite, buffer.DataLength() == 22); NL_TEST_ASSERT(inSuite, (buffer.DataLength() + context->mEvictedBytes) == writer.GetLengthWritten()); NL_TEST_ASSERT(inSuite, context->mEvictionCount == 7); // At this point the buffer should contain 2 instances of Encoding3. reader.Init(&buffer); reader.ImplicitProfileId = TestProfile_2; TestNext<TLVReader>(inSuite, reader); ReadEncoding3(inSuite, reader); TestNext<TLVReader>(inSuite, reader); ReadEncoding3(inSuite, reader); // Check that the reader is out of data TestEnd<TLVReader>(inSuite, reader); } void CheckCircularTLVBufferEdge(nlTestSuite * inSuite, void * inContext) { TestTLVContext * context = static_cast<TestTLVContext *>(inContext); CHIP_ERROR err; uint8_t backingStore[7]; uint8_t backingStore1[14]; CircularTLVWriter writer; CircularTLVReader reader; TLVWriter writer1; CHIPCircularTLVBuffer buffer(backingStore, sizeof(backingStore)); CHIPCircularTLVBuffer buffer1(backingStore1, sizeof(backingStore1)); writer.Init(&buffer); writer.ImplicitProfileId = TestProfile_2; context->mEvictionCount = 0; context->mEvictedBytes = 0; buffer.mProcessEvictedElement = CountEvictedMembers; buffer.mAppData = inContext; // Test eviction for an element that fits in the underlying buffer exactly err = writer.PutBoolean(ProfileTag(TestProfile_1, 2), true); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.PutBoolean(ProfileTag(TestProfile_1, 2), false); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.Finalize(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // At this point the buffer should contain only the boolean we just wrote reader.Init(&buffer); reader.ImplicitProfileId = TestProfile_2; TestNext<TLVReader>(inSuite, reader); TestGet<TLVReader, bool>(inSuite, reader, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), false); // Check that the reader is out of data TestEnd<TLVReader>(inSuite, reader); // verify that an element larger than the underlying buffer fails out. err = writer.OpenContainer(ProfileTag(TestProfile_1, 1), kTLVType_Structure, writer1); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer1.PutBoolean(ProfileTag(TestProfile_2, 2), false); NL_TEST_ASSERT(inSuite, err == CHIP_END_OF_TLV); // Verify reader correctness // Write an element that takes half of the buffer, and evict it. // Do it 2 times, so we test what happens when the head is at the // middle and at the end of the buffer but the buffer is empty. int i = 0; for (i = 0; i < 2; i++) { writer.Init(&buffer1); writer.ImplicitProfileId = TestProfile_2; err = writer.PutBoolean(ProfileTag(TestProfile_1, 2), true); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.Finalize(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); reader.Init(&buffer1); reader.ImplicitProfileId = TestProfile_2; TestNext<TLVReader>(inSuite, reader); TestGet<TLVReader, bool>(inSuite, reader, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); TestEnd<TLVReader>(inSuite, reader); buffer1.EvictHead(); reader.Init(&buffer1); reader.ImplicitProfileId = TestProfile_2; TestEnd<TLVReader>(inSuite, reader); } writer.Init(&buffer1); writer.ImplicitProfileId = TestProfile_2; context->mEvictionCount = 0; context->mEvictedBytes = 0; buffer1.mProcessEvictedElement = CountEvictedMembers; buffer1.mAppData = inContext; // Two elements fit in the buffer exactly err = writer.PutBoolean(ProfileTag(TestProfile_1, 2), true); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.PutBoolean(ProfileTag(TestProfile_1, 2), false); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.Finalize(); // Verify that we can read out two elements from the buffer reader.Init(&buffer1); reader.ImplicitProfileId = TestProfile_2; TestNext<TLVReader>(inSuite, reader); TestGet<TLVReader, bool>(inSuite, reader, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); TestNext<TLVReader>(inSuite, reader); TestGet<TLVReader, bool>(inSuite, reader, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), false); TestEnd<TLVReader>(inSuite, reader); // Check that the eviction works as expected buffer1.EvictHead(); // At this point the buffer should contain only the second boolean reader.Init(&buffer1); reader.ImplicitProfileId = TestProfile_2; TestNext<TLVReader>(inSuite, reader); TestGet<TLVReader, bool>(inSuite, reader, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), false); // Check that the reader is out of data TestEnd<TLVReader>(inSuite, reader); // Write another boolean, verify that the buffer is full and contains two booleans writer.Init(&buffer1); writer.ImplicitProfileId = TestProfile_2; err = writer.PutBoolean(ProfileTag(TestProfile_1, 2), true); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.Finalize(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // Verify that we can read out two elements from the buffer reader.Init(&buffer1); reader.ImplicitProfileId = TestProfile_2; TestNext<TLVReader>(inSuite, reader); TestGet<TLVReader, bool>(inSuite, reader, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), false); TestNext<TLVReader>(inSuite, reader); TestGet<TLVReader, bool>(inSuite, reader, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); TestEnd<TLVReader>(inSuite, reader); // Evict the elements from the buffer, verfiy that we have an // empty reader on our hands buffer1.EvictHead(); buffer1.EvictHead(); reader.Init(&buffer1); reader.ImplicitProfileId = TestProfile_2; TestEnd<TLVReader>(inSuite, reader); } void CheckCHIPTLVPutStringF(nlTestSuite * inSuite, void * inContext) { const size_t bufsize = 24; char strBuffer[bufsize]; char valStr[bufsize]; uint8_t backingStore[bufsize]; TLVWriter writer; TLVReader reader; size_t num = 1; CHIP_ERROR err = CHIP_NO_ERROR; writer.Init(backingStore, bufsize); snprintf(strBuffer, sizeof(strBuffer), "Sample string %zu", num); err = writer.PutStringF(ProfileTag(TestProfile_1, 1), "Sample string %zu", num); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.Finalize(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); reader.Init(backingStore, writer.GetLengthWritten()); err = reader.Next(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = reader.GetString(valStr, 256); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, strncmp(valStr, strBuffer, 256) == 0); } void CheckCHIPTLVPutStringFCircular(nlTestSuite * inSuite, void * inContext) { const size_t bufsize = 40; char strBuffer[bufsize]; char valStr[bufsize]; uint8_t backingStore[bufsize]; CircularTLVWriter writer; CircularTLVReader reader; CHIPCircularTLVBuffer buffer(backingStore, bufsize); size_t num = 1; CHIP_ERROR err = CHIP_NO_ERROR; // Initial test: Verify that a straight printf works as expected into continuous buffer. writer.Init(&buffer); snprintf(strBuffer, sizeof(strBuffer), "Sample string %zu", num); err = writer.PutBoolean(ProfileTag(TestProfile_1, 2), true); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.Finalize(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.PutStringF(ProfileTag(TestProfile_1, 1), "Sample string %zu", num); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.Finalize(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); reader.Init(&buffer); // Skip over the initial element err = reader.Next(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = reader.Next(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = reader.GetString(valStr, bufsize); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, strncmp(valStr, strBuffer, bufsize) == 0); // Verify that the PutStringF will handle correctly the case with the discontinuous buffer // This print will both stradle the boundary of the buffer and displace the previous two elements. num = 2; snprintf(strBuffer, sizeof(strBuffer), "Sample string %zu", num); err = writer.PutStringF(ProfileTag(TestProfile_1, 1), "Sample string %zu", num); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.Finalize(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); reader.Init(&buffer); err = reader.Next(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = reader.GetString(valStr, bufsize); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, strncmp(valStr, strBuffer, bufsize) == 0); } void CheckCHIPTLVSkipCircular(nlTestSuite * inSuite, void * inContext) { const size_t bufsize = 40; // large enough s.t. 2 elements fit, 3rd causes eviction uint8_t backingStore[bufsize]; char testString[] = "Sample string"; // 13 characters, without the trailing NULL, add 3 bytes for anon tag // Any pair of reader and writer would work here, either PacketBuffer based or CircularTLV based. CircularTLVWriter writer; CircularTLVReader reader; CHIPCircularTLVBuffer buffer(backingStore, bufsize); CHIP_ERROR err = CHIP_NO_ERROR; writer.Init(&buffer); err = writer.PutString(AnonymousTag, testString); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.PutString(AnonymousTag, testString); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.PutString(AnonymousTag, testString); // This event straddles the boundary NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.PutString(AnonymousTag, testString); // This one does not. NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.Finalize(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); reader.Init(&buffer); err = reader.Next(); // position the reader at the straddling element NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = reader.Skip(); // // Test that the buf ptr is handled correctly within the ReadData() function. NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } /** * Test Buffer Overflow */ void CheckBufferOverflow(nlTestSuite * inSuite, void * inContext) { TLVWriter writer; TLVReader reader; PacketBuffer * buf = PacketBuffer::New(0); uint16_t maxDataLen = buf->MaxDataLength(); uint16_t reserve = (sizeof(Encoding1) < maxDataLen) ? (maxDataLen - sizeof(Encoding1)) + 2 : 0; // Repeatedly write and read a TLV encoding to a chain of PacketBuffers. Use progressively larger // and larger amounts of space in the first buffer to force the encoding/decoding to overlap the // end of the buffer and the beginning of the next. for (; reserve < maxDataLen; reserve++) { buf->SetStart(buf->Start() + reserve); writer.Init(buf); writer.GetNewBuffer = TLVWriter::GetNewPacketBuffer; writer.ImplicitProfileId = TestProfile_2; WriteEncoding1(inSuite, writer); TestBufferContents(inSuite, buf, Encoding1, sizeof(Encoding1)); reader.Init(buf, 0xFFFFFFFFUL, true); reader.ImplicitProfileId = TestProfile_2; ReadEncoding1(inSuite, reader); PacketBuffer::Free(buf); buf = PacketBuffer::New(0); } } /** * Test case to verify the correctness of TLVReader::GetTag() * * TLVReader::GetTag() does not return the correct tag value when the * the compiler optimization level contains strict aliasing. In the below * example, the returned tag value would be 0xe, instead of 0xe00000001. * * The issue has been spotted on debug builds. * */ // clang-format off static const uint8_t sIdentifyResponseBuf[] = { 0xD5, 0x00, 0x00, 0x0E, 0x00, 0x01, 0x00, 0x25, 0x00, 0x5A, 0x23, 0x24, 0x01, 0x07, 0x24, 0x02, 0x05, 0x25, 0x03, 0x22, 0x1E, 0x2C, 0x04, 0x10, 0x30, 0x34, 0x41, 0x41, 0x30, 0x31, 0x41, 0x43, 0x32, 0x33, 0x31, 0x34, 0x30, 0x30, 0x4C, 0x50, 0x2C, 0x09, 0x06, 0x31, 0x2E, 0x34, 0x72, 0x63, 0x35, 0x24, 0x0C, 0x01, 0x18, }; // clang-format on static const uint32_t kIdentifyResponseLen = 53; void CheckStrictAliasing(nlTestSuite * inSuite, void * inContext) { const uint32_t kProfile_Id = 0x0000000e; CHIP_ERROR err = CHIP_NO_ERROR; TLVReader reader; reader.Init(sIdentifyResponseBuf, kIdentifyResponseLen); reader.ImplicitProfileId = kProfile_Id; err = reader.Next(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, reader.GetTag() == 0xe00000001); } /** * Test CHIP TLV Writer Copy Container */ void TestCHIPTLVWriterCopyContainer(nlTestSuite * inSuite) { uint8_t buf[2048]; { TLVWriter writer; TLVReader reader; reader.Init(Encoding1, sizeof(Encoding1)); reader.ImplicitProfileId = TestProfile_2; TestNext<TLVReader>(inSuite, reader); writer.Init(buf, sizeof(buf)); writer.ImplicitProfileId = TestProfile_2; CHIP_ERROR err = writer.CopyContainer(reader); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); uint32_t encodedLen = writer.GetLengthWritten(); NL_TEST_ASSERT(inSuite, encodedLen == sizeof(Encoding1)); int memcmpRes = memcmp(buf, Encoding1, encodedLen); NL_TEST_ASSERT(inSuite, memcmpRes == 0); } { TLVWriter writer; writer.Init(buf, sizeof(buf)); writer.ImplicitProfileId = TestProfile_2; CHIP_ERROR err = writer.CopyContainer(ProfileTag(TestProfile_1, 1), Encoding1, sizeof(Encoding1)); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); uint32_t encodedLen = writer.GetLengthWritten(); NL_TEST_ASSERT(inSuite, encodedLen == sizeof(Encoding1)); int memcmpRes = memcmp(buf, Encoding1, encodedLen); NL_TEST_ASSERT(inSuite, memcmpRes == 0); } } /** * Test CHIP TLV Writer Copy Element */ void TestCHIPTLVWriterCopyElement(nlTestSuite * inSuite) { CHIP_ERROR err; uint8_t expectedBuf[2048], testBuf[2048]; uint32_t expectedLen, testLen; TLVWriter writer; TLVType outerContainerType; enum { kRepeatCount = 3 }; writer.Init(expectedBuf, sizeof(expectedBuf)); writer.ImplicitProfileId = TestProfile_2; err = writer.StartContainer(AnonymousTag, kTLVType_Structure, outerContainerType); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); for (int i = 0; i < kRepeatCount; i++) { WriteEncoding1(inSuite, writer); } err = writer.EndContainer(outerContainerType); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.Finalize(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); expectedLen = writer.GetLengthWritten(); writer.Init(testBuf, sizeof(testBuf)); writer.ImplicitProfileId = TestProfile_2; err = writer.StartContainer(AnonymousTag, kTLVType_Structure, outerContainerType); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); for (int i = 0; i < kRepeatCount; i++) { TLVReader reader; reader.Init(Encoding1, sizeof(Encoding1)); reader.ImplicitProfileId = TestProfile_2; TestNext<TLVReader>(inSuite, reader); err = writer.CopyElement(reader); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } err = writer.EndContainer(outerContainerType); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.Finalize(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); testLen = writer.GetLengthWritten(); NL_TEST_ASSERT(inSuite, testLen == expectedLen); int memcmpRes = memcmp(testBuf, expectedBuf, testLen); NL_TEST_ASSERT(inSuite, memcmpRes == 0); } void PreserveSizeWrite(nlTestSuite * inSuite, TLVWriter & writer, bool preserveSize) { CHIP_ERROR err; TLVWriter writer2; // kTLVTagControl_FullyQualified_8Bytes err = writer.Put(ProfileTag(TestProfile_1, 4000000000ULL), (int64_t) 40000000000ULL, true); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.Put(ProfileTag(TestProfile_1, 4000000000ULL), (int16_t) 12345, true); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.Put(ProfileTag(TestProfile_1, 4000000000ULL), (float) 1.0); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.OpenContainer(ProfileTag(TestProfile_1, 1), kTLVType_Structure, writer2); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); { TLVWriter writer3; err = writer2.OpenContainer(ContextTag(0), kTLVType_Array, writer3); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer3.Put(AnonymousTag, (uint8_t) 42, preserveSize); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer3.Put(AnonymousTag, (uint16_t) 42, preserveSize); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer3.Put(AnonymousTag, (uint32_t) 42, preserveSize); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer3.Put(AnonymousTag, (uint64_t) 40000000000ULL, preserveSize); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer3.Put(AnonymousTag, (int8_t) -17, preserveSize); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer3.Put(AnonymousTag, (int16_t) -17, preserveSize); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer3.Put(AnonymousTag, (int32_t) -170000, preserveSize); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer3.Put(AnonymousTag, (int64_t) -170000, preserveSize); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // the below cases are for full coverage of PUTs err = writer3.Put(AnonymousTag, (uint64_t) 65535, false); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer3.Put(AnonymousTag, (int64_t) 32767, false); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer3.Put(AnonymousTag, (int64_t) 40000000000ULL, false); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.CloseContainer(writer3); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } err = writer.CloseContainer(writer2); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.Finalize(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } /** * Test CHIP TLV Writer with Preserve Size */ void TestCHIPTLVWriterPreserveSize(nlTestSuite * inSuite) { uint8_t buf[2048]; TLVWriter writer; writer.Init(buf, sizeof(buf)); writer.ImplicitProfileId = TestProfile_2; PreserveSizeWrite(inSuite, writer, true); uint32_t encodedLen = writer.GetLengthWritten(); NL_TEST_ASSERT(inSuite, encodedLen == 105); } /** * Test error handling of CHIP TLV Writer */ void TestCHIPTLVWriterErrorHandling(nlTestSuite * inSuite) { CHIP_ERROR err; uint8_t buf[2048]; TLVWriter writer, writer2, writer3; writer.Init(buf, sizeof(buf)); writer.ImplicitProfileId = TestProfile_2; // OpenContainer() for non-container err = writer.OpenContainer(ProfileTag(TestProfile_1, 1), kTLVType_Boolean, writer2); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_WRONG_TLV_TYPE); // CloseContainer() for non-container err = writer.CloseContainer(writer2); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INCORRECT_STATE); // OpenContainer() failure err = writer.OpenContainer(ProfileTag(TestProfile_1, 1), kTLVType_Structure, writer2); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.OpenContainer(ProfileTag(TestProfile_1, 1), kTLVType_Structure, writer3); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // CloseContainer() failure err = writer.CloseContainer(writer2); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_TLV_CONTAINER_OPEN); // StartContainer() TLVType outerContainerType; err = writer.StartContainer(ProfileTag(TestProfile_2, 4000000000ULL), kTLVType_Boolean, outerContainerType); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_WRONG_TLV_TYPE); // EndContainer() outerContainerType = kTLVType_Boolean; err = writer.EndContainer(outerContainerType); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INCORRECT_STATE); // PutPreEncodedContainer() TLVReader reader; reader.Init(buf, 2048); err = writer.PutPreEncodedContainer(ProfileTag(TestProfile_2, 4000000000ULL), kTLVType_Boolean, reader.GetReadPoint(), reader.GetRemainingLength()); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INVALID_ARGUMENT); } /** * Test CHIP TLV Writer */ void CheckCHIPTLVWriter(nlTestSuite * inSuite, void * inContext) { TestCHIPTLVWriterCopyContainer(inSuite); TestCHIPTLVWriterCopyElement(inSuite); TestCHIPTLVWriterPreserveSize(inSuite); TestCHIPTLVWriterErrorHandling(inSuite); } void SkipNonContainer(nlTestSuite * inSuite) { TLVReader reader; const uint8_t * readpoint1 = nullptr; const uint8_t * readpoint2 = nullptr; reader.Init(Encoding1, sizeof(Encoding1)); reader.ImplicitProfileId = TestProfile_2; TestSkip(inSuite, reader); readpoint1 = reader.GetReadPoint(); // Skip again, to check the operation is idempotent TestSkip(inSuite, reader); readpoint2 = reader.GetReadPoint(); NL_TEST_ASSERT(inSuite, readpoint1 == readpoint2); } void SkipContainer(nlTestSuite * inSuite) { TLVReader reader; const uint8_t * readpoint1 = nullptr; const uint8_t * readpoint2 = nullptr; reader.Init(Encoding1, sizeof(Encoding1)); reader.ImplicitProfileId = TestProfile_2; TestNext<TLVReader>(inSuite, reader); TestSkip(inSuite, reader); readpoint1 = reader.GetReadPoint(); // Skip again, to check the operation is idempotent TestSkip(inSuite, reader); readpoint2 = reader.GetReadPoint(); NL_TEST_ASSERT(inSuite, readpoint1 == readpoint2); } void NextContainer(nlTestSuite * inSuite) { TLVReader reader; reader.Init(Encoding1, sizeof(Encoding1)); reader.ImplicitProfileId = TestProfile_2; TestNext<TLVReader>(inSuite, reader); CHIP_ERROR err = reader.Next(); NL_TEST_ASSERT(inSuite, err == CHIP_END_OF_TLV); } /** * Test CHIP TLV Reader Skip functions */ void TestCHIPTLVReaderSkip(nlTestSuite * inSuite) { SkipNonContainer(inSuite); SkipContainer(inSuite); NextContainer(inSuite); } /** * Test CHIP TLV Reader Dup functions */ void TestCHIPTLVReaderDup(nlTestSuite * inSuite) { TLVReader reader; reader.Init(Encoding1, sizeof(Encoding1)); reader.ImplicitProfileId = TestProfile_2; TestNext<TLVReader>(inSuite, reader); { TLVReader reader2; TestAndOpenContainer(inSuite, reader, kTLVType_Structure, ProfileTag(TestProfile_1, 1), reader2); TestNext<TLVReader>(inSuite, reader2); TestGet<TLVReader, bool>(inSuite, reader2, kTLVType_Boolean, ProfileTag(TestProfile_1, 2), true); TestNext<TLVReader>(inSuite, reader2); TestGet<TLVReader, bool>(inSuite, reader2, kTLVType_Boolean, ProfileTag(TestProfile_2, 2), false); TestNext<TLVReader>(inSuite, reader2); { TLVReader reader3; TestAndOpenContainer(inSuite, reader2, kTLVType_Array, ContextTag(0), reader3); TestNext<TLVReader>(inSuite, reader3); TestGet<TLVReader, int8_t>(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag, 42); TestGet<TLVReader, int16_t>(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag, 42); TestGet<TLVReader, int32_t>(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag, 42); TestGet<TLVReader, int64_t>(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag, 42); TestGet<TLVReader, uint32_t>(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag, 42); TestGet<TLVReader, uint64_t>(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag, 42); TestNext<TLVReader>(inSuite, reader3); TestGet<TLVReader, int8_t>(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag, -17); TestGet<TLVReader, int16_t>(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag, -17); TestGet<TLVReader, int32_t>(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag, -17); TestGet<TLVReader, int64_t>(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag, -17); TestNext<TLVReader>(inSuite, reader3); TestGet<TLVReader, int32_t>(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag, -170000); TestGet<TLVReader, int64_t>(inSuite, reader3, kTLVType_SignedInteger, AnonymousTag, -170000); TestNext<TLVReader>(inSuite, reader3); TestGet<TLVReader, int64_t>(inSuite, reader3, kTLVType_UnsignedInteger, AnonymousTag, 40000000000ULL); TestGet<TLVReader, uint64_t>(inSuite, reader3, kTLVType_UnsignedInteger, AnonymousTag, 40000000000ULL); TestNext<TLVReader>(inSuite, reader3); { TLVReader reader4; TestAndOpenContainer(inSuite, reader3, kTLVType_Structure, AnonymousTag, reader4); TestEndAndCloseContainer(inSuite, reader3, reader4); } TestNext<TLVReader>(inSuite, reader3); { TLVReader reader5; TestAndOpenContainer(inSuite, reader3, kTLVType_Path, AnonymousTag, reader5); TestNext<TLVReader>(inSuite, reader5); TestNull(inSuite, reader5, ProfileTag(TestProfile_1, 17)); TestNext<TLVReader>(inSuite, reader5); TestNull(inSuite, reader5, ProfileTag(TestProfile_2, 900000)); TestNext<TLVReader>(inSuite, reader5); TestNull(inSuite, reader5, AnonymousTag); TestNext<TLVReader>(inSuite, reader5); { TLVType outerContainerType; TestAndEnterContainer<TLVReader>(inSuite, reader5, kTLVType_Structure, ProfileTag(TestProfile_2, 4000000000ULL), outerContainerType); TestNext<TLVReader>(inSuite, reader5); TestDupString(inSuite, reader5, CommonTag(70000), sLargeString); TestEndAndExitContainer<TLVReader>(inSuite, reader5, outerContainerType); } TestEndAndCloseContainer(inSuite, reader3, reader5); } TestEndAndCloseContainer(inSuite, reader2, reader3); } TestNext<TLVReader>(inSuite, reader2); TestDupBytes(inSuite, reader2, ProfileTag(TestProfile_1, 5), (uint8_t *) ("This is a test"), 14); TestNext<TLVReader>(inSuite, reader2); TestGet<TLVReader, double>(inSuite, reader2, kTLVType_FloatingPointNumber, ProfileTag(TestProfile_2, 65535), (float) 17.9); TestNext<TLVReader>(inSuite, reader2); TestGet<TLVReader, double>(inSuite, reader2, kTLVType_FloatingPointNumber, ProfileTag(TestProfile_2, 65536), (double) 17.9); TestEndAndCloseContainer(inSuite, reader, reader2); } TestEnd<TLVReader>(inSuite, reader); } /** * Test error handling of CHIP TLV Reader */ void TestCHIPTLVReaderErrorHandling(nlTestSuite * inSuite) { CHIP_ERROR err; uint8_t buf[2048]; TLVReader reader; reader.Init(buf, sizeof(buf)); reader.ImplicitProfileId = TestProfile_2; // Get(bool&) bool val; err = reader.Get(val); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_WRONG_TLV_TYPE); // Get(double&) double numD; err = reader.Get(numD); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_WRONG_TLV_TYPE); // Get(uint64_t&) uint64_t num; err = reader.Get(num); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_WRONG_TLV_TYPE); // GetBytes() uint8_t bBuf[16]; err = reader.GetBytes(bBuf, sizeof(bBuf)); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_WRONG_TLV_TYPE); // GetString() char sBuf[16]; err = reader.GetString(sBuf, sizeof(sBuf)); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_WRONG_TLV_TYPE); // OpenContainer() TLVReader reader2; err = reader.OpenContainer(reader2); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INCORRECT_STATE); // CloseContainer() err = reader.CloseContainer(reader2); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INCORRECT_STATE); // EnterContainer() TLVType outerContainerType = kTLVType_Boolean; err = reader.EnterContainer(outerContainerType); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INCORRECT_STATE); // DupString() char * str = (char *) malloc(16); err = reader.DupString(str); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_WRONG_TLV_TYPE); free(str); // GetDataPtr() const uint8_t * data = (uint8_t *) malloc(16); err = reader.GetDataPtr(data); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_WRONG_TLV_TYPE); free((void *) data); } /** * Test CHIP TLV Reader in a use case */ void TestCHIPTLVReaderInPractice(nlTestSuite * inSuite) { uint8_t buf[2048]; TLVWriter writer; TLVReader reader; writer.Init(buf, sizeof(buf)); writer.ImplicitProfileId = TestProfile_2; PreserveSizeWrite(inSuite, writer, true); reader.Init(buf, sizeof(buf)); TestNext<TLVReader>(inSuite, reader); TestGet<TLVReader, int64_t>(inSuite, reader, kTLVType_SignedInteger, ProfileTag(TestProfile_1, 4000000000ULL), (int64_t) 40000000000ULL); TestNext<TLVReader>(inSuite, reader); TestGet<TLVReader, int64_t>(inSuite, reader, kTLVType_SignedInteger, ProfileTag(TestProfile_1, 4000000000ULL), (int16_t) 12345); TestNext<TLVReader>(inSuite, reader); TestGet<TLVReader, double>(inSuite, reader, kTLVType_FloatingPointNumber, ProfileTag(TestProfile_1, 4000000000ULL), (float) 1.0); } void TestCHIPTLVReader_NextOverContainer_ProcessElement(nlTestSuite * inSuite, TLVReader & reader, void * context) { CHIP_ERROR err, nextRes1, nextRes2; TLVType outerContainerType; // If the current element is a container... if (TLVTypeIsContainer(reader.GetType())) { // Make two copies of the reader TLVReader readerClone1 = reader; TLVReader readerClone2 = reader; // Manually advance one of the readers to the element immediately after the container (if any). err = readerClone1.EnterContainer(outerContainerType); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); ForEachElement(inSuite, readerClone1, nullptr, nullptr); err = readerClone1.ExitContainer(outerContainerType); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); nextRes1 = readerClone1.Next(); NL_TEST_ASSERT(inSuite, nextRes1 == CHIP_NO_ERROR || nextRes1 == CHIP_END_OF_TLV); // For the other reader, skip over the entire container using the Next() method. nextRes2 = readerClone2.Next(); NL_TEST_ASSERT(inSuite, nextRes2 == CHIP_NO_ERROR || nextRes2 == CHIP_END_OF_TLV); // Verify the two readers end up in the same state/position. NL_TEST_ASSERT(inSuite, nextRes1 == nextRes2); NL_TEST_ASSERT(inSuite, readerClone1.GetType() == readerClone2.GetType()); NL_TEST_ASSERT(inSuite, readerClone1.GetReadPoint() == readerClone2.GetReadPoint()); } } /** * Test using CHIP TLV Reader Next() method to skip over containers. */ void TestCHIPTLVReader_NextOverContainer(nlTestSuite * inSuite) { TLVReader reader; reader.Init(Encoding1, sizeof(Encoding1)); reader.ImplicitProfileId = TestProfile_2; ForEachElement(inSuite, reader, nullptr, TestCHIPTLVReader_NextOverContainer_ProcessElement); } void TestCHIPTLVReader_SkipOverContainer_ProcessElement(nlTestSuite * inSuite, TLVReader & reader, void * context) { CHIP_ERROR err; TLVType outerContainerType; // If the current element is a container... if (TLVTypeIsContainer(reader.GetType())) { // Make two copies of the reader TLVReader readerClone1 = reader; TLVReader readerClone2 = reader; // Manually advance one of the readers to immediately after the container. err = readerClone1.EnterContainer(outerContainerType); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); ForEachElement(inSuite, readerClone1, nullptr, nullptr); err = readerClone1.ExitContainer(outerContainerType); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // For the other reader, skip over the entire container using the Skip() method. err = readerClone2.Skip(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // Verify the two readers end up in the same state/position. NL_TEST_ASSERT(inSuite, readerClone1.GetType() == readerClone2.GetType()); NL_TEST_ASSERT(inSuite, readerClone1.GetReadPoint() == readerClone2.GetReadPoint()); } } /** * Test using CHIP TLV Reader Skip() method to skip over containers. */ void TestCHIPTLVReader_SkipOverContainer(nlTestSuite * inSuite) { TLVReader reader; reader.Init(Encoding1, sizeof(Encoding1)); reader.ImplicitProfileId = TestProfile_2; ForEachElement(inSuite, reader, nullptr, TestCHIPTLVReader_SkipOverContainer_ProcessElement); } /** * Test CHIP TLV Reader */ void CheckCHIPTLVReader(nlTestSuite * inSuite, void * inContext) { TestCHIPTLVReaderSkip(inSuite); TestCHIPTLVReaderDup(inSuite); TestCHIPTLVReaderErrorHandling(inSuite); TestCHIPTLVReaderInPractice(inSuite); TestCHIPTLVReader_NextOverContainer(inSuite); TestCHIPTLVReader_SkipOverContainer(inSuite); } /** * Test CHIP TLV Items */ static void TestItems(nlTestSuite * inSuite, void * inContext) { CHIP_ERROR err = CHIP_NO_ERROR; uint8_t sBuffer[256]; TLVWriter writer; writer.Init(sBuffer, sizeof(sBuffer)); TLVWriter writer2; err = writer.OpenContainer(AnonymousTag, kTLVType_Array, writer2); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); { err = writer2.PutBoolean(AnonymousTag, true); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.Put(AnonymousTag, static_cast<int8_t>(-1)); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.Put(AnonymousTag, static_cast<int16_t>(-2)); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.Put(AnonymousTag, static_cast<int32_t>(-3)); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.Put(AnonymousTag, static_cast<int64_t>(-4)); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.Put(AnonymousTag, static_cast<float>(-5.5)); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.Put(AnonymousTag, static_cast<double>(-3.14159265358979323846)); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } err = writer.CloseContainer(writer2); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.OpenContainer(AnonymousTag, kTLVType_Array, writer2); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); { err = writer2.PutBoolean(AnonymousTag, false); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.Put(AnonymousTag, static_cast<int8_t>(1)); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.Put(AnonymousTag, static_cast<int16_t>(2)); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.Put(AnonymousTag, static_cast<int32_t>(3)); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.Put(AnonymousTag, static_cast<int64_t>(4)); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.Put(AnonymousTag, static_cast<uint8_t>(5)); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.Put(AnonymousTag, static_cast<uint16_t>(6)); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.Put(AnonymousTag, static_cast<uint32_t>(7)); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.Put(AnonymousTag, static_cast<uint64_t>(8)); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.Put(AnonymousTag, static_cast<float>(9.9)); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.Put(AnonymousTag, static_cast<double>(3.14159265358979323846)); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } err = writer.CloseContainer(writer2); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.Finalize(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } /** * Test CHIP TLV Containers */ static void TestContainers(nlTestSuite * inSuite, void * inContext) { CHIP_ERROR err = CHIP_NO_ERROR; TLVWriter writer; uint8_t sBuffer[256]; writer.Init(sBuffer, sizeof(sBuffer)); TLVWriter writer2; err = writer.OpenContainer(AnonymousTag, kTLVType_Array, writer2); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); TLVType type = writer2.GetContainerType(); NL_TEST_ASSERT(inSuite, type == kTLVType_Array); err = writer.CloseContainer(writer2); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.OpenContainer(AnonymousTag, kTLVType_Structure, writer2); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); type = writer2.GetContainerType(); NL_TEST_ASSERT(inSuite, type == kTLVType_Structure); err = writer.CloseContainer(writer2); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer.Finalize(); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } /** * Test CHIP TLV Basics */ static void CheckCHIPTLVBasics(nlTestSuite * inSuite, void * inContext) { TestItems(inSuite, inContext); TestContainers(inSuite, inContext); } /** * Test CHIP TLV Updater */ static void CheckCHIPUpdater(nlTestSuite * inSuite, void * inContext) { WriteAppendReadTest0(inSuite); WriteAppendReadTest1(inSuite); WriteFindAppendReadTest(inSuite, false); // Find an element WriteFindAppendReadTest(inSuite, true); // Find a container AppendReadTest(inSuite); WriteDeleteReadTest(inSuite); } /** * Test TLV CloseContainer symbol reservations */ class OptimisticTLVWriter : public TLVWriter { public: void Init(uint8_t * buf, uint32_t maxLen); }; void OptimisticTLVWriter::Init(uint8_t * buf, uint32_t maxLen) { TLVWriter::Init(buf, maxLen); SetCloseContainerReserved(false); } static void CheckCloseContainerReserve(nlTestSuite * inSuite, void * inContext) { // We are writing the structure looking like: // // [{TestProfile_1:2: true}] // // the above should consume 11 bytes in the TLV encoding. The // chosen buffer is too small for that, this test verifies that we // fail in the right places in the code. With the standard // TLVWriter, we now make provisions to reserve the space for the // CloseContainer tag in the OpenContainer call. As a result, we // expect to error out when we attempt to write out the value for // the TestProfile_1:2 tag. In contrast, the // `OptimisticTLVWriter` implements the earlier TLVWriter behavior // and fails out in the last CloseContainer call. The error // caught there is different because we run up against the mMaxLen // rather than mRemainingLen check. uint8_t buf[10]; uint8_t buf1[7]; CHIP_ERROR err = CHIP_NO_ERROR; TLVWriter writer1; OptimisticTLVWriter writer2; TLVWriter innerWriter1, innerWriter2; TLVType container1, container2; writer1.Init(buf, sizeof(buf)); err = writer1.OpenContainer(AnonymousTag, kTLVType_Array, innerWriter1); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = innerWriter1.OpenContainer(AnonymousTag, kTLVType_Structure, innerWriter2); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = innerWriter2.PutBoolean(ProfileTag(TestProfile_1, 2), true); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_BUFFER_TOO_SMALL); err = innerWriter1.CloseContainer(innerWriter2); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer1.CloseContainer(innerWriter1); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); writer2.Init(buf, sizeof(buf)); err = writer2.OpenContainer(AnonymousTag, kTLVType_Array, innerWriter1); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = innerWriter1.OpenContainer(AnonymousTag, kTLVType_Structure, innerWriter2); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = innerWriter2.PutBoolean(ProfileTag(TestProfile_1, 2), true); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = innerWriter1.CloseContainer(innerWriter2); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.CloseContainer(innerWriter1); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_BUFFER_TOO_SMALL); // test the same scheme works on the Start/End container writer1.Init(buf, sizeof(buf)); err = writer1.StartContainer(AnonymousTag, kTLVType_Array, container1); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer1.StartContainer(AnonymousTag, kTLVType_Structure, container2); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer1.PutBoolean(ProfileTag(TestProfile_1, 2), true); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_BUFFER_TOO_SMALL); err = writer1.EndContainer(container2); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer1.EndContainer(container1); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); writer2.Init(buf, sizeof(buf)); err = writer2.StartContainer(AnonymousTag, kTLVType_Array, container1); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.StartContainer(AnonymousTag, kTLVType_Structure, container2); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.PutBoolean(ProfileTag(TestProfile_1, 2), true); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.EndContainer(container2); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.EndContainer(container1); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_BUFFER_TOO_SMALL); // Test that the reservations work for the empty containers writer1.Init(buf1, sizeof(buf1)); err = writer1.OpenContainer(ProfileTag(TestProfile_1, 2), kTLVType_Structure, innerWriter1); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_BUFFER_TOO_SMALL); err = writer1.CloseContainer(innerWriter1); NL_TEST_ASSERT(inSuite, err != CHIP_NO_ERROR); writer2.Init(buf1, sizeof(buf1)); err = writer2.OpenContainer(ProfileTag(TestProfile_1, 2), kTLVType_Structure, innerWriter1); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.CloseContainer(innerWriter1); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_BUFFER_TOO_SMALL); writer1.Init(buf1, sizeof(buf1)); err = writer1.StartContainer(ProfileTag(TestProfile_1, 2), kTLVType_Structure, container1); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_BUFFER_TOO_SMALL); err = writer1.EndContainer(container1); NL_TEST_ASSERT(inSuite, err != CHIP_NO_ERROR); writer2.Init(buf1, sizeof(buf1)); err = writer2.StartContainer(ProfileTag(TestProfile_1, 2), kTLVType_Structure, container1); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = writer2.EndContainer(container1); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_BUFFER_TOO_SMALL); // Test that the reservations work if the writer has a maxLen of 0. writer1.Init(buf1, 0); err = writer1.OpenContainer(ProfileTag(TestProfile_1, 2), kTLVType_Structure, innerWriter1); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_BUFFER_TOO_SMALL); err = writer1.StartContainer(AnonymousTag, kTLVType_Array, container1); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_BUFFER_TOO_SMALL); // Test again all cases from 0 to the length of buf1 for (size_t maxLen = 0; maxLen <= sizeof(buf); maxLen++) { // Open/CloseContainer writer1.Init(buf, maxLen); err = writer1.OpenContainer(AnonymousTag, kTLVType_Array, innerWriter1); if (err == CHIP_NO_ERROR) err = innerWriter1.OpenContainer(AnonymousTag, kTLVType_Structure, innerWriter2); if (err == CHIP_NO_ERROR) err = innerWriter2.PutBoolean(ProfileTag(TestProfile_1, 2), true); if (err == CHIP_NO_ERROR) err = innerWriter1.CloseContainer(innerWriter2); if (err == CHIP_NO_ERROR) err = writer1.CloseContainer(innerWriter1); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_BUFFER_TOO_SMALL); // Start/EndContainer writer1.Init(buf, maxLen); if (err == CHIP_NO_ERROR) err = writer1.StartContainer(AnonymousTag, kTLVType_Array, container1); if (err == CHIP_NO_ERROR) err = writer1.StartContainer(AnonymousTag, kTLVType_Structure, container2); if (err == CHIP_NO_ERROR) err = writer1.PutBoolean(ProfileTag(TestProfile_1, 2), true); if (err == CHIP_NO_ERROR) err = writer1.EndContainer(container2); if (err == CHIP_NO_ERROR) err = writer1.EndContainer(container1); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_BUFFER_TOO_SMALL); } } static CHIP_ERROR ReadFuzzedEncoding1(nlTestSuite * inSuite, TLVReader & reader) { CHIP_ERROR err = CHIP_NO_ERROR; #define FUZZ_CHECK_VAL(TYPE, VAL) \ do \ { \ TYPE val; \ err = reader.Get(val); \ SuccessOrExit(err); \ VerifyOrExit(val == (VAL), err = CHIP_ERROR_INVALID_ARGUMENT); \ } while (0) #define FUZZ_CHECK_STRING(VAL) \ do \ { \ char buf[sizeof(VAL)]; \ VerifyOrExit(reader.GetLength() == strlen(VAL), err = CHIP_ERROR_INVALID_ADDRESS); \ err = reader.GetString(buf, sizeof(buf)); \ SuccessOrExit(err); \ VerifyOrExit(strcmp(buf, (VAL)) == 0, err = CHIP_ERROR_INVALID_ADDRESS); \ } while (0) err = reader.Next(kTLVType_Structure, ProfileTag(TestProfile_1, 1)); SuccessOrExit(err); { TLVType outerContainer1Type; err = reader.EnterContainer(outerContainer1Type); SuccessOrExit(err); err = reader.Next(kTLVType_Boolean, ProfileTag(TestProfile_1, 2)); SuccessOrExit(err); FUZZ_CHECK_VAL(bool, true); err = reader.Next(kTLVType_Boolean, ProfileTag(TestProfile_2, 2)); SuccessOrExit(err); FUZZ_CHECK_VAL(bool, false); err = reader.Next(kTLVType_Array, ContextTag(0)); SuccessOrExit(err); { TLVType outerContainer2Type; err = reader.EnterContainer(outerContainer2Type); SuccessOrExit(err); err = reader.Next(kTLVType_SignedInteger, AnonymousTag); SuccessOrExit(err); FUZZ_CHECK_VAL(int8_t, 42); FUZZ_CHECK_VAL(int16_t, 42); FUZZ_CHECK_VAL(int32_t, 42); FUZZ_CHECK_VAL(int64_t, 42); FUZZ_CHECK_VAL(uint8_t, 42); FUZZ_CHECK_VAL(uint16_t, 42); FUZZ_CHECK_VAL(uint32_t, 42); FUZZ_CHECK_VAL(uint64_t, 42); err = reader.Next(kTLVType_SignedInteger, AnonymousTag); SuccessOrExit(err); FUZZ_CHECK_VAL(int8_t, -17); FUZZ_CHECK_VAL(int16_t, -17); FUZZ_CHECK_VAL(int32_t, -17); FUZZ_CHECK_VAL(int64_t, -17); err = reader.Next(kTLVType_SignedInteger, AnonymousTag); SuccessOrExit(err); FUZZ_CHECK_VAL(int32_t, -170000); FUZZ_CHECK_VAL(int64_t, -170000); err = reader.Next(kTLVType_UnsignedInteger, AnonymousTag); SuccessOrExit(err); FUZZ_CHECK_VAL(int64_t, 40000000000ULL); FUZZ_CHECK_VAL(uint64_t, 40000000000ULL); err = reader.Next(kTLVType_Structure, AnonymousTag); SuccessOrExit(err); { TLVType outerContainer3Type; err = reader.EnterContainer(outerContainer3Type); SuccessOrExit(err); err = reader.ExitContainer(outerContainer3Type); SuccessOrExit(err); } err = reader.Next(kTLVType_Path, AnonymousTag); SuccessOrExit(err); { TLVType outerContainer3Type; err = reader.EnterContainer(outerContainer3Type); SuccessOrExit(err); err = reader.Next(kTLVType_Null, ProfileTag(TestProfile_1, 17)); SuccessOrExit(err); err = reader.Next(kTLVType_Null, ProfileTag(TestProfile_2, 900000)); SuccessOrExit(err); err = reader.Next(kTLVType_Null, AnonymousTag); SuccessOrExit(err); err = reader.Next(kTLVType_Structure, ProfileTag(TestProfile_2, 4000000000ULL)); SuccessOrExit(err); { TLVType outerContainer4Type; err = reader.EnterContainer(outerContainer4Type); SuccessOrExit(err); err = reader.Next(kTLVType_UTF8String, CommonTag(70000)); SuccessOrExit(err); FUZZ_CHECK_STRING(sLargeString); err = reader.ExitContainer(outerContainer4Type); SuccessOrExit(err); } err = reader.ExitContainer(outerContainer3Type); SuccessOrExit(err); } err = reader.ExitContainer(outerContainer2Type); SuccessOrExit(err); } err = reader.Next(kTLVType_UTF8String, ProfileTag(TestProfile_1, 5)); SuccessOrExit(err); FUZZ_CHECK_STRING("This is a test"); err = reader.Next(kTLVType_FloatingPointNumber, ProfileTag(TestProfile_2, 65535)); SuccessOrExit(err); FUZZ_CHECK_VAL(double, (float) 17.9); err = reader.Next(kTLVType_FloatingPointNumber, ProfileTag(TestProfile_2, 65536)); SuccessOrExit(err); FUZZ_CHECK_VAL(double, (double) 17.9); err = reader.ExitContainer(outerContainer1Type); SuccessOrExit(err); } err = reader.Next(); if (err == CHIP_END_OF_TLV) err = CHIP_NO_ERROR; exit: return err; } static uint32_t sFuzzTestDurationSecs = 5; static uint8_t sFixedFuzzMask = 0; static void TLVReaderFuzzTest(nlTestSuite * inSuite, void * inContext) { time_t now, endTime; uint8_t fuzzedData[sizeof(Encoding1)]; // clang-format off static uint8_t sFixedFuzzVals[] = { 0x00, 0x01, 0xFF, 0x20, // 1-byte signed integer with context tag 0x21, // 2-byte signed integer with context tag 0x22, // 4-byte signed integer with context tag 0x23, // 8-byte signed integer with context tag 0x24, // 1-byte unsigned integer with context tag 0x25, // 1-byte unsigned integer with context tag 0x26, // 1-byte unsigned integer with context tag 0x27, // 1-byte unsigned integer with context tag 0x28, // Boolean false with context tag 0x29, // Boolean true with context tag 0x27, // UTF-8 string with 1-byte length and context tag 0x30, // Byte string with 1-byte length and context tag 0x35, // Structure with context tag 0x36, // Array with context tag 0x18, // End of container }; // clang-format on memcpy(fuzzedData, Encoding1, sizeof(fuzzedData)); time(&now); endTime = now + sFuzzTestDurationSecs + 1; srand(now); size_t m = 0; while (true) { for (size_t i = 0; i < sizeof(fuzzedData); i++) { uint8_t origVal = fuzzedData[i]; if (m < sizeof(sFixedFuzzVals)) { if (origVal == sFixedFuzzVals[m]) continue; fuzzedData[i] = sFixedFuzzVals[m]; } else { uint8_t fuzzMask = sFixedFuzzMask; while (fuzzMask == 0) fuzzMask = GetRandU8(); fuzzedData[i] ^= fuzzMask; } TLVReader reader; reader.Init(fuzzedData, sizeof(fuzzedData)); reader.ImplicitProfileId = TestProfile_2; CHIP_ERROR readRes = ReadFuzzedEncoding1(inSuite, reader); NL_TEST_ASSERT(inSuite, readRes != CHIP_NO_ERROR); if (readRes == CHIP_NO_ERROR) { printf("Unexpected success of fuzz test: offset %u, original value 0x%02X, mutated value 0x%02X\n", (unsigned) i, (unsigned) origVal, (unsigned) fuzzedData[i]); ExitNow(); } time(&now); if (now >= endTime) ExitNow(); fuzzedData[i] = origVal; } if (m < sizeof(sFixedFuzzVals)) m++; } exit: return; } // Test Suite /** * Test Suite that lists all the test functions. */ // clang-format off static const nlTest sTests[] = { NL_TEST_DEF("Simple Write Read Test", CheckSimpleWriteRead), NL_TEST_DEF("Inet Buffer Test", CheckPacketBuffer), NL_TEST_DEF("Buffer Overflow Test", CheckBufferOverflow), NL_TEST_DEF("Pretty Print Test", CheckPrettyPrinter), NL_TEST_DEF("Data Macro Test", CheckDataMacro), NL_TEST_DEF("Strict Aliasing Test", CheckStrictAliasing), NL_TEST_DEF("CHIP TLV Basics", CheckCHIPTLVBasics), NL_TEST_DEF("CHIP TLV Writer", CheckCHIPTLVWriter), NL_TEST_DEF("CHIP TLV Reader", CheckCHIPTLVReader), NL_TEST_DEF("CHIP TLV Utilities", CheckCHIPTLVUtilities), NL_TEST_DEF("CHIP TLV Updater", CheckCHIPUpdater), NL_TEST_DEF("CHIP TLV Empty Find", CheckCHIPTLVEmptyFind), NL_TEST_DEF("CHIP Circular TLV buffer, simple", CheckCircularTLVBufferSimple), NL_TEST_DEF("CHIP Circular TLV buffer, mid-buffer start", CheckCircularTLVBufferStartMidway), NL_TEST_DEF("CHIP Circular TLV buffer, straddle", CheckCircularTLVBufferEvictStraddlingEvent), NL_TEST_DEF("CHIP Circular TLV buffer, edge", CheckCircularTLVBufferEdge), NL_TEST_DEF("CHIP TLV Printf", CheckCHIPTLVPutStringF), NL_TEST_DEF("CHIP TLV Printf, Circular TLV buf", CheckCHIPTLVPutStringFCircular), NL_TEST_DEF("CHIP TLV Skip non-contiguous", CheckCHIPTLVSkipCircular), NL_TEST_DEF("CHIP TLV Check reserve", CheckCloseContainerReserve), NL_TEST_DEF("CHIP TLV Reader Fuzz Test", TLVReaderFuzzTest), NL_TEST_SENTINEL() }; // clang-format on int TestCHIPTLV(void) { // clang-format off nlTestSuite theSuite = { "chip-tlv", &sTests[0], nullptr, nullptr }; // clang-format on TestTLVContext context; context.mSuite = &theSuite; // Run test suit against one context nlTestRunner(&theSuite, &context); return (nlTestRunnerStats(&theSuite)); } CHIP_REGISTER_TEST_SUITE(TestCHIPTLV)
33.085699
134
0.656791
simonlingoogle
8b3115b344ea66758e6d4c76caea1fc9e07cd806
434
cpp
C++
code/sandbox2.cpp
chistopher/scale-free-flow
2db5fe9563a459035b38b449a293aecbac32710f
[ "MIT" ]
null
null
null
code/sandbox2.cpp
chistopher/scale-free-flow
2db5fe9563a459035b38b449a293aecbac32710f
[ "MIT" ]
null
null
null
code/sandbox2.cpp
chistopher/scale-free-flow
2db5fe9563a459035b38b449a293aecbac32710f
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #include <ScopedTimer.hpp> #include <ProgressIndicator.hpp> #include <common.h> #include <utils.h> #include <Dinics.h> #include <BoykovKolmogorov.h> #include <ghtree.h> #include <girgs/Generator.h> #define rep(a, b) for(int a = 0; a < (b); ++a) #define all(a) (a).begin(),(a).end() //#define endl '\n' using namespace std; int main() { ios::sync_with_stdio(false); return 0; }
15.5
48
0.626728
chistopher
8b32451c1fe2c6d4d57ccedb008590f06ee40187
6,888
hpp
C++
adobe/manip.hpp
jaredwy/adobe_source_libraries
b71f5d08ab10396e9d2ba5e73861ca018f899a2d
[ "BSL-1.0" ]
252
2015-01-09T13:38:47.000Z
2022-03-30T09:02:01.000Z
adobe/manip.hpp
etiennemlb/adobe_source_libraries
5ced8bf61fbb487e9a2c6fa3ea7abc2687448c3b
[ "BSL-1.0" ]
37
2015-05-04T23:49:40.000Z
2022-01-22T18:31:51.000Z
adobe/manip.hpp
etiennemlb/adobe_source_libraries
5ced8bf61fbb487e9a2c6fa3ea7abc2687448c3b
[ "BSL-1.0" ]
59
2015-06-09T07:44:56.000Z
2022-01-22T17:35:05.000Z
/* Copyright 2013 Adobe 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 ADOBE_STD_SERIALIZATION /**************************************************************************************************/ #ifndef ADOBE_MANIP_HPP #define ADOBE_MANIP_HPP /**************************************************************************************************/ #include <adobe/config.hpp> #include <iostream> /**************************************************************************************************/ namespace adobe { /**************************************************************************************************/ /*! \addtogroup manipulator @{ */ class manipulator_base { public: manipulator_base() : error_m(std::ios_base::goodbit) {} protected: template <typename StreamType> std::ios_base::iostate handle_error(StreamType& strm) const { std::ios_base::iostate err(error_m); try { throw; } catch (std::bad_alloc&) { set_bad(); std::ios_base::iostate exception_mask(strm.exceptions()); if (exception_mask & std::ios_base::failbit && !(exception_mask & std::ios_base::badbit)) strm.setstate(err); else if (exception_mask & std::ios_base::badbit) { try { strm.setstate(err); } catch (std::ios_base::failure&) { } throw; } } catch (...) { set_fail(); std::ios_base::iostate exception_mask(strm.exceptions()); if ((exception_mask & std::ios_base::badbit) && (err & std::ios_base::badbit)) strm.setstate(err); else if (exception_mask & std::ios_base::failbit) { try { strm.setstate(err); } catch (std::ios_base::failure&) { } throw; } } return err; } void set_fail() const { error_m |= std::ios_base::failbit; } void set_bad() const { error_m |= std::ios_base::badbit; } mutable std::ios_base::iostate error_m; }; /**************************************************************************************************/ template <typename ArgumentType, class charT, class traits> class basic_omanipulator : public manipulator_base { public: typedef ArgumentType argument_type; typedef std::basic_ostream<charT, traits> stream_type; typedef stream_type& (*manip_func)(stream_type&, const ArgumentType&); basic_omanipulator(manip_func pf, const argument_type& arg) : pf_m(pf), arg_m(arg) {} void do_manip(stream_type& strm) const { if (error_m != std::ios_base::goodbit) strm.setstate(error_m); else { std::ios_base::iostate err(error_m); try { (*pf_m)(strm, arg_m); } catch (...) { err = handle_error(strm); } if (err) strm.setstate(err); } } private: manip_func pf_m; protected: argument_type arg_m; }; /**************************************************************************************************/ template <typename ArgumentType1, typename ArgumentType2, class charT, class traits> class basic_omanipulator2 : public manipulator_base { public: typedef ArgumentType1 argument_type_1; typedef ArgumentType2 argument_type_2; typedef std::basic_ostream<charT, traits> stream_type; typedef stream_type& (*manip_func)(stream_type&, const ArgumentType1&, const ArgumentType2&); basic_omanipulator2(manip_func pf, const ArgumentType1& arg1, const ArgumentType2& arg2) : pf_m(pf), arg1_m(arg1), arg2_m(arg2) {} void do_manip(stream_type& strm) const { if (error_m != std::ios_base::goodbit) strm.setstate(error_m); else { std::ios_base::iostate err(error_m); try { (*pf_m)(strm, arg1_m, arg2_m); } catch (...) { err = handle_error(strm); } if (err) strm.setstate(err); } } private: manip_func pf_m; protected: argument_type_1 arg1_m; argument_type_2 arg2_m; }; /**************************************************************************************************/ template <class ArgumentType, class charT, class traits> std::basic_ostream<charT, traits>& operator<<(std::basic_ostream<charT, traits>& os, const adobe::basic_omanipulator<ArgumentType, charT, traits>& manip) { if (os.good()) manip.do_manip(os); return os; } /**************************************************************************************************/ template <class ArgumentType1, class ArgumentType2, class charT, class traits> std::basic_ostream<charT, traits>& operator<<(std::basic_ostream<charT, traits>& os, const adobe::basic_omanipulator2<ArgumentType1, ArgumentType2, charT, traits>& manip) { if (os.good()) manip.do_manip(os); return os; } /**************************************************************************************************/ template <class charT, class traits> class basic_bounded_width : public basic_omanipulator<unsigned int, charT, traits> { typedef basic_omanipulator<unsigned int, charT, traits> inherited_t; public: typedef typename inherited_t::stream_type stream_type; typedef typename inherited_t::argument_type argument_type; basic_bounded_width(argument_type min, argument_type max) : basic_omanipulator<argument_type, charT, traits>(basic_bounded_width::fct, min), min_m(min), max_m(max) {} inherited_t& operator()(argument_type i) { inherited_t::arg_m = std::min(max_m, std::max(i, min_m)); return *this; } private: static stream_type& fct(stream_type& strm, const argument_type& i) { strm.width(i); return strm; } argument_type min_m; argument_type max_m; }; typedef basic_bounded_width<char, std::char_traits<char>> bounded_width; typedef basic_bounded_width<wchar_t, std::char_traits<wchar_t>> wbounded_width; //! @} /**************************************************************************************************/ } // namespace adobe /**************************************************************************************************/ #endif /**************************************************************************************************/ #endif /**************************************************************************************************/
30.210526
100
0.49187
jaredwy
8b35bbc7066416e55e21909e4033d774ab0d1c2f
5,453
cpp
C++
hphp/runtime/vm/jit/tc-debugger.cpp
thekid/hhvm
3f7d3bdde3cbab3b90dd0f156ae56445738432b1
[ "PHP-3.01", "Zend-2.0" ]
7
2015-08-28T06:20:50.000Z
2021-11-08T09:48:24.000Z
hphp/runtime/vm/jit/tc-debugger.cpp
thekid/hhvm
3f7d3bdde3cbab3b90dd0f156ae56445738432b1
[ "PHP-3.01", "Zend-2.0" ]
1
2020-01-19T19:06:32.000Z
2020-01-19T19:06:32.000Z
hphp/runtime/vm/jit/tc-debugger.cpp
profclems/hhvm
240f1370de88926a6c0760cc089b93b84bb0f88d
[ "PHP-3.01", "Zend-2.0" ]
3
2018-01-23T20:44:59.000Z
2021-05-06T12:45:31.000Z
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present 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 "hphp/runtime/vm/jit/tc.h" #include "hphp/runtime/vm/jit/tc-internal.h" #include "hphp/runtime/base/request-injection-data.h" #include "hphp/runtime/base/thread-info.h" #include "hphp/runtime/vm/srckey.h" #include "hphp/runtime/vm/jit/types.h" #include "hphp/runtime/vm/jit/abi.h" #include "hphp/runtime/vm/jit/code-gen-helpers.h" #include "hphp/runtime/vm/jit/code-gen-tls.h" #include "hphp/runtime/vm/jit/debugger.h" #include "hphp/runtime/vm/jit/smashable-instr.h" #include "hphp/runtime/vm/jit/srcdb.h" #include "hphp/runtime/vm/jit/translator-inline.h" #include "hphp/runtime/vm/jit/vasm-gen.h" #include "hphp/runtime/vm/jit/vasm-instr.h" #include "hphp/runtime/vm/jit/vasm-reg.h" #include "hphp/util/arch.h" #include "hphp/util/timer.h" TRACE_SET_MOD(mcg); namespace HPHP { namespace jit { namespace tc { namespace { void addDbgGuardImpl(SrcKey sk, SrcRec* sr, CodeBlock& cb, DataBlock& data, CGMeta& fixups) { TCA realCode = sr->getTopTranslation(); if (!realCode) return; // No translations, nothing to do. auto const dbgGuard = vwrap(cb, data, fixups, [&] (Vout& v) { if (!sk.resumed()) { auto const off = sr->nonResumedSPOff(); v << lea{rvmfp()[-cellsToBytes(off.offset)], rvmsp()}; } auto const tinfo = v.makeReg(); auto const attached = v.makeReg(); auto const sf = v.makeReg(); auto const done = v.makeBlock(); constexpr size_t dbgOff = offsetof(ThreadInfo, m_reqInjectionData) + RequestInjectionData::debuggerReadOnlyOffset(); v << ldimmq{reinterpret_cast<uintptr_t>(sk.pc()), rarg(0)}; emitTLSLoad(v, tls_datum(ThreadInfo::s_threadInfo), tinfo); v << loadb{tinfo[dbgOff], attached}; v << testbi{static_cast<int8_t>(0xffu), attached, sf}; v << jcci{CC_NZ, sf, done, ustubs().interpHelper}; v = done; v << fallthru{}; }, CodeKind::Helper); // Emit a jump to the actual code. auto const dbgBranchGuardSrc = emitSmashableJmp(cb, fixups, realCode); // Add the guard to the SrcRec. sr->addDebuggerGuard(dbgGuard, dbgBranchGuardSrc); } /////////////////////////////////////////////////////////////////////////////// } bool addDbgGuards(const Unit* unit) { // TODO refactor // It grabs the write lease and iterates through whole SrcDB... struct timespec tsBegin, tsEnd; { auto codeLock = lockCode(); auto metaLock = lockMetadata(); auto view = code().view(); auto& main = view.main(); auto& data = view.data(); HPHP::Timer::GetMonotonicTime(tsBegin); // Doc says even find _could_ invalidate iterator, in pactice it should // be very rare, so go with it now. CGMeta fixups; for (auto& pair : srcDB()) { SrcKey const sk = SrcKey::fromAtomicInt(pair.first); // We may have a SrcKey to a deleted function. NB: this may miss a // race with deleting a Func. See task #2826313. if (!Func::isFuncIdValid(sk.funcID())) continue; SrcRec* sr = pair.second; auto srLock = sr->writelock(); if (sr->unitMd5() == unit->md5() && !sr->hasDebuggerGuard() && isSrcKeyInDbgBL(sk)) { addDbgGuardImpl(sk, sr, main, data, fixups); } } fixups.process(nullptr); } HPHP::Timer::GetMonotonicTime(tsEnd); int64_t elapsed = gettime_diff_us(tsBegin, tsEnd); if (Trace::moduleEnabledRelease(Trace::mcg, 5)) { Trace::traceRelease("addDbgGuards got lease for %" PRId64 " us\n", elapsed); } return true; } bool addDbgGuardHelper(const Func* func, Offset offset, bool resumed, bool hasThis) { SrcKey sk{func, offset, resumed, hasThis}; if (auto const sr = srcDB().find(sk)) { if (sr->hasDebuggerGuard()) { return true; } } else { // no translation yet return true; } if (debug) { if (!isSrcKeyInDbgBL(sk)) { TRACE(5, "calling addDbgGuard on PC that is not in blacklist"); return false; } } auto codeLock = lockCode(); auto metaLock = lockMetadata(); CGMeta fixups; if (auto sr = srcDB().find(sk)) { auto view = code().view(); addDbgGuardImpl(sk, sr, view.main(), view.data(), fixups); } fixups.process(nullptr); return true; } bool addDbgGuard(const Func* func, Offset offset, bool resumed) { auto const ret = addDbgGuardHelper(func, offset, resumed, false); if (!ret || !func->cls() || func->isStatic()) return ret; return addDbgGuardHelper(func, offset, resumed, true); } }}}
33.048485
80
0.595085
thekid
8b3896a642293840201ab50be9ea48fe2cd83095
1,892
cpp
C++
codeforces/D - Barcelonian Distance/Wrong answer on test 9.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/D - Barcelonian Distance/Wrong answer on test 9.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/D - Barcelonian Distance/Wrong answer on test 9.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Nov/19/2018 01:59 * solution_verdict: Wrong answer on test 9 language: GNU C++14 * run_time: 15 ms memory_used: 100 KB * problem: https://codeforces.com/contest/1079/problem/D ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=1e5; double a,b,c,a1,a2,b1,b2; double _findy(double x) { return (-a*x-c)/b; } double _findx(double y) { return (-b*y-c)/a; } double dis(pair<double,double>p1,pair<double,double>p2) { return sqrt((p1.first-p2.first)*(p1.first-p2.first)+(p1.second-p2.second)*(p1.second-p2.second)); } int main() { ios_base::sync_with_stdio(0);cin.tie(0); cin>>a>>b>>c; cin>>a1>>b1>>a2>>b2; double ans=abs(a1-a2)+abs(b1-b2); if(!a||!b)cout<<ans<<endl,exit(0); pair<double,double>p1; p1.first=a1; p1.second=_findy(p1.first); pair<double,double>p2; p2.first=a2; p2.second=_findy(p2.first); ans=min(ans,dis(p1,p2)+abs(a1-p1.first)+abs(b1-p1.second)+abs(a2-p2.first)+abs(b2-p2.second)); p2.second=b2; p2.first=_findx(p2.second); ans=min(ans,dis(p1,p2)+abs(a1-p1.first)+abs(b1-p1.second)+abs(a2-p2.first)+abs(b2-p2.second)); p1.second=b1; p1.first=_findx(p1.second); p2.first=a2; p2.second=_findy(p2.first); ans=min(ans,dis(p1,p2)+abs(a1-p1.first)+abs(b1-p1.second)+abs(a2-p2.first)+abs(b2-p2.second)); p2.second=b2; p2.first=_findx(p2.second); ans=min(ans,dis(p1,p2)+abs(a1-p1.first)+abs(b1-p1.second)+abs(a2-p2.first)+abs(b2-p2.second)); cout<<setprecision(10)<<fixed<<ans<<endl; return 0; }
37.098039
111
0.541755
kzvd4729
8b3a2a34ecc89a46f56446af0008e7f5aaa6531f
765
cpp
C++
ad_map_access/impl/tests/generated/ad/map/route/LaneSegmentListTests.cpp
seowwj/map
2afacd50e1b732395c64b1884ccfaeeca0040ee7
[ "MIT" ]
null
null
null
ad_map_access/impl/tests/generated/ad/map/route/LaneSegmentListTests.cpp
seowwj/map
2afacd50e1b732395c64b1884ccfaeeca0040ee7
[ "MIT" ]
null
null
null
ad_map_access/impl/tests/generated/ad/map/route/LaneSegmentListTests.cpp
seowwj/map
2afacd50e1b732395c64b1884ccfaeeca0040ee7
[ "MIT" ]
1
2020-10-27T11:09:30.000Z
2020-10-27T11:09:30.000Z
/* * ----------------- BEGIN LICENSE BLOCK --------------------------------- * * Copyright (C) 2018-2020 Intel Corporation * * SPDX-License-Identifier: MIT * * ----------------- END LICENSE BLOCK ----------------------------------- */ /* * Generated file */ #if defined(__clang__) && (__clang_major__ >= 7) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wself-assign-overloaded" #endif #include <gtest/gtest.h> #include <limits> #include "ad/map/route/LaneSegmentList.hpp" TEST(LaneSegmentListTests, ostreamOperatorTest) { std::stringstream stream; ::ad::map::route::LaneSegmentList value; stream << value; ASSERT_GT(stream.str().size(), 0u); } #if defined(__clang__) && (__clang_major__ >= 7) #pragma GCC diagnostic pop #endif
21.857143
74
0.611765
seowwj
8b3e75e2817205050217d3acbc01c3f0f3733b43
19,601
cpp
C++
src/libtsduck/tsSDT.cpp
yrpark99/tsduck
2929092e42c5c7eec95a119af91cc09ffdde2028
[ "BSD-2-Clause" ]
null
null
null
src/libtsduck/tsSDT.cpp
yrpark99/tsduck
2929092e42c5c7eec95a119af91cc09ffdde2028
[ "BSD-2-Clause" ]
null
null
null
src/libtsduck/tsSDT.cpp
yrpark99/tsduck
2929092e42c5c7eec95a119af91cc09ffdde2028
[ "BSD-2-Clause" ]
null
null
null
//---------------------------------------------------------------------------- // // TSDuck - The MPEG Transport Stream Toolkit // Copyright (c) 2005-2018, Thierry Lelegard // 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. // // 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. // //---------------------------------------------------------------------------- // // Representation of a Service Description Table (SDT) // //---------------------------------------------------------------------------- #include "tsSDT.h" #include "tsRST.h" #include "tsNames.h" #include "tsBinaryTable.h" #include "tsTablesDisplay.h" #include "tsTablesFactory.h" #include "tsxmlElement.h" TSDUCK_SOURCE; #define MY_XML_NAME u"SDT" TS_XML_TABLE_FACTORY(ts::SDT, MY_XML_NAME); TS_ID_TABLE_FACTORY(ts::SDT, ts::TID_SDT_ACT); TS_ID_TABLE_FACTORY(ts::SDT, ts::TID_SDT_OTH); TS_ID_SECTION_DISPLAY(ts::SDT::DisplaySection, ts::TID_SDT_ACT); TS_ID_SECTION_DISPLAY(ts::SDT::DisplaySection, ts::TID_SDT_OTH); //---------------------------------------------------------------------------- // Constructors //---------------------------------------------------------------------------- ts::SDT::SDT(bool is_actual_, uint8_t version_, bool is_current_, uint16_t ts_id_, uint16_t onetw_id_) : AbstractLongTable(TID(is_actual_ ? TID_SDT_ACT : TID_SDT_OTH), MY_XML_NAME, version_, is_current_), ts_id(ts_id_), onetw_id(onetw_id_), services(this) { _is_valid = true; } ts::SDT::SDT(const BinaryTable& table, const DVBCharset* charset) : AbstractLongTable(TID_SDT_ACT, MY_XML_NAME), // TID will be updated by deserialize() ts_id(0), onetw_id(0), services(this) { deserialize(table, charset); } ts::SDT::SDT(const SDT& other) : AbstractLongTable(other), ts_id(other.ts_id), onetw_id(other.onetw_id), services(this, other.services) { } //---------------------------------------------------------------------------- // Search a service by name. //---------------------------------------------------------------------------- bool ts::SDT::findService(const UString& name, uint16_t& service_id, bool exact_match) const { for (ServiceMap::const_iterator it = services.begin(); it != services.end(); ++it) { const UString service_name(it->second.serviceName()); if ((exact_match && service_name == name) || (!exact_match && service_name.similar(name))) { service_id = it->first; return true; } } // Service not found service_id = 0; return false; } bool ts::SDT::findService(ts::Service& service, bool exact_match) const { uint16_t service_id = 0; if (!service.hasName() || !findService(service.getName(), service_id, exact_match)) { return false; } else { service.setId(service_id); return true; } } //---------------------------------------------------------------------------- // Deserialization //---------------------------------------------------------------------------- void ts::SDT::deserialize(const BinaryTable& table, const DVBCharset* charset) { // Clear table content _is_valid = false; ts_id = 0; onetw_id = 0; services.clear(); if (!table.isValid()) { return; } // Check table id: SDT Actual or Other if ((_table_id = table.tableId()) != TID_SDT_ACT && _table_id != TID_SDT_OTH) { return; } // Loop on all sections for (size_t si = 0; si < table.sectionCount(); ++si) { // Reference to current section const Section& sect (*table.sectionAt(si)); // Abort if not expected table if (sect.tableId() != _table_id) { return; } // Get common properties (should be identical in all sections) version = sect.version(); is_current = sect.isCurrent(); ts_id = sect.tableIdExtension(); // Analyze the section payload: const uint8_t* data (sect.payload()); size_t remain (sect.payloadSize()); // Get original_network_id (should be identical on all sections). // Note that there is one trailing reserved byte. if (remain < 3) { return; } onetw_id = GetUInt16 (data); data += 3; remain -= 3; // Get services description while (remain >= 5) { uint16_t service_id = GetUInt16 (data); Service& serv (services[service_id]); serv.EITs_present = (data[2] & 0x02) != 0; serv.EITpf_present = (data[2] & 0x01) != 0; serv.running_status = data[3] >> 5; serv.CA_controlled = (data[3] & 0x10) != 0; size_t info_length (GetUInt16 (data + 3) & 0x0FFF); data += 5; remain -= 5; info_length = std::min (info_length, remain); serv.descs.add (data, info_length); data += info_length; remain -= info_length; } } _is_valid = true; } //---------------------------------------------------------------------------- // Private method: Add a new section to a table being serialized. // Section number is incremented. Data and remain are reinitialized. //---------------------------------------------------------------------------- void ts::SDT::addSection(BinaryTable& table, int& section_number, uint8_t* payload, uint8_t*& data, size_t& remain) const { table.addSection(new Section(_table_id, true, // is_private_section ts_id, // tid_ext version, is_current, uint8_t(section_number), uint8_t(section_number), //last_section_number payload, data - payload)); // payload_size, // Reinitialize pointers. // Restart after constant part of payload (3 bytes). remain += data - payload - 3; data = payload + 3; section_number++; } //---------------------------------------------------------------------------- // Serialization //---------------------------------------------------------------------------- void ts::SDT::serialize(BinaryTable& table, const DVBCharset* charset) const { // Reinitialize table object table.clear(); // Return an empty table if not valid if (!_is_valid) { return; } // Build the sections uint8_t payload[MAX_PSI_LONG_SECTION_PAYLOAD_SIZE]; int section_number(0); uint8_t* data(payload); size_t remain(sizeof(payload)); // Add original_network_id and one reserved byte at beginning of the // payload (will remain identical in all sections). PutUInt16(data, onetw_id); data[2] = 0xFF; data += 3; remain -= 3; // Add all services for (ServiceMap::const_iterator it = services.begin(); it != services.end(); ++it) { const uint16_t service_id(it->first); const Service& serv(it->second); // If we cannot at least add the fixed part, open a new section if (remain < 5) { addSection(table, section_number, payload, data, remain); } // Insert the characteristics of the service. When the section is // not large enough to hold the entire descriptor list, open a // new section for the rest of the descriptors. In that case, the // common properties of the service must be repeated. bool starting(true); size_t start_index(0); while (starting || start_index < serv.descs.count()) { // If we are at the beginning of a service description, // make sure that the entire service description fits in // the section. If it does not fit, start a new section. // Note that huge service descriptions may not fit into // one section. In that case, the service description // will span two sections later. if (starting && 5 + serv.descs.binarySize() > remain) { addSection(table, section_number, payload, data, remain); } starting = false; // Insert common characteristics of the service assert(remain >= 5); PutUInt16(data, service_id); data[2] = 0xFC | (serv.EITs_present ? 0x02 : 0x00) | (serv.EITpf_present ? 0x01 : 0x00); data += 3; remain -= 3; // Insert descriptors (all or some). uint8_t* flags(data); start_index = serv.descs.lengthSerialize(data, remain, start_index); // The following fields are inserted in the 4 "reserved" bits // of the descriptor_loop_length. flags[0] = (flags[0] & 0x0F) | (serv.running_status << 5) | (serv.CA_controlled ? 0x10 : 0x00); // If not all descriptors were written, the section is full. // Open a new one and continue with this service. if (start_index < serv.descs.count()) { addSection(table, section_number, payload, data, remain); } } } // Add partial section (if there is one) if (data > payload + 3 || table.sectionCount() == 0) { addSection(table, section_number, payload, data, remain); } } //---------------------------------------------------------------------------- // Default constructor for SDT::Service //---------------------------------------------------------------------------- ts::SDT::Service::Service(const AbstractTable* table) : EntryWithDescriptors(table), EITs_present(false), EITpf_present(false), running_status(0), CA_controlled(false) { } //---------------------------------------------------------------------------- // Locate and deserialize the first DVB service_descriptor inside the entry. //---------------------------------------------------------------------------- bool ts::SDT::Service::locateServiceDescriptor(ServiceDescriptor& desc, const DVBCharset* charset) const { const size_t index = descs.search(DID_SERVICE); if (index >= descs.count()) { desc.invalidate(); return false; } else { assert(!descs[index].isNull()); desc.deserialize(*descs[index], charset); return desc.isValid(); } } //---------------------------------------------------------------------------- // Return the service type, service name and provider name (all found from // the first DVB "service descriptor", if there is one in the list). //---------------------------------------------------------------------------- uint8_t ts::SDT::Service::serviceType() const { ServiceDescriptor sd; return locateServiceDescriptor(sd) ? sd.service_type : 0; // 0 is a "reserved" service_type value } ts::UString ts::SDT::Service::providerName(const DVBCharset* charset) const { ServiceDescriptor sd; return locateServiceDescriptor(sd, charset) ? sd.provider_name : UString(); } ts::UString ts::SDT::Service::serviceName(const DVBCharset* charset) const { ServiceDescriptor sd; return locateServiceDescriptor(sd, charset) ? sd.service_name : UString(); } //---------------------------------------------------------------------------- // Set a string value (typically provider or service name). //---------------------------------------------------------------------------- void ts::SDT::Service::setString(UString ServiceDescriptor::* field, const UString& value, uint8_t service_type, const DVBCharset* charset) { // Locate the service descriptor const size_t index = descs.search(DID_SERVICE); if (index >= descs.count()) { // No valid service_descriptor, add a new one. ServiceDescriptor sd(service_type); sd.*field = value; DescriptorPtr dp(new Descriptor); CheckNonNull(dp.pointer()); sd.serialize(*dp, charset); if (dp->isValid()) { descs.add(dp); } } else { // Replace service name in existing descriptor assert(!descs[index].isNull()); ServiceDescriptor sd; sd.deserialize(*descs[index], charset); if (sd.isValid()) { sd.*field = value; sd.serialize(*descs[index], charset); } } } //---------------------------------------------------------------------------- // Modify the service_descriptor with the new service type. //---------------------------------------------------------------------------- void ts::SDT::Service::setType(uint8_t service_type) { // Locate the service descriptor const size_t index(descs.search(DID_SERVICE)); if (index >= descs.count() || descs[index]->payloadSize() < 2) { // No valid service_descriptor, add a new one. ByteBlock data(5); data[0] = DID_SERVICE; // tag data[1] = 3; // descriptor length data[2] = service_type; data[3] = 0; // provider name length data[4] = 0; // service name length descs.add(DescriptorPtr(new Descriptor(data))); } else if (descs[index]->payloadSize() > 0) { // Replace service type in existing descriptor uint8_t* payload = descs[index]->payload(); payload[0] = service_type; } } //---------------------------------------------------------------------------- // A static method to display a SDT section. //---------------------------------------------------------------------------- void ts::SDT::DisplaySection(TablesDisplay& display, const ts::Section& section, int indent) { std::ostream& strm(display.out()); const std::string margin(indent, ' '); const uint8_t* data = section.payload(); size_t size = section.payloadSize(); strm << margin << UString::Format(u"Transport Stream Id: %d (0x%X)", {section.tableIdExtension(), section.tableIdExtension()}) << std::endl; if (size >= 2) { uint16_t nwid = GetUInt16(data); strm << margin << UString::Format(u"Original Network Id: %d (0x%04X)", {nwid, nwid}) << std::endl; data += 2; size -= 2; if (size >= 1) { data += 1; size -= 1; // unused byte } // Loop across all services while (size >= 5) { uint16_t servid = GetUInt16(data); bool eits = (data[2] >> 1) & 0x01; bool eitpf = data[2] & 0x01; uint16_t length_bytes = GetUInt16(data + 3); uint8_t running_status = uint8_t(length_bytes >> 13); bool ca_mode = (length_bytes >> 12) & 0x01; size_t length = length_bytes & 0x0FFF; data += 5; size -= 5; if (length > size) { length = size; } strm << margin << UString::Format(u"Service Id: %d (0x%04X)", {servid, servid}) << ", EITs: " << UString::YesNo(eits) << ", EITp/f: " << UString::YesNo(eitpf) << ", CA mode: " << (ca_mode ? "controlled" : "free") << std::endl << margin << "Running status: " << names::RunningStatus(running_status) << std::endl; display.displayDescriptorList(data, length, indent, section.tableId()); data += length; size -= length; } } display.displayExtraData(data, size, indent); } //---------------------------------------------------------------------------- // XML serialization //---------------------------------------------------------------------------- void ts::SDT::buildXML(xml::Element* root) const { root->setIntAttribute(u"version", version); root->setBoolAttribute(u"current", is_current); root->setIntAttribute(u"transport_stream_id", ts_id, true); root->setIntAttribute(u"original_network_id", onetw_id, true); root->setBoolAttribute(u"actual", isActual()); for (ServiceMap::const_iterator it = services.begin(); it != services.end(); ++it) { xml::Element* e = root->addElement(u"service"); e->setIntAttribute(u"service_id", it->first, true); e->setBoolAttribute(u"EIT_schedule", it->second.EITs_present); e->setBoolAttribute(u"EIT_present_following", it->second.EITpf_present); e->setBoolAttribute(u"CA_mode", it->second.CA_controlled); e->setEnumAttribute(RST::RunningStatusNames, u"running_status", it->second.running_status); it->second.descs.toXML(e); } } //---------------------------------------------------------------------------- // XML deserialization //---------------------------------------------------------------------------- void ts::SDT::fromXML(const xml::Element* element) { services.clear(); xml::ElementVector children; bool actual = true; _is_valid = checkXMLName(element) && element->getIntAttribute<uint8_t>(version, u"version", false, 0, 0, 31) && element->getBoolAttribute(is_current, u"current", false, true) && element->getIntAttribute<uint16_t>(ts_id, u"transport_stream_id", true, 0, 0x0000, 0xFFFF) && element->getIntAttribute<uint16_t>(onetw_id, u"original_network_id", true, 0, 0x0000, 0xFFFF) && element->getBoolAttribute(actual, u"actual", false, true) && element->getChildren(children, u"service"); setActual(actual); for (size_t index = 0; _is_valid && index < children.size(); ++index) { uint16_t id = 0; int rs = 0; _is_valid = children[index]->getIntAttribute<uint16_t>(id, u"service_id", true, 0, 0x0000, 0xFFFF) && children[index]->getBoolAttribute(services[id].EITs_present, u"EIT_schedule", false, false) && children[index]->getBoolAttribute(services[id].EITpf_present, u"EIT_present_following", false, false) && children[index]->getBoolAttribute(services[id].CA_controlled, u"CA_mode", false, false) && children[index]->getEnumAttribute(rs, RST::RunningStatusNames, u"running_status", false, 0) && services[id].descs.fromXML(children[index]); if (_is_valid) { services[id].running_status = uint8_t(rs); } } }
36.433086
144
0.543646
yrpark99
8b3e89f7e1cb3cd9337b869dca27164abf6eb81b
1,044
cpp
C++
src/thunderbots/software/test/ai/passing/pass.cpp
FSXAC/Software
3754f5ec2c513906f66a05d4399aca516d03ba9f
[ "MIT" ]
null
null
null
src/thunderbots/software/test/ai/passing/pass.cpp
FSXAC/Software
3754f5ec2c513906f66a05d4399aca516d03ba9f
[ "MIT" ]
null
null
null
src/thunderbots/software/test/ai/passing/pass.cpp
FSXAC/Software
3754f5ec2c513906f66a05d4399aca516d03ba9f
[ "MIT" ]
null
null
null
/** * Tests for the "Pass" class */ #include "ai/passing/pass.h" #include <gtest/gtest.h> using namespace AI::Passing; TEST(PassTest, test_constructing_pass_with_negative_speed) { EXPECT_THROW(Pass(Point(1, 2), Point(3, 4), -0.1, Timestamp::fromSeconds(10)), std::invalid_argument); } TEST(PassTest, test_getters) { Pass p(Point(1, 2), Point(3, 4), 3.443, Timestamp::fromSeconds(10)); EXPECT_EQ(Point(1, 2), p.passerPoint()); EXPECT_EQ(Point(3, 4), p.receiverPoint()); EXPECT_EQ(3.443, p.speed()); EXPECT_DOUBLE_EQ(std::sqrt(8) / 3.443 + 10, p.estimateReceiveTime().getSeconds()); EXPECT_DOUBLE_EQ(std::sqrt(8) / 3.443, p.estimatePassDuration().getSeconds()); EXPECT_EQ(Timestamp::fromSeconds(10), p.startTime()); } TEST(PassTest, test_stream_operator) { Pass p(Point(1, 2), Point(3, 4), 99.97, Timestamp::fromSeconds(10)); std::stringstream out; out << p; EXPECT_EQ("Receiver: (3, 4), Passer: (1, 2) Speed (m/s): 99.97 Start Time (s): 10", out.str()); }
27.473684
87
0.641762
FSXAC
8b460be9f2d3b90dbc32c9b5a2bb05d21a4b4244
681
cpp
C++
src/libsasm/TokenStream.cpp
Galfodo/SIDdecompiler
aeda7aff18c8d61e5e0716a1301d4d3c52f12234
[ "MIT" ]
11
2019-03-13T12:38:39.000Z
2021-10-17T05:04:58.000Z
src/libsasm/TokenStream.cpp
Galfodo/SIDdecompiler
aeda7aff18c8d61e5e0716a1301d4d3c52f12234
[ "MIT" ]
null
null
null
src/libsasm/TokenStream.cpp
Galfodo/SIDdecompiler
aeda7aff18c8d61e5e0716a1301d4d3c52f12234
[ "MIT" ]
null
null
null
#include "TokenStream.h" #include <assert.h> namespace SASM { TokenStream::TokenStream(GetToken_pf pfGetToken, char const* pzData) : m_pfGetToken(pfGetToken), m_pzData(pzData), m_CachedToken(false) { assert(m_pfGetToken != NULL); } bool TokenStream::next(Token& token) { if (m_CachedToken) { token = m_NextToken; m_CachedToken = false; return true; } return m_pfGetToken(token, &m_pzData, false); } bool TokenStream::peek(Token& token) { if (m_CachedToken) { token = m_NextToken; return true; } else if (m_pfGetToken(m_NextToken, &m_pzData, false)) { m_CachedToken = true; token = m_NextToken; return true; } return false; } }
20.636364
137
0.690162
Galfodo
8b4839012406abfdf6796a20b83ec6518e84d7b7
29,625
cpp
C++
lib/Index/IndexDatastore.cpp
gmittert/indexstore-db
31ff487bd8d10531a9af761e4ecc1c929ccee2ff
[ "Apache-2.0" ]
null
null
null
lib/Index/IndexDatastore.cpp
gmittert/indexstore-db
31ff487bd8d10531a9af761e4ecc1c929ccee2ff
[ "Apache-2.0" ]
null
null
null
lib/Index/IndexDatastore.cpp
gmittert/indexstore-db
31ff487bd8d10531a9af761e4ecc1c929ccee2ff
[ "Apache-2.0" ]
null
null
null
//===--- IndexDatastore.cpp -----------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 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 "IndexDatastore.h" #include "StoreSymbolRecord.h" #include "IndexStoreDB/Core/Symbol.h" #include "IndexStoreDB/Index/FilePathIndex.h" #include "IndexStoreDB/Index/SymbolIndex.h" #include "IndexStoreDB/Index/IndexSystemDelegate.h" #include "IndexStoreDB/Database/Database.h" #include "IndexStoreDB/Database/DatabaseError.h" #include "IndexStoreDB/Database/ImportTransaction.h" #include "IndexStoreDB/Database/ReadTransaction.h" #include "IndexStoreDB/Support/FilePathWatcher.h" #include "IndexStoreDB/Support/Path.h" #include "IndexStoreDB/Support/Concurrency.h" #include "IndexStoreDB/Support/Logging.h" #include "indexstore/IndexStoreCXX.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Errc.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Mutex.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #include <dispatch/dispatch.h> #include <Block.h> #include <unordered_map> #include <unordered_set> // Dispatch on Linux doesn't have QOS_* macros. #if !__has_include(<sys/qos.h>) #define QOS_CLASS_UTILITY DISPATCH_QUEUE_PRIORITY_LOW #endif using namespace IndexStoreDB; using namespace IndexStoreDB::db; using namespace IndexStoreDB::index; using namespace indexstore; using namespace llvm; using namespace std::chrono; static sys::TimePoint<> toTimePoint(timespec ts) { auto time = time_point_cast<nanoseconds>(sys::toTimePoint(ts.tv_sec)); time += nanoseconds(ts.tv_nsec); return time; } const static dispatch_qos_class_t unitChangesQOS = QOS_CLASS_UTILITY; namespace { class UnitMonitor; struct UnitEventInfo { IndexStore::UnitEvent::Kind kind; std::string name; }; struct DoneInitState { std::atomic<bool> DoneInit{false}; }; class StoreUnitRepo : public std::enable_shared_from_this<StoreUnitRepo> { IndexStoreRef IdxStore; SymbolIndexRef SymIndex; std::shared_ptr<IndexSystemDelegate> Delegate; std::shared_ptr<CanonicalPathCache> CanonPathCache; std::shared_ptr<FilePathWatcher> PathWatcher; // This is shared so that it can be safely passed to an asynchronous block. std::shared_ptr<DoneInitState> DoneInitializingPtr; dispatch_semaphore_t InitSemaphore; dispatch_queue_t queueForUnitChanges; mutable llvm::sys::Mutex StateMtx; std::unordered_map<IDCode, std::shared_ptr<UnitMonitor>> UnitMonitorsByCode; public: StoreUnitRepo(IndexStoreRef IdxStore, SymbolIndexRef SymIndex, std::shared_ptr<IndexSystemDelegate> Delegate, std::shared_ptr<CanonicalPathCache> canonPathCache) : IdxStore(IdxStore), SymIndex(std::move(SymIndex)), Delegate(std::move(Delegate)), CanonPathCache(std::move(canonPathCache)) { DoneInitializingPtr = std::make_shared<DoneInitState>(); InitSemaphore = dispatch_semaphore_create(0); dispatch_queue_attr_t qosAttribute = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, unitChangesQOS, 0); queueForUnitChanges = dispatch_queue_create("IndexStoreDB.store.unit.processing", qosAttribute); } ~StoreUnitRepo() { dispatch_release(InitSemaphore); dispatch_release(queueForUnitChanges); } dispatch_queue_t getQueueForUnitChanges() const { return queueForUnitChanges; } void onFilesChange(std::vector<UnitEventInfo> evts, function_ref<void(unsigned)> ReportCompleted, function_ref<void()> DirectoryDeleted); void waitUntilDoneInitializing(); void purgeStaleData(); std::shared_ptr<UnitMonitor> getUnitMonitor(IDCode unitCode) const; void addUnitMonitor(IDCode unitCode, std::shared_ptr<UnitMonitor> monitor); void removeUnitMonitor(IDCode unitCode); void onUnitOutOfDate(IDCode unitCode, StringRef unitName, sys::TimePoint<> outOfDateModTime, OutOfDateTriggerHintRef hint, bool synchronous = false); void onFSEvent(std::vector<std::string> parentPaths); void checkUnitContainingFileIsOutOfDate(StringRef file); private: void registerUnit(StringRef UnitName); void removeUnit(StringRef UnitName); }; class IndexDatastoreImpl { IndexStoreRef IdxStore; std::shared_ptr<StoreUnitRepo> UnitRepo; public: bool init(IndexStoreRef idxStore, SymbolIndexRef SymIndex, std::shared_ptr<IndexSystemDelegate> Delegate, std::shared_ptr<CanonicalPathCache> CanonPathCache, bool readonly, std::string &Error); void waitUntilDoneInitializing(); bool isUnitOutOfDate(StringRef unitOutputPath, ArrayRef<StringRef> dirtyFiles); bool isUnitOutOfDate(StringRef unitOutputPath, llvm::sys::TimePoint<> outOfDateModTime); void checkUnitContainingFileIsOutOfDate(StringRef file); void purgeStaleData(); }; class UnitMonitor { struct OutOfDateTrigger { OutOfDateTriggerHintRef hint; sys::TimePoint<> outOfDateModTime; std::string getTriggerFilePath() const { return hint->originalFileTrigger(); } }; std::weak_ptr<StoreUnitRepo> UnitRepo; IDCode UnitCode; std::string UnitName; sys::TimePoint<> ModTime; mutable llvm::sys::Mutex StateMtx; /// Map of out-of-date file path to its associated info. StringMap<OutOfDateTrigger> OutOfDateTriggers; public: UnitMonitor(std::shared_ptr<StoreUnitRepo> unitRepo); void initialize(IDCode unitCode, StringRef UnitName, sys::TimePoint<> modTime, ArrayRef<CanonicalFilePath> userFileDepends, ArrayRef<IDCode> userUnitDepends); ~UnitMonitor(); StringRef getUnitName() const { return UnitName; } sys::TimePoint<> getModTime() const { return ModTime; } std::vector<OutOfDateTrigger> getOutOfDateTriggers() const; void checkForOutOfDate(sys::TimePoint<> outOfDateModTime, StringRef filePath, bool synchronous=false); void markOutOfDate(sys::TimePoint<> outOfDateModTime, OutOfDateTriggerHintRef hint, bool synchronous=false); static std::pair<StringRef, sys::TimePoint<>> getMostRecentModTime(ArrayRef<StringRef> filePaths); static sys::TimePoint<> getModTimeForOutOfDateCheck(StringRef filePath); }; } // anonymous namespace //===----------------------------------------------------------------------===// // StoreUnitRepo //===----------------------------------------------------------------------===// void StoreUnitRepo::onFilesChange(std::vector<UnitEventInfo> evts, function_ref<void(unsigned)> ReportCompleted, function_ref<void()> DirectoryDeleted) { auto guardForMapFullError = [&](function_ref<void()> block) { unsigned tries = 0; while (true) { try { ++tries; block(); break; } catch (db::MapFullError err) { // If we hit the map size limit try again but only for a limited number of times. if (tries > 4) { // If it still fails after doubling the map size 4 times then something is going // wrong so give up. LOG_WARN("guardForMapFullError", "Still MDB_MAP_FULL error after increasing map size, tries: " << tries); throw; } SymIndex->getDBase()->increaseMapSize(); // Try again. } } }; for (const auto &evt : evts) { guardForMapFullError([&]{ switch (evt.kind) { case IndexStore::UnitEvent::Kind::Added: registerUnit(evt.name); break; case IndexStore::UnitEvent::Kind::Removed: removeUnit(evt.name); break; case IndexStore::UnitEvent::Kind::Modified: registerUnit(evt.name); break; case IndexStore::UnitEvent::Kind::DirectoryDeleted: DirectoryDeleted(); break; } }); ReportCompleted(1); } // Can't just initialize this in the constructor because 'shared_from_this()' // cannot be called from a constructor. if (!PathWatcher) { std::weak_ptr<StoreUnitRepo> weakUnitRepo = shared_from_this(); auto pathEventsReceiver = [weakUnitRepo](std::vector<std::string> paths) { if (auto unitRepo = weakUnitRepo.lock()) { unitRepo->onFSEvent(std::move(paths)); } }; PathWatcher = std::make_shared<FilePathWatcher>(std::move(pathEventsReceiver)); } if (!DoneInitializingPtr->DoneInit) { dispatch_semaphore_signal(InitSemaphore); DoneInitializingPtr->DoneInit = true; } } void StoreUnitRepo::registerUnit(StringRef unitName) { std::string Error; auto optModTime = IdxStore->getUnitModificationTime(unitName, Error); if (!optModTime) { LOG_WARN_FUNC("error getting mod time for unit '" << unitName << "':" << Error); return; } auto unitModTime = toTimePoint(optModTime.getValue()); std::unique_ptr<IndexUnitReader> readerPtr; auto getUnitReader = [&]() -> IndexUnitReader& { if (!readerPtr) { readerPtr.reset(new IndexUnitReader(*IdxStore, unitName, Error)); if (readerPtr->isInvalid()) { LOG_WARN_FUNC("error loading unit '" << unitName << "':" << Error); } } return *readerPtr; }; IDCode unitCode; bool needDatabaseUpdate; Optional<bool> optIsSystem; IDCode PrevMainFileCode; IDCode PrevOutFileCode; Optional<StoreUnitInfo> StoreUnitInfoOpt; std::vector<CanonicalFilePath> UserFileDepends; std::vector<IDCode> UserUnitDepends; // Returns true if an error occurred. auto importUnit = [&]() -> bool { ImportTransaction import(SymIndex->getDBase()); UnitDataImport unitImport(import, unitName, unitModTime); unitCode = unitImport.getUnitCode(); needDatabaseUpdate = !unitImport.isUpToDate(); optIsSystem = unitImport.getIsSystem(); if (!needDatabaseUpdate) { PrevMainFileCode = unitImport.getPrevMainFileCode(); PrevOutFileCode = unitImport.getPrevOutFileCode(); return false; } auto &Reader = getUnitReader(); if (Reader.isInvalid()) return true; SymbolProviderKind symProviderKind = getSymbolProviderKindFromIdentifer(Reader.getProviderIdentifier()).getValue(); optIsSystem = Reader.isSystemUnit(); unitImport.setIsSystemUnit(optIsSystem.getValue()); unitImport.setSymbolProviderKind(symProviderKind); unitImport.setTarget(Reader.getTarget()); StringRef WorkDir = Reader.getWorkingDirectory(); CanonicalFilePath CanonMainFile; bool hasMainFile = Reader.hasMainFile(); if (hasMainFile) { CanonMainFile = CanonPathCache->getCanonicalPath(Reader.getMainFilePath(), WorkDir); unitImport.setMainFile(CanonMainFile); } CanonicalFilePath CanonOutFile = CanonPathCache->getCanonicalPath(Reader.getOutputFile(), WorkDir); unitImport.setOutFile(CanonOutFile); StoreUnitInfoOpt = StoreUnitInfo{unitName, CanonMainFile, CanonOutFile, unitModTime}; CanonicalFilePath CanonSysroot = CanonPathCache->getCanonicalPath(Reader.getSysrootPath(), WorkDir); unitImport.setSysroot(CanonSysroot); Reader.foreachDependency([&](IndexUnitDependency Dep)->bool { switch (Dep.getKind()) { case IndexUnitDependency::DependencyKind::Record: { CanonicalFilePath CanonPath = CanonPathCache->getCanonicalPath(Dep.getFilePath(), WorkDir); if (CanonPath.empty()) break; if (!Dep.isSystem()) UserFileDepends.push_back(CanonPath); StringRef recordName = Dep.getName(); bool isNewProvider; IDCode providerCode = unitImport.addProviderDependency(recordName, CanonPath, Dep.getModuleName(), Dep.isSystem(), &isNewProvider); if (!isNewProvider) break; std::string Error; auto Rec = StoreSymbolRecord::create(IdxStore, recordName, providerCode, symProviderKind, /*fileRefs=*/None); if (!Rec) { LOG_WARN_FUNC("error creating store symbol record: " << Error); break; } SymIndex->importSymbols(import, Rec); break; } case IndexUnitDependency::DependencyKind::Unit: { IDCode unitDepCode = unitImport.addUnitDependency(Dep.getName()); if (!Dep.isSystem()) UserUnitDepends.push_back(unitDepCode); break; } case IndexUnitDependency::DependencyKind::File: { CanonicalFilePath CanonPath = CanonPathCache->getCanonicalPath(Dep.getFilePath(), WorkDir); if (CanonPath.empty()) break; if (!Dep.isSystem()) UserFileDepends.push_back(CanonPath); unitImport.addFileDependency(CanonPath); } } return true; }); unitImport.commit(); import.commit(); return false; }; if (importUnit()) return; // error occurred; if (Delegate) { if (!StoreUnitInfoOpt.hasValue()) { ReadTransaction reader(SymIndex->getDBase()); CanonicalFilePath mainFile = reader.getFullFilePathFromCode(PrevMainFileCode); CanonicalFilePath outFile = reader.getFullFilePathFromCode(PrevOutFileCode); StoreUnitInfoOpt = StoreUnitInfo{unitName, mainFile, outFile, unitModTime}; } Delegate->processedStoreUnit(StoreUnitInfoOpt.getValue()); } if (*optIsSystem) return; // Monitor user files of the unit. // Get the user files if we didn't already go through them earlier. if (!needDatabaseUpdate) { auto &Reader = getUnitReader(); if (Reader.isInvalid()) return; StringRef WorkDir = Reader.getWorkingDirectory(); Reader.foreachDependency([&](IndexUnitDependency Dep)->bool { switch (Dep.getKind()) { case IndexUnitDependency::DependencyKind::Unit: if (!Dep.isSystem()) UserUnitDepends.push_back(makeIDCodeFromString(Dep.getName())); break; case IndexUnitDependency::DependencyKind::Record: case IndexUnitDependency::DependencyKind::File: { CanonicalFilePath CanonPath = CanonPathCache->getCanonicalPath(Dep.getFilePath(), WorkDir); if (CanonPath.empty()) break; if (!Dep.isSystem()) UserFileDepends.push_back(CanonPath); } } return true; }); } auto localThis = shared_from_this(); auto unitMonitor = std::make_shared<UnitMonitor>(localThis); unitMonitor->initialize(unitCode, unitName, unitModTime, UserFileDepends, UserUnitDepends); addUnitMonitor(unitCode, unitMonitor); } void StoreUnitRepo::removeUnit(StringRef unitName) { removeUnitMonitor(makeIDCodeFromString(unitName)); ImportTransaction import(SymIndex->getDBase()); import.removeUnitData(unitName); import.commit(); } void StoreUnitRepo::purgeStaleData() { // FIXME: Get referenced records from the database. // IdxStore->purgeStaleRecords(ActiveRecNames); } void StoreUnitRepo::waitUntilDoneInitializing() { if (DoneInitializingPtr->DoneInit) return; dispatch_semaphore_wait(InitSemaphore, DISPATCH_TIME_FOREVER); } std::shared_ptr<UnitMonitor> StoreUnitRepo::getUnitMonitor(IDCode unitCode) const { sys::ScopedLock L(StateMtx); auto It = UnitMonitorsByCode.find(unitCode); if (It != UnitMonitorsByCode.end()) return It->second; return nullptr; } void StoreUnitRepo::addUnitMonitor(IDCode unitCode, std::shared_ptr<UnitMonitor> monitor) { sys::ScopedLock L(StateMtx); UnitMonitorsByCode[unitCode] = monitor; } void StoreUnitRepo::removeUnitMonitor(IDCode unitCode) { sys::ScopedLock L(StateMtx); UnitMonitorsByCode.erase(unitCode); } void StoreUnitRepo::onUnitOutOfDate(IDCode unitCode, StringRef unitName, sys::TimePoint<> outOfDateModTime, OutOfDateTriggerHintRef hint, bool synchronous) { CanonicalFilePath MainFilePath; CanonicalFilePath OutFilePath; llvm::sys::TimePoint<> CurrModTime; SmallVector<IDCode, 8> dependentUnits; { ReadTransaction reader(SymIndex->getDBase()); auto unitInfo = reader.getUnitInfo(unitCode); if (!unitInfo.isInvalid()) { if (unitInfo.HasMainFile) { MainFilePath = reader.getFullFilePathFromCode(unitInfo.MainFileCode); } OutFilePath = reader.getFullFilePathFromCode(unitInfo.OutFileCode); CurrModTime = unitInfo.ModTime; } reader.getDirectDependentUnits(unitCode, dependentUnits); } if (!MainFilePath.empty() && Delegate) { StoreUnitInfo unitInfo{unitName, MainFilePath, OutFilePath, CurrModTime}; Delegate->unitIsOutOfDate(unitInfo, outOfDateModTime, hint, synchronous); } for (IDCode depUnit : dependentUnits) { if (auto monitor = getUnitMonitor(depUnit)) { if (monitor->getModTime() < outOfDateModTime) monitor->markOutOfDate(outOfDateModTime, DependentUnitOutOfDateTriggerHint::create(unitName, hint), synchronous); } } } void StoreUnitRepo::onFSEvent(std::vector<std::string> changedParentPaths) { std::vector<CanonicalFilePathRef> parentPathStrRefs; parentPathStrRefs.reserve(changedParentPaths.size()); for (auto &path : changedParentPaths) parentPathStrRefs.push_back(CanonicalFilePathRef::getAsCanonicalPath(path)); struct OutOfDateCheck { std::shared_ptr<UnitMonitor> Monitor; sys::TimePoint<> ModTime; CanonicalFilePath FilePath; }; std::vector<OutOfDateCheck> outOfDateChecks; { ReadTransaction reader(SymIndex->getDBase()); reader.findFilePathsWithParentPaths(parentPathStrRefs, [&](IDCode pathCode, CanonicalFilePathRef filePath) -> bool { // The timestamp that the file system returns has second precision, so if the file // was touched in less than a second after it got indexed, it will look like it is not actually dirty. // FIXME: Use modification-time + file-size to check for updated files. auto modTime = UnitMonitor::getModTimeForOutOfDateCheck(filePath.getPath()); reader.foreachUnitContainingFile(pathCode, [&](ArrayRef<IDCode> unitCodes) -> bool { for (IDCode unitCode : unitCodes) { if (auto monitor = getUnitMonitor(unitCode)) { outOfDateChecks.push_back(OutOfDateCheck{monitor, modTime, filePath}); } } return true; }); return true; }); } // We collect and call later to avoid nested read transactions. for (auto &check : outOfDateChecks) { check.Monitor->checkForOutOfDate(check.ModTime, check.FilePath.getPath()); } } void StoreUnitRepo::checkUnitContainingFileIsOutOfDate(StringRef filePath) { auto realPath = CanonPathCache->getCanonicalPath(filePath); filePath = realPath.getPath(); // The timestamp that the file system returns has second precision, so if the file // was touched in less than a second after it got indexed, it will look like it is not actually dirty. // FIXME: Use modification-time + file-size to check for updated files. auto modTime = UnitMonitor::getModTimeForOutOfDateCheck(filePath); std::vector<std::shared_ptr<UnitMonitor>> unitMonitors; { ReadTransaction reader(SymIndex->getDBase()); IDCode pathCode = reader.getFilePathCode(realPath); reader.foreachUnitContainingFile(pathCode, [&](ArrayRef<IDCode> unitCodes) -> bool { for (IDCode unitCode : unitCodes) { if (auto monitor = getUnitMonitor(unitCode)) { unitMonitors.push_back(std::move(monitor)); } } return true; }); } // We collect and call later to avoid nested read transactions. for (auto &unitMonitor : unitMonitors) { unitMonitor->checkForOutOfDate(modTime, filePath, /*synchronous=*/true); } } //===----------------------------------------------------------------------===// // UnitMonitor //===----------------------------------------------------------------------===// UnitMonitor::UnitMonitor(std::shared_ptr<StoreUnitRepo> unitRepo) { this->UnitRepo = unitRepo; } void UnitMonitor::initialize(IDCode unitCode, StringRef unitName, sys::TimePoint<> modTime, ArrayRef<CanonicalFilePath> userFileDepends, ArrayRef<IDCode> userUnitDepends) { auto unitRepo = this->UnitRepo.lock(); if (!unitRepo) return; this->UnitCode = unitCode; this->UnitName = unitName; this->ModTime = modTime; for (IDCode unitDepCode : userUnitDepends) { if (auto depMonitor = unitRepo->getUnitMonitor(unitDepCode)) { for (const auto &trigger : depMonitor->getOutOfDateTriggers()) { if (trigger.outOfDateModTime > modTime) { markOutOfDate(trigger.outOfDateModTime, DependentUnitOutOfDateTriggerHint::create(depMonitor->getUnitName(), trigger.hint)); } } } } SmallVector<StringRef, 32> filePaths; filePaths.reserve(userFileDepends.size()); for (const auto &canonPath : userFileDepends) { filePaths.push_back(canonPath.getPath()); } auto mostRecentFileAndTime = getMostRecentModTime(filePaths); if (mostRecentFileAndTime.second > modTime) { markOutOfDate(mostRecentFileAndTime.second, DependentFileOutOfDateTriggerHint::create(mostRecentFileAndTime.first)); return; } } UnitMonitor::~UnitMonitor() {} std::vector<UnitMonitor::OutOfDateTrigger> UnitMonitor::getOutOfDateTriggers() const { sys::ScopedLock L(StateMtx); std::vector<OutOfDateTrigger> triggers; for (const auto &entry : OutOfDateTriggers) { triggers.push_back(entry.getValue()); } return triggers; } void UnitMonitor::checkForOutOfDate(sys::TimePoint<> outOfDateModTime, StringRef filePath, bool synchronous) { sys::ScopedLock L(StateMtx); auto findIt = OutOfDateTriggers.find(filePath); if (findIt != OutOfDateTriggers.end() && findIt->getValue().outOfDateModTime >= outOfDateModTime) { return; // already marked as out-of-date related to this trigger file. } if (ModTime < outOfDateModTime) markOutOfDate(outOfDateModTime, DependentFileOutOfDateTriggerHint::create(filePath), synchronous); } void UnitMonitor::markOutOfDate(sys::TimePoint<> outOfDateModTime, OutOfDateTriggerHintRef hint, bool synchronous) { { sys::ScopedLock L(StateMtx); OutOfDateTrigger trigger{ hint, outOfDateModTime}; auto &entry = OutOfDateTriggers[trigger.getTriggerFilePath()]; if (entry.outOfDateModTime >= outOfDateModTime) return; // already marked as out-of-date related to this trigger file. entry = trigger; } if (auto localUnitRepo = UnitRepo.lock()) localUnitRepo->onUnitOutOfDate(UnitCode, UnitName, outOfDateModTime, hint, synchronous); } std::pair<StringRef, sys::TimePoint<>> UnitMonitor::getMostRecentModTime(ArrayRef<StringRef> filePaths) { sys::TimePoint<> mostRecentTime = sys::TimePoint<>::min(); StringRef mostRecentFile; auto checkModTime = [&](sys::TimePoint<> mod, StringRef filePath) { if (mod > mostRecentTime) { mostRecentTime = mod; mostRecentFile = filePath; } }; for (StringRef filePath : filePaths) { sys::fs::file_status fileStat; std::error_code EC = sys::fs::status(filePath, fileStat); sys::TimePoint<> currModTime = sys::TimePoint<>::min(); if (sys::fs::status_known(fileStat) && fileStat.type() == sys::fs::file_type::file_not_found) { // Make a recent time value so that we consider this out-of-date. currModTime = std::chrono::system_clock::now(); } else if (!EC) { currModTime = fileStat.getLastModificationTime(); } checkModTime(currModTime, filePath); } return std::make_pair(mostRecentFile, mostRecentTime); } sys::TimePoint<> UnitMonitor::getModTimeForOutOfDateCheck(StringRef filePath) { sys::fs::file_status fileStat; std::error_code EC = sys::fs::status(filePath, fileStat); sys::TimePoint<> modTime = sys::TimePoint<>::min(); if (sys::fs::status_known(fileStat) && fileStat.type() == sys::fs::file_type::file_not_found) { // Make a recent time value so that we consider this out-of-date. modTime = std::chrono::system_clock::now(); } else if (!EC) { modTime = fileStat.getLastModificationTime(); } return modTime; } //===----------------------------------------------------------------------===// // IndexDatastoreImpl //===----------------------------------------------------------------------===// bool IndexDatastoreImpl::init(IndexStoreRef idxStore, SymbolIndexRef SymIndex, std::shared_ptr<IndexSystemDelegate> Delegate, std::shared_ptr<CanonicalPathCache> CanonPathCache, bool readonly, std::string &Error) { this->IdxStore = std::move(idxStore); if (!this->IdxStore) return true; if (readonly) return false; auto UnitRepo = std::make_shared<StoreUnitRepo>(this->IdxStore, SymIndex, Delegate, CanonPathCache); std::weak_ptr<StoreUnitRepo> WeakUnitRepo = UnitRepo; auto OnUnitsChange = [WeakUnitRepo, Delegate](IndexStore::UnitEventNotification EventNote) { auto UnitRepo = WeakUnitRepo.lock(); if (!UnitRepo) return; std::vector<UnitEventInfo> evts; for (size_t i = 0, e = EventNote.getEventsCount(); i != e; ++i) { auto evt = EventNote.getEvent(i); evts.push_back(UnitEventInfo{evt.getKind(), evt.getUnitName()}); } // Create the block with QoS explicitly to ensure that the QoS from the indexstore callback can't affect the onFilesChange priority. This call may do a lot of I/O and we don't want to wedge the system by running at elevated priority. dispatch_block_t onUnitChangeBlock = dispatch_block_create_with_qos_class(DISPATCH_BLOCK_INHERIT_QOS_CLASS, unitChangesQOS, 0, ^{ Delegate->processingAddedPending(evts.size()); UnitRepo->onFilesChange(std::move(evts), [&](unsigned NumCompleted){ Delegate->processingCompleted(NumCompleted); }, [&](){ // FIXME: the database should recover. }); }); dispatch_async(UnitRepo->getQueueForUnitChanges(), onUnitChangeBlock); Block_release(onUnitChangeBlock); }; this->IdxStore->setUnitEventHandler(OnUnitsChange); bool err = this->IdxStore->startEventListening(/*waitInitialSync=*/false, Error); if (err) return true; this->UnitRepo = std::move(UnitRepo); return false; } void IndexDatastoreImpl::waitUntilDoneInitializing() { if (UnitRepo) UnitRepo->waitUntilDoneInitializing(); } bool IndexDatastoreImpl::isUnitOutOfDate(StringRef unitOutputPath, ArrayRef<StringRef> dirtyFiles) { auto mostRecentFileAndTime = UnitMonitor::getMostRecentModTime(dirtyFiles); return isUnitOutOfDate(unitOutputPath, mostRecentFileAndTime.second); } bool IndexDatastoreImpl::isUnitOutOfDate(StringRef unitOutputPath, sys::TimePoint<> outOfDateModTime) { SmallString<128> nameBuf; IdxStore->getUnitNameFromOutputPath(unitOutputPath, nameBuf); StringRef unitName = nameBuf.str(); std::string error; auto optUnitModTime = IdxStore->getUnitModificationTime(unitName, error); if (!optUnitModTime) return true; auto unitModTime = toTimePoint(optUnitModTime.getValue()); return outOfDateModTime > unitModTime; } void IndexDatastoreImpl::checkUnitContainingFileIsOutOfDate(StringRef file) { UnitRepo->checkUnitContainingFileIsOutOfDate(file); } void IndexDatastoreImpl::purgeStaleData() { UnitRepo->purgeStaleData(); } //===----------------------------------------------------------------------===// // IndexDatastore //===----------------------------------------------------------------------===// std::unique_ptr<IndexDatastore> IndexDatastore::create(IndexStoreRef idxStore, SymbolIndexRef SymIndex, std::shared_ptr<IndexSystemDelegate> Delegate, std::shared_ptr<CanonicalPathCache> CanonPathCache, bool readonly, std::string &Error) { std::unique_ptr<IndexDatastoreImpl> Impl(new IndexDatastoreImpl()); bool Err = Impl->init(std::move(idxStore), std::move(SymIndex), std::move(Delegate), std::move(CanonPathCache), readonly, Error); if (Err) return nullptr; std::unique_ptr<IndexDatastore> Store; Store.reset(new IndexDatastore(Impl.release())); return Store; } #define IMPL static_cast<IndexDatastoreImpl*>(Impl) IndexDatastore::~IndexDatastore() { delete IMPL; } void IndexDatastore::waitUntilDoneInitializing() { return IMPL->waitUntilDoneInitializing(); } bool IndexDatastore::isUnitOutOfDate(StringRef unitOutputPath, ArrayRef<StringRef> dirtyFiles) { return IMPL->isUnitOutOfDate(unitOutputPath, dirtyFiles); } bool IndexDatastore::isUnitOutOfDate(StringRef unitOutputPath, sys::TimePoint<> outOfDateModTime) { return IMPL->isUnitOutOfDate(unitOutputPath, outOfDateModTime); } void IndexDatastore::checkUnitContainingFileIsOutOfDate(StringRef file) { return IMPL->checkUnitContainingFileIsOutOfDate(file); } void IndexDatastore::purgeStaleData() { return IMPL->purgeStaleData(); }
36.084044
237
0.684489
gmittert
8b48f08041eabfd511df39a8badc93f1cb027293
11,984
cc
C++
test/syscalls/linux/itimer.cc
akhand9999/gvisor
001d57df10531208c048450c8e0bc4c5a9ec9caf
[ "Apache-2.0" ]
2
2021-02-23T03:14:54.000Z
2021-04-16T08:46:24.000Z
test/syscalls/linux/itimer.cc
akhand9999/gvisor
001d57df10531208c048450c8e0bc4c5a9ec9caf
[ "Apache-2.0" ]
8
2020-06-25T09:43:46.000Z
2022-03-31T01:01:00.000Z
test/syscalls/linux/itimer.cc
akhand9999/gvisor
001d57df10531208c048450c8e0bc4c5a9ec9caf
[ "Apache-2.0" ]
3
2021-02-08T17:44:27.000Z
2022-01-14T16:48:26.000Z
// Copyright 2018 The gVisor 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. #include <signal.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/types.h> #include <time.h> #include <atomic> #include <functional> #include <iostream> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/string_view.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "test/util/file_descriptor.h" #include "test/util/logging.h" #include "test/util/multiprocess_util.h" #include "test/util/posix_error.h" #include "test/util/signal_util.h" #include "test/util/test_util.h" #include "test/util/thread_util.h" #include "test/util/timer_util.h" namespace gvisor { namespace testing { namespace { constexpr char kSIGALRMToMainThread[] = "--itimer_sigarlm_to_main_thread"; constexpr char kSIGPROFFairnessActive[] = "--itimer_sigprof_fairness_active"; constexpr char kSIGPROFFairnessIdle[] = "--itimer_sigprof_fairness_idle"; // Time period to be set for the itimers. constexpr absl::Duration kPeriod = absl::Milliseconds(25); // Total amount of time to spend per thread. constexpr absl::Duration kTestDuration = absl::Seconds(20); // Amount of spin iterations to perform as the minimum work item per thread. // Chosen to be sub-millisecond range. constexpr int kIterations = 10000000; // Allow deviation in the number of samples. constexpr double kNumSamplesDeviationRatio = 0.2; TEST(ItimerTest, ItimervalUpdatedBeforeExpiration) { constexpr int kSleepSecs = 10; constexpr int kAlarmSecs = 15; static_assert( kSleepSecs < kAlarmSecs, "kSleepSecs must be less than kAlarmSecs for the test to be meaningful"); constexpr int kMaxRemainingSecs = kAlarmSecs - kSleepSecs; // Install a no-op handler for SIGALRM. struct sigaction sa = {}; sigfillset(&sa.sa_mask); sa.sa_handler = +[](int signo) {}; auto const cleanup_sa = ASSERT_NO_ERRNO_AND_VALUE(ScopedSigaction(SIGALRM, sa)); // Set an itimer-based alarm for kAlarmSecs from now. struct itimerval itv = {}; itv.it_value.tv_sec = kAlarmSecs; auto const cleanup_itimer = ASSERT_NO_ERRNO_AND_VALUE(ScopedItimer(ITIMER_REAL, itv)); // After sleeping for kSleepSecs, the itimer value should reflect the elapsed // time even if it hasn't expired. absl::SleepFor(absl::Seconds(kSleepSecs)); ASSERT_THAT(getitimer(ITIMER_REAL, &itv), SyscallSucceeds()); EXPECT_TRUE( itv.it_value.tv_sec < kMaxRemainingSecs || (itv.it_value.tv_sec == kMaxRemainingSecs && itv.it_value.tv_usec == 0)) << "Remaining time: " << itv.it_value.tv_sec << " seconds + " << itv.it_value.tv_usec << " microseconds"; } ABSL_CONST_INIT static thread_local std::atomic_int signal_test_num_samples = ATOMIC_VAR_INIT(0); void SignalTestSignalHandler(int /*signum*/) { signal_test_num_samples++; } struct SignalTestResult { int expected_total; int main_thread_samples; std::vector<int> worker_samples; }; std::ostream& operator<<(std::ostream& os, const SignalTestResult& r) { os << "{expected_total: " << r.expected_total << ", main_thread_samples: " << r.main_thread_samples << ", worker_samples: ["; bool first = true; for (int sample : r.worker_samples) { if (!first) { os << ", "; } os << sample; first = false; } os << "]}"; return os; } // Starts two worker threads and itimer id and measures the number of signal // delivered to each thread. SignalTestResult ItimerSignalTest(int id, clock_t main_clock, clock_t worker_clock, int signal, absl::Duration sleep) { signal_test_num_samples = 0; struct sigaction sa = {}; sa.sa_handler = &SignalTestSignalHandler; sa.sa_flags = SA_RESTART; sigemptyset(&sa.sa_mask); auto sigaction_cleanup = ScopedSigaction(signal, sa).ValueOrDie(); int socketfds[2]; TEST_PCHECK(socketpair(AF_UNIX, SOCK_STREAM, 0, socketfds) == 0); // Do the spinning in the workers. std::function<void*(int)> work = [&](int socket_fd) { FileDescriptor fd(socket_fd); absl::Time finish = Now(worker_clock) + kTestDuration; while (Now(worker_clock) < finish) { // Blocked on read. char c; RetryEINTR(read)(fd.get(), &c, 1); for (int i = 0; i < kIterations; i++) { // Ensure compiler won't optimize this loop away. asm(""); } if (sleep != absl::ZeroDuration()) { // Sleep so that the entire process is idle for a while. absl::SleepFor(sleep); } // Unblock the other thread. RetryEINTR(write)(fd.get(), &c, 1); } return reinterpret_cast<void*>(signal_test_num_samples.load()); }; ScopedThread th1( static_cast<std::function<void*()>>(std::bind(work, socketfds[0]))); ScopedThread th2( static_cast<std::function<void*()>>(std::bind(work, socketfds[1]))); absl::Time start = Now(main_clock); // Start the timer. struct itimerval timer = {}; timer.it_value = absl::ToTimeval(kPeriod); timer.it_interval = absl::ToTimeval(kPeriod); auto cleanup_itimer = ScopedItimer(id, timer).ValueOrDie(); // Unblock th1. // // N.B. th2 owns socketfds[1] but can't close it until it unblocks. char c = 0; TEST_CHECK(write(socketfds[1], &c, 1) == 1); SignalTestResult result; // Wait for the workers to be done and collect their sample counts. result.worker_samples.push_back(reinterpret_cast<int64_t>(th1.Join())); result.worker_samples.push_back(reinterpret_cast<int64_t>(th2.Join())); cleanup_itimer.Release()(); result.expected_total = (Now(main_clock) - start) / kPeriod; result.main_thread_samples = signal_test_num_samples.load(); return result; } int TestSIGALRMToMainThread() { SignalTestResult result = ItimerSignalTest(ITIMER_REAL, CLOCK_REALTIME, CLOCK_REALTIME, SIGALRM, absl::ZeroDuration()); std::cerr << "result: " << result << std::endl; // ITIMER_REAL-generated SIGALRMs prefer to deliver to the thread group leader // (but don't guarantee it), so we expect to see most samples on the main // thread. // // The number of SIGALRMs delivered to a worker should not exceed 20% // of the number of total signals expected (this is somewhat arbitrary). const int worker_threshold = result.expected_total / 5; // // Linux only guarantees timers will never expire before the requested time. // Thus, we only check the upper bound and also it at least have one sample. TEST_CHECK(result.main_thread_samples <= result.expected_total); TEST_CHECK(result.main_thread_samples > 0); for (int num : result.worker_samples) { TEST_CHECK_MSG(num <= worker_threshold, "worker received too many samples"); } return 0; } // Random save/restore is disabled as it introduces additional latency and // unpredictable distribution patterns. TEST(ItimerTest, DeliversSIGALRMToMainThread_NoRandomSave) { pid_t child; int execve_errno; auto kill = ASSERT_NO_ERRNO_AND_VALUE( ForkAndExec("/proc/self/exe", {"/proc/self/exe", kSIGALRMToMainThread}, {}, &child, &execve_errno)); EXPECT_EQ(0, execve_errno); int status; EXPECT_THAT(RetryEINTR(waitpid)(child, &status, 0), SyscallSucceedsWithValue(child)); // Not required anymore. kill.Release(); EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0) << status; } // Signals are delivered to threads fairly. // // sleep indicates how long to sleep worker threads each iteration to make the // entire process idle. int TestSIGPROFFairness(absl::Duration sleep) { SignalTestResult result = ItimerSignalTest(ITIMER_PROF, CLOCK_PROCESS_CPUTIME_ID, CLOCK_THREAD_CPUTIME_ID, SIGPROF, sleep); std::cerr << "result: " << result << std::endl; // The number of samples on the main thread should be very low as it did // nothing. TEST_CHECK(result.main_thread_samples < 60); // Both workers should get roughly equal number of samples. TEST_CHECK(result.worker_samples.size() == 2); TEST_CHECK(result.expected_total > 0); // In an ideal world each thread would get exactly 50% of the signals, // but since that's unlikely to happen we allow for them to get no less than // kNumSamplesDeviationRatio of the total observed samples. TEST_CHECK_MSG(std::abs(result.worker_samples[0] - result.worker_samples[1]) < ((result.worker_samples[0] + result.worker_samples[1]) * kNumSamplesDeviationRatio), "one worker received disproportionate share of samples"); return 0; } // Random save/restore is disabled as it introduces additional latency and // unpredictable distribution patterns. TEST(ItimerTest, DeliversSIGPROFToThreadsRoughlyFairlyActive_NoRandomSave) { // TODO(b/143247272): CPU time accounting is inaccurate for the KVM platform. SKIP_IF(GvisorPlatform() == Platform::kKVM); pid_t child; int execve_errno; auto kill = ASSERT_NO_ERRNO_AND_VALUE( ForkAndExec("/proc/self/exe", {"/proc/self/exe", kSIGPROFFairnessActive}, {}, &child, &execve_errno)); EXPECT_EQ(0, execve_errno); int status; EXPECT_THAT(RetryEINTR(waitpid)(child, &status, 0), SyscallSucceedsWithValue(child)); // Not required anymore. kill.Release(); EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0) << "Exited with code: " << status; } // Random save/restore is disabled as it introduces additional latency and // unpredictable distribution patterns. TEST(ItimerTest, DeliversSIGPROFToThreadsRoughlyFairlyIdle_NoRandomSave) { // TODO(b/143247272): CPU time accounting is inaccurate for the KVM platform. SKIP_IF(GvisorPlatform() == Platform::kKVM); pid_t child; int execve_errno; auto kill = ASSERT_NO_ERRNO_AND_VALUE( ForkAndExec("/proc/self/exe", {"/proc/self/exe", kSIGPROFFairnessIdle}, {}, &child, &execve_errno)); EXPECT_EQ(0, execve_errno); int status; EXPECT_THAT(RetryEINTR(waitpid)(child, &status, 0), SyscallSucceedsWithValue(child)); // Not required anymore. kill.Release(); EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0) << "Exited with code: " << status; } } // namespace } // namespace testing } // namespace gvisor namespace { void MaskSIGPIPE() { // Always mask SIGPIPE as it's common and tests aren't expected to handle it. // We don't take the TestInit() path so we must do this manually. struct sigaction sa = {}; sa.sa_handler = SIG_IGN; TEST_CHECK(sigaction(SIGPIPE, &sa, nullptr) == 0); } } // namespace int main(int argc, char** argv) { // These tests require no background threads, so check for them before // TestInit. for (int i = 0; i < argc; i++) { absl::string_view arg(argv[i]); if (arg == gvisor::testing::kSIGALRMToMainThread) { MaskSIGPIPE(); return gvisor::testing::TestSIGALRMToMainThread(); } if (arg == gvisor::testing::kSIGPROFFairnessActive) { MaskSIGPIPE(); return gvisor::testing::TestSIGPROFFairness(absl::ZeroDuration()); } if (arg == gvisor::testing::kSIGPROFFairnessIdle) { MaskSIGPIPE(); // Sleep time > ClockTick (10ms) exercises sleeping gVisor's // kernel.cpuClockTicker. return gvisor::testing::TestSIGPROFFairness(absl::Milliseconds(25)); } } gvisor::testing::TestInit(&argc, &argv); return gvisor::testing::RunAllTests(); }
33.853107
80
0.69743
akhand9999
8b4e007ede6494ab291587244a35e4a83d3db66b
25,541
cc
C++
db/column_family.cc
aginika/rocksdb
3d74f09979a2eadc1711a13ca4e221b53a6c44b3
[ "BSD-3-Clause" ]
null
null
null
db/column_family.cc
aginika/rocksdb
3d74f09979a2eadc1711a13ca4e221b53a6c44b3
[ "BSD-3-Clause" ]
null
null
null
db/column_family.cc
aginika/rocksdb
3d74f09979a2eadc1711a13ca4e221b53a6c44b3
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2013, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. // // Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include "db/column_family.h" #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #include <inttypes.h> #include <vector> #include <string> #include <algorithm> #include <limits> #include "db/db_impl.h" #include "db/version_set.h" #include "db/internal_stats.h" #include "db/compaction_picker.h" #include "db/table_properties_collector.h" #include "db/write_controller.h" #include "util/autovector.h" #include "util/hash_skiplist_rep.h" #include "util/options_helper.h" namespace rocksdb { namespace { // This function computes the amount of time in microseconds by which a write // should be delayed based on the number of level-0 files according to the // following formula: // if n < bottom, return 0; // if n >= top, return 1000; // otherwise, let r = (n - bottom) / // (top - bottom) // and return r^2 * 1000. // The goal of this formula is to gradually increase the rate at which writes // are slowed. We also tried linear delay (r * 1000), but it seemed to do // slightly worse. There is no other particular reason for choosing quadratic. uint64_t SlowdownAmount(int n, double bottom, double top) { uint64_t delay; if (n >= top) { delay = 1000; } else if (n < bottom) { delay = 0; } else { // If we are here, we know that: // level0_start_slowdown <= n < level0_slowdown // since the previous two conditions are false. double how_much = static_cast<double>(n - bottom) / (top - bottom); delay = std::max(how_much * how_much * 1000, 100.0); } assert(delay <= 1000); return delay; } } // namespace ColumnFamilyHandleImpl::ColumnFamilyHandleImpl(ColumnFamilyData* cfd, DBImpl* db, port::Mutex* mutex) : cfd_(cfd), db_(db), mutex_(mutex) { if (cfd_ != nullptr) { cfd_->Ref(); } } ColumnFamilyHandleImpl::~ColumnFamilyHandleImpl() { if (cfd_ != nullptr) { DBImpl::DeletionState deletion_state; mutex_->Lock(); if (cfd_->Unref()) { delete cfd_; } db_->FindObsoleteFiles(deletion_state, false, true); mutex_->Unlock(); if (deletion_state.HaveSomethingToDelete()) { db_->PurgeObsoleteFiles(deletion_state); } } } uint32_t ColumnFamilyHandleImpl::GetID() const { return cfd()->GetID(); } const Comparator* ColumnFamilyHandleImpl::user_comparator() const { return cfd()->user_comparator(); } ColumnFamilyOptions SanitizeOptions(const InternalKeyComparator* icmp, const ColumnFamilyOptions& src) { ColumnFamilyOptions result = src; result.comparator = icmp; #ifdef OS_MACOSX // TODO(icanadi) make write_buffer_size uint64_t instead of size_t ClipToRange(&result.write_buffer_size, ((size_t)64) << 10, ((size_t)1) << 30); #else ClipToRange(&result.write_buffer_size, ((size_t)64) << 10, ((size_t)64) << 30); #endif // if user sets arena_block_size, we trust user to use this value. Otherwise, // calculate a proper value from writer_buffer_size; if (result.arena_block_size <= 0) { result.arena_block_size = result.write_buffer_size / 10; } result.min_write_buffer_number_to_merge = std::min(result.min_write_buffer_number_to_merge, result.max_write_buffer_number - 1); result.compression_per_level = src.compression_per_level; if (result.max_mem_compaction_level >= result.num_levels) { result.max_mem_compaction_level = result.num_levels - 1; } if (result.soft_rate_limit > result.hard_rate_limit) { result.soft_rate_limit = result.hard_rate_limit; } if (result.max_write_buffer_number < 2) { result.max_write_buffer_number = 2; } if (!result.prefix_extractor) { assert(result.memtable_factory); Slice name = result.memtable_factory->Name(); if (name.compare("HashSkipListRepFactory") == 0 || name.compare("HashLinkListRepFactory") == 0) { result.memtable_factory = std::make_shared<SkipListFactory>(); } } // -- Sanitize the table properties collector // All user defined properties collectors will be wrapped by // UserKeyTablePropertiesCollector since for them they only have the // knowledge of the user keys; internal keys are invisible to them. auto& collector_factories = result.table_properties_collector_factories; for (size_t i = 0; i < result.table_properties_collector_factories.size(); ++i) { assert(collector_factories[i]); collector_factories[i] = std::make_shared<UserKeyTablePropertiesCollectorFactory>( collector_factories[i]); } // Add collector to collect internal key statistics collector_factories.push_back( std::make_shared<InternalKeyPropertiesCollectorFactory>()); if (result.compaction_style == kCompactionStyleFIFO) { result.num_levels = 1; // since we delete level0 files in FIFO compaction when there are too many // of them, these options don't really mean anything result.level0_file_num_compaction_trigger = std::numeric_limits<int>::max(); result.level0_slowdown_writes_trigger = std::numeric_limits<int>::max(); result.level0_stop_writes_trigger = std::numeric_limits<int>::max(); } return result; } int SuperVersion::dummy = 0; void* const SuperVersion::kSVInUse = &SuperVersion::dummy; void* const SuperVersion::kSVObsolete = nullptr; SuperVersion::~SuperVersion() { for (auto td : to_delete) { delete td; } } SuperVersion* SuperVersion::Ref() { refs.fetch_add(1, std::memory_order_relaxed); return this; } bool SuperVersion::Unref() { // fetch_sub returns the previous value of ref uint32_t previous_refs = refs.fetch_sub(1, std::memory_order_relaxed); assert(previous_refs > 0); return previous_refs == 1; } void SuperVersion::Cleanup() { assert(refs.load(std::memory_order_relaxed) == 0); imm->Unref(&to_delete); MemTable* m = mem->Unref(); if (m != nullptr) { to_delete.push_back(m); } current->Unref(); } void SuperVersion::Init(MemTable* new_mem, MemTableListVersion* new_imm, Version* new_current) { mem = new_mem; imm = new_imm; current = new_current; mem->Ref(); imm->Ref(); current->Ref(); refs.store(1, std::memory_order_relaxed); } namespace { void SuperVersionUnrefHandle(void* ptr) { // UnrefHandle is called when a thread exists or a ThreadLocalPtr gets // destroyed. When former happens, the thread shouldn't see kSVInUse. // When latter happens, we are in ~ColumnFamilyData(), no get should happen as // well. SuperVersion* sv = static_cast<SuperVersion*>(ptr); if (sv->Unref()) { sv->db_mutex->Lock(); sv->Cleanup(); sv->db_mutex->Unlock(); delete sv; } } } // anonymous namespace ColumnFamilyData::ColumnFamilyData(uint32_t id, const std::string& name, Version* dummy_versions, Cache* table_cache, const ColumnFamilyOptions& cf_options, const DBOptions* db_options, const EnvOptions& env_options, ColumnFamilySet* column_family_set) : id_(id), name_(name), dummy_versions_(dummy_versions), current_(nullptr), refs_(0), dropped_(false), internal_comparator_(cf_options.comparator), options_(*db_options, SanitizeOptions(&internal_comparator_, cf_options)), ioptions_(options_), mutable_cf_options_(options_), mem_(nullptr), imm_(options_.min_write_buffer_number_to_merge), super_version_(nullptr), super_version_number_(0), local_sv_(new ThreadLocalPtr(&SuperVersionUnrefHandle)), next_(nullptr), prev_(nullptr), log_number_(0), column_family_set_(column_family_set) { Ref(); // if dummy_versions is nullptr, then this is a dummy column family. if (dummy_versions != nullptr) { internal_stats_.reset( new InternalStats(options_.num_levels, db_options->env, this)); table_cache_.reset(new TableCache(ioptions_, env_options, table_cache)); if (options_.compaction_style == kCompactionStyleUniversal) { compaction_picker_.reset( new UniversalCompactionPicker(&options_, &internal_comparator_)); } else if (options_.compaction_style == kCompactionStyleLevel) { compaction_picker_.reset( new LevelCompactionPicker(&options_, &internal_comparator_)); } else { assert(options_.compaction_style == kCompactionStyleFIFO); compaction_picker_.reset( new FIFOCompactionPicker(&options_, &internal_comparator_)); } Log(options_.info_log, "Options for column family \"%s\":\n", name.c_str()); const ColumnFamilyOptions* cf_options = &options_; cf_options->Dump(options_.info_log.get()); } RecalculateWriteStallConditions(); } // DB mutex held ColumnFamilyData::~ColumnFamilyData() { assert(refs_ == 0); // remove from linked list auto prev = prev_; auto next = next_; prev->next_ = next; next->prev_ = prev; // it's nullptr for dummy CFD if (column_family_set_ != nullptr) { // remove from column_family_set column_family_set_->RemoveColumnFamily(this); } if (current_ != nullptr) { current_->Unref(); } if (super_version_ != nullptr) { // Release SuperVersion reference kept in ThreadLocalPtr. // This must be done outside of mutex_ since unref handler can lock mutex. super_version_->db_mutex->Unlock(); local_sv_.reset(); super_version_->db_mutex->Lock(); bool is_last_reference __attribute__((unused)); is_last_reference = super_version_->Unref(); assert(is_last_reference); super_version_->Cleanup(); delete super_version_; super_version_ = nullptr; } if (dummy_versions_ != nullptr) { // List must be empty assert(dummy_versions_->next_ == dummy_versions_); delete dummy_versions_; } if (mem_ != nullptr) { delete mem_->Unref(); } autovector<MemTable*> to_delete; imm_.current()->Unref(&to_delete); for (MemTable* m : to_delete) { delete m; } } void ColumnFamilyData::RecalculateWriteStallConditions() { if (current_ != nullptr) { const double score = current_->MaxCompactionScore(); const int max_level = current_->MaxCompactionScoreLevel(); auto write_controller = column_family_set_->write_controller_; if (imm()->size() == options_.max_write_buffer_number) { write_controller_token_ = write_controller->GetStopToken(); internal_stats_->AddCFStats(InternalStats::MEMTABLE_COMPACTION, 1); Log(options_.info_log, "[%s] Stopping writes because we have %d immutable memtables " "(waiting for flush)", name_.c_str(), imm()->size()); } else if (current_->NumLevelFiles(0) >= options_.level0_stop_writes_trigger) { write_controller_token_ = write_controller->GetStopToken(); internal_stats_->AddCFStats(InternalStats::LEVEL0_NUM_FILES, 1); Log(options_.info_log, "[%s] Stopping writes because we have %d level-0 files", name_.c_str(), current_->NumLevelFiles(0)); } else if (options_.level0_slowdown_writes_trigger >= 0 && current_->NumLevelFiles(0) >= options_.level0_slowdown_writes_trigger) { uint64_t slowdown = SlowdownAmount( current_->NumLevelFiles(0), options_.level0_slowdown_writes_trigger, options_.level0_stop_writes_trigger); write_controller_token_ = write_controller->GetDelayToken(slowdown); internal_stats_->AddCFStats(InternalStats::LEVEL0_SLOWDOWN, slowdown); Log(options_.info_log, "[%s] Stalling writes because we have %d level-0 files (%" PRIu64 "us)", name_.c_str(), current_->NumLevelFiles(0), slowdown); } else if (options_.hard_rate_limit > 1.0 && score > options_.hard_rate_limit) { uint64_t kHardLimitSlowdown = 1000; write_controller_token_ = write_controller->GetDelayToken(kHardLimitSlowdown); internal_stats_->RecordLevelNSlowdown(max_level, kHardLimitSlowdown, false); Log(options_.info_log, "[%s] Stalling writes because we hit hard limit on level %d. " "(%" PRIu64 "us)", name_.c_str(), max_level, kHardLimitSlowdown); } else if (options_.soft_rate_limit > 0.0 && score > options_.soft_rate_limit) { uint64_t slowdown = SlowdownAmount(score, options_.soft_rate_limit, options_.hard_rate_limit); write_controller_token_ = write_controller->GetDelayToken(slowdown); internal_stats_->RecordLevelNSlowdown(max_level, slowdown, true); Log(options_.info_log, "[%s] Stalling writes because we hit soft limit on level %d (%" PRIu64 "us)", name_.c_str(), max_level, slowdown); } else { write_controller_token_.reset(); } } } const EnvOptions* ColumnFamilyData::soptions() const { return &(column_family_set_->env_options_); } void ColumnFamilyData::SetCurrent(Version* current) { current_ = current; } void ColumnFamilyData::CreateNewMemtable(const MemTableOptions& moptions) { assert(current_ != nullptr); if (mem_ != nullptr) { delete mem_->Unref(); } mem_ = new MemTable(internal_comparator_, ioptions_, moptions); mem_->Ref(); } Compaction* ColumnFamilyData::PickCompaction(LogBuffer* log_buffer) { auto result = compaction_picker_->PickCompaction(current_, log_buffer); return result; } Compaction* ColumnFamilyData::CompactRange(int input_level, int output_level, uint32_t output_path_id, const InternalKey* begin, const InternalKey* end, InternalKey** compaction_end) { return compaction_picker_->CompactRange(current_, input_level, output_level, output_path_id, begin, end, compaction_end); } SuperVersion* ColumnFamilyData::GetReferencedSuperVersion( port::Mutex* db_mutex) { SuperVersion* sv = nullptr; if (LIKELY(column_family_set_->db_options_->allow_thread_local)) { sv = GetThreadLocalSuperVersion(db_mutex); sv->Ref(); if (!ReturnThreadLocalSuperVersion(sv)) { sv->Unref(); } } else { db_mutex->Lock(); sv = super_version_->Ref(); db_mutex->Unlock(); } return sv; } SuperVersion* ColumnFamilyData::GetThreadLocalSuperVersion( port::Mutex* db_mutex) { SuperVersion* sv = nullptr; // The SuperVersion is cached in thread local storage to avoid acquiring // mutex when SuperVersion does not change since the last use. When a new // SuperVersion is installed, the compaction or flush thread cleans up // cached SuperVersion in all existing thread local storage. To avoid // acquiring mutex for this operation, we use atomic Swap() on the thread // local pointer to guarantee exclusive access. If the thread local pointer // is being used while a new SuperVersion is installed, the cached // SuperVersion can become stale. In that case, the background thread would // have swapped in kSVObsolete. We re-check the value at when returning // SuperVersion back to thread local, with an atomic compare and swap. // The superversion will need to be released if detected to be stale. void* ptr = local_sv_->Swap(SuperVersion::kSVInUse); // Invariant: // (1) Scrape (always) installs kSVObsolete in ThreadLocal storage // (2) the Swap above (always) installs kSVInUse, ThreadLocal storage // should only keep kSVInUse before ReturnThreadLocalSuperVersion call // (if no Scrape happens). assert(ptr != SuperVersion::kSVInUse); sv = static_cast<SuperVersion*>(ptr); if (sv == SuperVersion::kSVObsolete || sv->version_number != super_version_number_.load()) { RecordTick(options_.statistics.get(), NUMBER_SUPERVERSION_ACQUIRES); SuperVersion* sv_to_delete = nullptr; if (sv && sv->Unref()) { RecordTick(options_.statistics.get(), NUMBER_SUPERVERSION_CLEANUPS); db_mutex->Lock(); // NOTE: underlying resources held by superversion (sst files) might // not be released until the next background job. sv->Cleanup(); sv_to_delete = sv; } else { db_mutex->Lock(); } sv = super_version_->Ref(); db_mutex->Unlock(); delete sv_to_delete; } assert(sv != nullptr); return sv; } bool ColumnFamilyData::ReturnThreadLocalSuperVersion(SuperVersion* sv) { assert(sv != nullptr); // Put the SuperVersion back void* expected = SuperVersion::kSVInUse; if (local_sv_->CompareAndSwap(static_cast<void*>(sv), expected)) { // When we see kSVInUse in the ThreadLocal, we are sure ThreadLocal // storage has not been altered and no Scrape has happend. The // SuperVersion is still current. return true; } else { // ThreadLocal scrape happened in the process of this GetImpl call (after // thread local Swap() at the beginning and before CompareAndSwap()). // This means the SuperVersion it holds is obsolete. assert(expected == SuperVersion::kSVObsolete); } return false; } SuperVersion* ColumnFamilyData::InstallSuperVersion( SuperVersion* new_superversion, port::Mutex* db_mutex) { db_mutex->AssertHeld(); return InstallSuperVersion(new_superversion, db_mutex, mutable_cf_options_); } SuperVersion* ColumnFamilyData::InstallSuperVersion( SuperVersion* new_superversion, port::Mutex* db_mutex, const MutableCFOptions& mutable_cf_options) { new_superversion->db_mutex = db_mutex; new_superversion->mutable_cf_options = mutable_cf_options; new_superversion->Init(mem_, imm_.current(), current_); SuperVersion* old_superversion = super_version_; super_version_ = new_superversion; ++super_version_number_; super_version_->version_number = super_version_number_; // Reset SuperVersions cached in thread local storage if (column_family_set_->db_options_->allow_thread_local) { ResetThreadLocalSuperVersions(); } RecalculateWriteStallConditions(); if (old_superversion != nullptr && old_superversion->Unref()) { old_superversion->Cleanup(); return old_superversion; // will let caller delete outside of mutex } return nullptr; } void ColumnFamilyData::ResetThreadLocalSuperVersions() { autovector<void*> sv_ptrs; local_sv_->Scrape(&sv_ptrs, SuperVersion::kSVObsolete); for (auto ptr : sv_ptrs) { assert(ptr); if (ptr == SuperVersion::kSVInUse) { continue; } auto sv = static_cast<SuperVersion*>(ptr); if (sv->Unref()) { sv->Cleanup(); delete sv; } } } bool ColumnFamilyData::SetOptions( const std::unordered_map<std::string, std::string>& options_map) { MutableCFOptions new_mutable_cf_options; if (GetMutableOptionsFromStrings(mutable_cf_options_, options_map, &new_mutable_cf_options)) { mutable_cf_options_ = new_mutable_cf_options; return true; } return false; } ColumnFamilySet::ColumnFamilySet(const std::string& dbname, const DBOptions* db_options, const EnvOptions& env_options, Cache* table_cache, WriteController* write_controller) : max_column_family_(0), dummy_cfd_(new ColumnFamilyData(0, "", nullptr, nullptr, ColumnFamilyOptions(), db_options, env_options, nullptr)), default_cfd_cache_(nullptr), db_name_(dbname), db_options_(db_options), env_options_(env_options), table_cache_(table_cache), write_controller_(write_controller), spin_lock_(ATOMIC_FLAG_INIT) { // initialize linked list dummy_cfd_->prev_ = dummy_cfd_; dummy_cfd_->next_ = dummy_cfd_; } ColumnFamilySet::~ColumnFamilySet() { while (column_family_data_.size() > 0) { // cfd destructor will delete itself from column_family_data_ auto cfd = column_family_data_.begin()->second; cfd->Unref(); delete cfd; } dummy_cfd_->Unref(); delete dummy_cfd_; } ColumnFamilyData* ColumnFamilySet::GetDefault() const { assert(default_cfd_cache_ != nullptr); return default_cfd_cache_; } ColumnFamilyData* ColumnFamilySet::GetColumnFamily(uint32_t id) const { auto cfd_iter = column_family_data_.find(id); if (cfd_iter != column_family_data_.end()) { return cfd_iter->second; } else { return nullptr; } } ColumnFamilyData* ColumnFamilySet::GetColumnFamily(const std::string& name) const { auto cfd_iter = column_families_.find(name); if (cfd_iter != column_families_.end()) { auto cfd = GetColumnFamily(cfd_iter->second); assert(cfd != nullptr); return cfd; } else { return nullptr; } } uint32_t ColumnFamilySet::GetNextColumnFamilyID() { return ++max_column_family_; } uint32_t ColumnFamilySet::GetMaxColumnFamily() { return max_column_family_; } void ColumnFamilySet::UpdateMaxColumnFamily(uint32_t new_max_column_family) { max_column_family_ = std::max(new_max_column_family, max_column_family_); } size_t ColumnFamilySet::NumberOfColumnFamilies() const { return column_families_.size(); } // under a DB mutex ColumnFamilyData* ColumnFamilySet::CreateColumnFamily( const std::string& name, uint32_t id, Version* dummy_versions, const ColumnFamilyOptions& options) { assert(column_families_.find(name) == column_families_.end()); ColumnFamilyData* new_cfd = new ColumnFamilyData(id, name, dummy_versions, table_cache_, options, db_options_, env_options_, this); Lock(); column_families_.insert({name, id}); column_family_data_.insert({id, new_cfd}); Unlock(); max_column_family_ = std::max(max_column_family_, id); // add to linked list new_cfd->next_ = dummy_cfd_; auto prev = dummy_cfd_->prev_; new_cfd->prev_ = prev; prev->next_ = new_cfd; dummy_cfd_->prev_ = new_cfd; if (id == 0) { default_cfd_cache_ = new_cfd; } return new_cfd; } void ColumnFamilySet::Lock() { // spin lock while (spin_lock_.test_and_set(std::memory_order_acquire)) { } } void ColumnFamilySet::Unlock() { spin_lock_.clear(std::memory_order_release); } // REQUIRES: DB mutex held void ColumnFamilySet::FreeDeadColumnFamilies() { autovector<ColumnFamilyData*> to_delete; for (auto cfd = dummy_cfd_->next_; cfd != dummy_cfd_; cfd = cfd->next_) { if (cfd->refs_ == 0) { to_delete.push_back(cfd); } } for (auto cfd : to_delete) { // this is very rare, so it's not a problem that we do it under a mutex delete cfd; } } // under a DB mutex void ColumnFamilySet::RemoveColumnFamily(ColumnFamilyData* cfd) { auto cfd_iter = column_family_data_.find(cfd->GetID()); assert(cfd_iter != column_family_data_.end()); Lock(); column_family_data_.erase(cfd_iter); column_families_.erase(cfd->GetName()); Unlock(); } bool ColumnFamilyMemTablesImpl::Seek(uint32_t column_family_id) { if (column_family_id == 0) { // optimization for common case current_ = column_family_set_->GetDefault(); } else { // maybe outside of db mutex, should lock column_family_set_->Lock(); current_ = column_family_set_->GetColumnFamily(column_family_id); column_family_set_->Unlock(); // TODO(icanadi) Maybe remove column family from the hash table when it's // dropped? if (current_ != nullptr && current_->IsDropped()) { current_ = nullptr; } } handle_.SetCFD(current_); return current_ != nullptr; } uint64_t ColumnFamilyMemTablesImpl::GetLogNumber() const { assert(current_ != nullptr); return current_->GetLogNumber(); } MemTable* ColumnFamilyMemTablesImpl::GetMemTable() const { assert(current_ != nullptr); return current_->mem(); } const Options* ColumnFamilyMemTablesImpl::GetOptions() const { assert(current_ != nullptr); return current_->options(); } ColumnFamilyHandle* ColumnFamilyMemTablesImpl::GetColumnFamilyHandle() { assert(current_ != nullptr); return &handle_; } void ColumnFamilyMemTablesImpl::CheckMemtableFull() { if (current_ != nullptr && current_->mem()->ShouldScheduleFlush()) { flush_scheduler_->ScheduleFlush(current_); current_->mem()->MarkFlushScheduled(); } } uint32_t GetColumnFamilyID(ColumnFamilyHandle* column_family) { uint32_t column_family_id = 0; if (column_family != nullptr) { auto cfh = reinterpret_cast<ColumnFamilyHandleImpl*>(column_family); column_family_id = cfh->GetID(); } return column_family_id; } const Comparator* GetColumnFamilyUserComparator( ColumnFamilyHandle* column_family) { if (column_family != nullptr) { auto cfh = reinterpret_cast<ColumnFamilyHandleImpl*>(column_family); return cfh->user_comparator(); } return nullptr; } } // namespace rocksdb
34.375505
80
0.688266
aginika
8b4fbb23dd395ae1e1f0788fc5afddf14565361d
2,800
cpp
C++
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcEdgeLoop.cpp
AlexVlk/ifcplusplus
2f8cd5457312282b8d90b261dbf8fb66e1c84057
[ "MIT" ]
426
2015-04-12T10:00:46.000Z
2022-03-29T11:03:02.000Z
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcEdgeLoop.cpp
AlexVlk/ifcplusplus
2f8cd5457312282b8d90b261dbf8fb66e1c84057
[ "MIT" ]
124
2015-05-15T05:51:00.000Z
2022-02-09T15:25:12.000Z
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcEdgeLoop.cpp
AlexVlk/ifcplusplus
2f8cd5457312282b8d90b261dbf8fb66e1c84057
[ "MIT" ]
214
2015-05-06T07:30:37.000Z
2022-03-26T16:14:04.000Z
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */ #include <sstream> #include <limits> #include "ifcpp/model/AttributeObject.h" #include "ifcpp/model/BuildingException.h" #include "ifcpp/model/BuildingGuid.h" #include "ifcpp/reader/ReaderUtil.h" #include "ifcpp/writer/WriterUtil.h" #include "ifcpp/IFC4/include/IfcEdgeLoop.h" #include "ifcpp/IFC4/include/IfcOrientedEdge.h" #include "ifcpp/IFC4/include/IfcPresentationLayerAssignment.h" #include "ifcpp/IFC4/include/IfcStyledItem.h" // ENTITY IfcEdgeLoop IfcEdgeLoop::IfcEdgeLoop( int id ) { m_entity_id = id; } shared_ptr<BuildingObject> IfcEdgeLoop::getDeepCopy( BuildingCopyOptions& options ) { shared_ptr<IfcEdgeLoop> copy_self( new IfcEdgeLoop() ); for( size_t ii=0; ii<m_EdgeList.size(); ++ii ) { auto item_ii = m_EdgeList[ii]; if( item_ii ) { copy_self->m_EdgeList.emplace_back( dynamic_pointer_cast<IfcOrientedEdge>(item_ii->getDeepCopy(options) ) ); } } return copy_self; } void IfcEdgeLoop::getStepLine( std::stringstream& stream ) const { stream << "#" << m_entity_id << "= IFCEDGELOOP" << "("; writeEntityList( stream, m_EdgeList ); stream << ");"; } void IfcEdgeLoop::getStepParameter( std::stringstream& stream, bool /*is_select_type*/ ) const { stream << "#" << m_entity_id; } const std::wstring IfcEdgeLoop::toString() const { return L"IfcEdgeLoop"; } void IfcEdgeLoop::readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<BuildingEntity> >& map ) { const size_t num_args = args.size(); if( num_args != 1 ){ std::stringstream err; err << "Wrong parameter count for entity IfcEdgeLoop, expecting 1, having " << num_args << ". Entity ID: " << m_entity_id << std::endl; throw BuildingException( err.str().c_str() ); } readEntityReferenceList( args[0], m_EdgeList, map ); } void IfcEdgeLoop::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const { IfcLoop::getAttributes( vec_attributes ); if( !m_EdgeList.empty() ) { shared_ptr<AttributeObjectVector> EdgeList_vec_object( new AttributeObjectVector() ); std::copy( m_EdgeList.begin(), m_EdgeList.end(), std::back_inserter( EdgeList_vec_object->m_vec ) ); vec_attributes.emplace_back( std::make_pair( "EdgeList", EdgeList_vec_object ) ); } } void IfcEdgeLoop::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes_inverse ) const { IfcLoop::getAttributesInverse( vec_attributes_inverse ); } void IfcEdgeLoop::setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self_entity ) { IfcLoop::setInverseCounterparts( ptr_self_entity ); } void IfcEdgeLoop::unlinkFromInverseCounterparts() { IfcLoop::unlinkFromInverseCounterparts(); }
42.424242
229
0.732857
AlexVlk
332b3eee53dda3c23b959ffe64a4e96d0da94a1b
592
cpp
C++
lab_08/src/pixelate.cpp
srafi1/csci13600-labs-1
60081dced2c237f6843b28f335db9a4ed56a8ac2
[ "BSD-3-Clause" ]
null
null
null
lab_08/src/pixelate.cpp
srafi1/csci13600-labs-1
60081dced2c237f6843b28f335db9a4ed56a8ac2
[ "BSD-3-Clause" ]
2
2018-11-15T17:15:08.000Z
2018-11-20T18:14:33.000Z
lab_08/src/pixelate.cpp
srafi1/csci13600-labs-1
60081dced2c237f6843b28f335db9a4ed56a8ac2
[ "BSD-3-Clause" ]
4
2018-11-08T15:05:15.000Z
2018-12-14T04:08:49.000Z
#include <array> #include "main.hpp" constexpr std::array<std::array<size_t, 2>, 4> offsets = {{{0, 0}, {0, 1}, {1, 0}, {1, 1}}}; void pixelate(std::vector<std::vector<int> >& muhimage) { for (size_t i = 0; i < muhimage.size() / 2; i++) { for (size_t j = 0; j < muhimage[0].size() / 2; j++) { int a = 0; size_t x = i * 2; size_t y = j * 2; for (std::array<size_t, 2> o : offsets) { a += muhimage[x + o[0]][y + o[1]]; } a /= 4; for (std::array<size_t, 2> o : offsets) { muhimage[x + o[0]][y + o[1]] = a; } } } }
23.68
92
0.464527
srafi1
332b65d32a5a7ad25b371e4d8e23a6bd4bc0aa81
1,587
cpp
C++
basicVoltmeter-textbook-example/basicIOCmd.cpp
betaghIEEE/stm32-mbed-tutorials
fe4f4c37e8e58f4e1e5707231fd5de8759cfe02b
[ "Apache-2.0" ]
null
null
null
basicVoltmeter-textbook-example/basicIOCmd.cpp
betaghIEEE/stm32-mbed-tutorials
fe4f4c37e8e58f4e1e5707231fd5de8759cfe02b
[ "Apache-2.0" ]
null
null
null
basicVoltmeter-textbook-example/basicIOCmd.cpp
betaghIEEE/stm32-mbed-tutorials
fe4f4c37e8e58f4e1e5707231fd5de8759cfe02b
[ "Apache-2.0" ]
null
null
null
#include "basicIOCmd.h" #include "BufferedSerial.h" #include "mbed.h" #include "unity_internals.h" // // Clear the screen // BufferedSerial myPC(USBTX, USBRX, 9600); #define BLINKING_RATE_MS 1000 #define BUFFER_SIZE 1000 extern void wait_seconds (int seconds){ int wait_ms = seconds * BLINKING_RATE_MS; thread_sleep_for(wait_ms); } extern void wait_milliseconds (int ms){ thread_sleep_for(ms); } void wait (float delay){ int blinkValue = floor(delay * BLINKING_RATE_MS); //wait_us(blinkValue); thread_sleep_for(blinkValue); } void clrscr() { char clrscr[] = {0x1B, '[', '2' , 'J',0}; printf("%s", clrscr); } // // Home the cursor // void homescr() { char homescr[] = {0x1B, '[' , 'H' , 0}; printf("%s", homescr); } // // Goto specified line and column // void gotoscr(int line, int column) { char scr[] = {0x1B, '[', 0x00, ';' ,0x00, 'H', 0}; scr[2] = line; scr[4] = column; printf("%s", scr); fflush(stdout); } void printFloat ( float t){ gotoscr(4, 3); int count = floor(t * 1000); printf("The count is %d /1000", count ); fflush(stdout); } void printVoltage(float t ) { gotoscr(8, 3); int count = floor(t * 1000); printf("The Voltage is %d try %5.3f", count, t ); char buffer[BUFFER_SIZE]; fflush(stdout); }
18.670588
80
0.512287
betaghIEEE
332c2fd96835af8eb8273fc7d64ecef07627c345
4,320
cpp
C++
aws-cpp-sdk-application-autoscaling/source/model/ScalableTarget.cpp
grujicbr/aws-sdk-cpp
bdd43c178042f09c6739645e3f6cd17822a7c35c
[ "Apache-2.0" ]
1
2020-03-11T05:36:20.000Z
2020-03-11T05:36:20.000Z
aws-cpp-sdk-application-autoscaling/source/model/ScalableTarget.cpp
novaquark/aws-sdk-cpp
a0969508545bec9ae2864c9e1e2bb9aff109f90c
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-application-autoscaling/source/model/ScalableTarget.cpp
novaquark/aws-sdk-cpp
a0969508545bec9ae2864c9e1e2bb9aff109f90c
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/application-autoscaling/model/ScalableTarget.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace ApplicationAutoScaling { namespace Model { ScalableTarget::ScalableTarget() : m_serviceNamespace(ServiceNamespace::NOT_SET), m_serviceNamespaceHasBeenSet(false), m_resourceIdHasBeenSet(false), m_scalableDimension(ScalableDimension::NOT_SET), m_scalableDimensionHasBeenSet(false), m_minCapacity(0), m_minCapacityHasBeenSet(false), m_maxCapacity(0), m_maxCapacityHasBeenSet(false), m_roleARNHasBeenSet(false), m_creationTimeHasBeenSet(false), m_suspendedStateHasBeenSet(false) { } ScalableTarget::ScalableTarget(JsonView jsonValue) : m_serviceNamespace(ServiceNamespace::NOT_SET), m_serviceNamespaceHasBeenSet(false), m_resourceIdHasBeenSet(false), m_scalableDimension(ScalableDimension::NOT_SET), m_scalableDimensionHasBeenSet(false), m_minCapacity(0), m_minCapacityHasBeenSet(false), m_maxCapacity(0), m_maxCapacityHasBeenSet(false), m_roleARNHasBeenSet(false), m_creationTimeHasBeenSet(false), m_suspendedStateHasBeenSet(false) { *this = jsonValue; } ScalableTarget& ScalableTarget::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("ServiceNamespace")) { m_serviceNamespace = ServiceNamespaceMapper::GetServiceNamespaceForName(jsonValue.GetString("ServiceNamespace")); m_serviceNamespaceHasBeenSet = true; } if(jsonValue.ValueExists("ResourceId")) { m_resourceId = jsonValue.GetString("ResourceId"); m_resourceIdHasBeenSet = true; } if(jsonValue.ValueExists("ScalableDimension")) { m_scalableDimension = ScalableDimensionMapper::GetScalableDimensionForName(jsonValue.GetString("ScalableDimension")); m_scalableDimensionHasBeenSet = true; } if(jsonValue.ValueExists("MinCapacity")) { m_minCapacity = jsonValue.GetInteger("MinCapacity"); m_minCapacityHasBeenSet = true; } if(jsonValue.ValueExists("MaxCapacity")) { m_maxCapacity = jsonValue.GetInteger("MaxCapacity"); m_maxCapacityHasBeenSet = true; } if(jsonValue.ValueExists("RoleARN")) { m_roleARN = jsonValue.GetString("RoleARN"); m_roleARNHasBeenSet = true; } if(jsonValue.ValueExists("CreationTime")) { m_creationTime = jsonValue.GetDouble("CreationTime"); m_creationTimeHasBeenSet = true; } if(jsonValue.ValueExists("SuspendedState")) { m_suspendedState = jsonValue.GetObject("SuspendedState"); m_suspendedStateHasBeenSet = true; } return *this; } JsonValue ScalableTarget::Jsonize() const { JsonValue payload; if(m_serviceNamespaceHasBeenSet) { payload.WithString("ServiceNamespace", ServiceNamespaceMapper::GetNameForServiceNamespace(m_serviceNamespace)); } if(m_resourceIdHasBeenSet) { payload.WithString("ResourceId", m_resourceId); } if(m_scalableDimensionHasBeenSet) { payload.WithString("ScalableDimension", ScalableDimensionMapper::GetNameForScalableDimension(m_scalableDimension)); } if(m_minCapacityHasBeenSet) { payload.WithInteger("MinCapacity", m_minCapacity); } if(m_maxCapacityHasBeenSet) { payload.WithInteger("MaxCapacity", m_maxCapacity); } if(m_roleARNHasBeenSet) { payload.WithString("RoleARN", m_roleARN); } if(m_creationTimeHasBeenSet) { payload.WithDouble("CreationTime", m_creationTime.SecondsWithMSPrecision()); } if(m_suspendedStateHasBeenSet) { payload.WithObject("SuspendedState", m_suspendedState.Jsonize()); } return payload; } } // namespace Model } // namespace ApplicationAutoScaling } // namespace Aws
24
121
0.750694
grujicbr
33333cf3e77058e549c76523d5837687bcf9d6fb
7,474
cpp
C++
KDIS/KDataStream.cpp
cdit-ma/kdis
f722221cee0e5ea6869f9e923ad1cdb93d5d289f
[ "BSD-2-Clause" ]
null
null
null
KDIS/KDataStream.cpp
cdit-ma/kdis
f722221cee0e5ea6869f9e923ad1cdb93d5d289f
[ "BSD-2-Clause" ]
null
null
null
KDIS/KDataStream.cpp
cdit-ma/kdis
f722221cee0e5ea6869f9e923ad1cdb93d5d289f
[ "BSD-2-Clause" ]
null
null
null
/********************************************************************* Copyright 2013 Karl Jones 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. 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. For Further Information Please Contact me at Karljj1@yahoo.com http://p.sf.net/kdis/UserGuide *********************************************************************/ #include "./KDataStream.h" using namespace KDIS; using namespace KDIS::UTILS; using namespace std; ////////////////////////////////////////////////////////////////////////// // public: ////////////////////////////////////////////////////////////////////////// KDataStream::KDataStream( Endian Network_Endian /*= Big_Endian*/ ) : m_NetEndian( Network_Endian ), m_ui16CurrentWritePos( 0 ) { if( IsMachineBigEndian() == true ) { m_MachineEndian = Big_Endian; } else { m_MachineEndian = Little_Endian; } } ////////////////////////////////////////////////////////////////////////// KDataStream::KDataStream( KOCTET * SerialData, KUINT16 DataSize, Endian Network_Endian /*= Big_Endian */ ) : m_NetEndian( Network_Endian ), m_ui16CurrentWritePos( 0 ) { // Copy Data into vector for( KUINT16 i = 0; i < DataSize; ++i ) { m_vBuffer.push_back( SerialData[i] ); } if( IsMachineBigEndian() == true ) { m_MachineEndian = Big_Endian; } else { m_MachineEndian = Little_Endian; } } ////////////////////////////////////////////////////////////////////////// KDataStream::~KDataStream() { } ////////////////////////////////////////////////////////////////////////// Endian KDataStream::GetMachineEndian() const { return m_MachineEndian; } ////////////////////////////////////////////////////////////////////////// Endian KDataStream::GetNetWorkEndian() const { return m_NetEndian; } ////////////////////////////////////////////////////////////////////////// KUINT16 KDataStream::GetBufferSize() const { return ( m_vBuffer.size() - m_ui16CurrentWritePos ); } ////////////////////////////////////////////////////////////////////////// KUINT16 KDataStream::CopyIntoBuffer( KOCTET * Buffer, KUINT16 BufferSize, KUINT16 WritePos /*= 0*/ ) const throw( KException ) { if( ( BufferSize - WritePos ) < ( KUINT16 )m_vBuffer.size() ) { throw KException( BUFFER_TOO_SMALL ); } vector<KUOCTET>::const_iterator citr = m_vBuffer.begin(); vector<KUOCTET>::const_iterator citrEnd = m_vBuffer.end(); KUINT16 CurrentWritePos = WritePos; for( ; citr != citrEnd; ++citr, ++CurrentWritePos ) { Buffer[CurrentWritePos] = *citr; } return m_vBuffer.size(); } ////////////////////////////////////////////////////////////////////////// void KDataStream::CopyFromBuffer( const KOCTET * SerialData, KUINT16 DataSize, Endian NetworkEndian /*= Big_Endian*/ ) { // Copy Data into vector for( KUINT16 i = 0; i < DataSize; ++i ) { m_vBuffer.push_back( SerialData[i] ); } } ////////////////////////////////////////////////////////////////////////// const KOCTET * KDataStream::GetBufferPtr() const { return ( const KOCTET* )&m_vBuffer[0]; } ////////////////////////////////////////////////////////////////////////// const vector<KUOCTET> & KDataStream::GetBuffer() const { return m_vBuffer; } ////////////////////////////////////////////////////////////////////////// void KDataStream::ResetWritePosition() { m_ui16CurrentWritePos = 0; } ////////////////////////////////////////////////////////////////////////// void KDataStream::SetCurrentWritePosition( KUINT16 WP ) { m_ui16CurrentWritePos = WP; } ////////////////////////////////////////////////////////////////////////// KUINT16 KDataStream::GetCurrentWritePosition() const { return m_ui16CurrentWritePos; } ////////////////////////////////////////////////////////////////////////// void KDataStream::Clear() { m_vBuffer.clear(); m_ui16CurrentWritePos = 0; } ////////////////////////////////////////////////////////////////////////// KString KDataStream::GetAsString() const { KStringStream ss; vector<KUOCTET>::const_iterator citr = m_vBuffer.begin(); vector<KUOCTET>::const_iterator citrEnd = m_vBuffer.end(); for( ; citr != citrEnd; ++citr ) { // If less than 10 add a zero so that each octet has the same 2 digit // representation. if( *citr < 10 )ss << "0"; ss << hex << ( KUINT16 )*citr << " "; } return ss.str(); } ////////////////////////////////////////////////////////////////////////// void KDataStream::ReadFromString( const KString & S ) { KStringStream ss( S ); KUINT16 o; while( ss >> hex >> o ) { m_vBuffer.push_back( o ); } } ////////////////////////////////////////////////////////////////////////// void KDataStream::Write( KUOCTET V ) { m_vBuffer.push_back( V ); } ////////////////////////////////////////////////////////////////////////// void KDataStream::Write( KOCTET V ) { m_vBuffer.push_back( V ); } ////////////////////////////////////////////////////////////////////////// void KDataStream::Read( KUOCTET & V ) { V = m_vBuffer[m_ui16CurrentWritePos++]; } ////////////////////////////////////////////////////////////////////////// void KDataStream::Read( KOCTET & V ) { V = m_vBuffer[m_ui16CurrentWritePos++]; } ////////////////////////////////////////////////////////////////////////// KDataStream & KDataStream::operator << ( KDataStream val ) { vector<KUOCTET>::const_iterator citr = val.m_vBuffer.begin(); vector<KUOCTET>::const_iterator citrEnd = val.m_vBuffer.end(); // Copy data into the buffer OCTET by OCTET for( ; citr != citrEnd; ++citr ) { m_vBuffer.push_back( *citr ); } return *this; } ////////////////////////////////////////////////////////////////////////// KBOOL KDataStream::operator == ( const KDataStream & Value ) const { if( m_vBuffer != Value.m_vBuffer ) return false; return true; } ////////////////////////////////////////////////////////////////////////// KBOOL KDataStream::operator != ( const KDataStream & Value ) const { return !( *this == Value ); } //////////////////////////////////////////////////////////////////////////
27.377289
127
0.500134
cdit-ma
33337503b14c67e7aa1c770bf6232b92fbcedabc
3,173
hpp
C++
include/move.hpp
bsamseth/Goldfish
c99cb9f2b14bbd04e0c2a9ae32b78e074ff6199b
[ "MIT" ]
6
2019-01-23T03:13:36.000Z
2020-09-06T09:54:48.000Z
include/move.hpp
bsamseth/Goldfish
c99cb9f2b14bbd04e0c2a9ae32b78e074ff6199b
[ "MIT" ]
33
2015-12-28T08:48:01.000Z
2019-09-25T11:39:53.000Z
include/move.hpp
bsamseth/Goldfish
c99cb9f2b14bbd04e0c2a9ae32b78e074ff6199b
[ "MIT" ]
6
2018-08-06T14:05:11.000Z
2022-02-15T01:30:49.000Z
#pragma once #include "movetype.hpp" #include "piece.hpp" #include "piecetype.hpp" #include "square.hpp" namespace goldfish { namespace Moves { constexpr int TYPE_SHIFT = 0; constexpr int TYPE_MASK = MoveTypes::MASK << TYPE_SHIFT; constexpr int ORIGIN_SQUARE_SHIFT = 3; constexpr int ORIGIN_SQUARE_MASK = Squares::MASK << ORIGIN_SQUARE_SHIFT; constexpr int TARGET_SQUARE_SHIFT = 10; constexpr int TARGET_SQUARE_MASK = Squares::MASK << TARGET_SQUARE_SHIFT; constexpr int ORIGIN_PIECE_SHIFT = 17; constexpr int ORIGIN_PIECE_MASK = Pieces::MASK << ORIGIN_PIECE_SHIFT; constexpr int TARGET_PIECE_SHIFT = 22; constexpr int TARGET_PIECE_MASK = Pieces::MASK << TARGET_PIECE_SHIFT; constexpr int PROMOTION_SHIFT = 27; constexpr int PROMOTION_MASK = PieceTypes::MASK << PROMOTION_SHIFT; } // namespace Moves /** * This class represents a move as a int value. The fields are represented by * the following bits. * <p/> * <code> 0 - 2</code>: type (required) * <code> 3 - 9</code>: origin square (required) * <code>10 - 16</code>: target square (required) * <code>17 - 21</code>: origin piece (required) * <code>22 - 26</code>: target piece (optional) * <code>27 - 29</code>: promotion type (optional) */ enum Move : int { NO_MOVE = (MoveType::NO_MOVE_TYPE << Moves::TYPE_SHIFT) | (Square::NO_SQUARE << Moves::ORIGIN_SQUARE_SHIFT) | (Square::NO_SQUARE << Moves::TARGET_SQUARE_SHIFT) | (Piece::NO_PIECE << Moves::ORIGIN_PIECE_SHIFT) | (Piece::NO_PIECE << Moves::TARGET_PIECE_SHIFT) | (PieceType::NO_PIECE_TYPE << Moves::PROMOTION_SHIFT) }; namespace Moves { constexpr bool is_valid(Move move) { return move != Move::NO_MOVE; } constexpr Move value_of(MoveType type, Square origin_square, Square target_square, Piece origin_piece, Piece target_piece, PieceType promotion) { int move = 0; move |= type << TYPE_SHIFT; move |= origin_square << ORIGIN_SQUARE_SHIFT; move |= target_square << TARGET_SQUARE_SHIFT; move |= origin_piece << ORIGIN_PIECE_SHIFT; move |= target_piece << TARGET_PIECE_SHIFT; move |= promotion << PROMOTION_SHIFT; return Move(move); } constexpr MoveType get_type(Move move) { return MoveType((move & TYPE_MASK) >> TYPE_SHIFT); } constexpr Square get_origin_square(Move move) { return Square((move & ORIGIN_SQUARE_MASK) >> ORIGIN_SQUARE_SHIFT); } constexpr Square get_target_square(Move move) { return Square((move & TARGET_SQUARE_MASK) >> TARGET_SQUARE_SHIFT); } constexpr Piece get_origin_piece(Move move) { return Piece((move & ORIGIN_PIECE_MASK) >> ORIGIN_PIECE_SHIFT); } constexpr Piece get_target_piece(Move move) { return Piece((move & TARGET_PIECE_MASK) >> TARGET_PIECE_SHIFT); } constexpr PieceType get_promotion(Move move) { return PieceType((move & PROMOTION_MASK) >> PROMOTION_SHIFT); } constexpr bool is_capture(Move m) { return get_target_piece(m) != Piece::NO_PIECE; } } // namespace Moves } // namespace goldfish
29.110092
77
0.676647
bsamseth
33338e281180f80868f3b7f4c494b65c0482c7b8
1,979
hpp
C++
src/estimation/ButterworthFilter.hpp
dakejahl/TeensyFlight3.6
da334100eaa42f82bf7f83f14bf5042397433ebd
[ "MIT" ]
17
2019-09-22T11:58:29.000Z
2022-03-16T03:13:14.000Z
src/estimation/ButterworthFilter.hpp
dakejahl/TeensyFlight3.6
da334100eaa42f82bf7f83f14bf5042397433ebd
[ "MIT" ]
11
2019-09-01T06:56:02.000Z
2020-04-29T11:46:25.000Z
src/estimation/ButterworthFilter.hpp
dakejahl/teensy36_customized
da334100eaa42f82bf7f83f14bf5042397433ebd
[ "MIT" ]
2
2020-01-20T09:57:15.000Z
2020-10-12T05:16:53.000Z
// MIT License // Copyright (c) 2019 Jacob Dahl // 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. #pragma once #include <cmath> // Second order butterworth filter class ButterworthFilter { public: ButterworthFilter(float sample_freq, float cutoff_freq) { // set initial parameters set_cutoff_frequency(sample_freq, cutoff_freq); } // Change filter parameters void set_cutoff_frequency(float sample_freq, float cutoff_freq); /** * Add a new raw value to the filter * * @return retrieve the filtered result */ float apply(float sample); // Return the cutoff frequency float get_cutoff_freq() const { return _cutoff_freq; } // Reset the filter state to this value float reset(float sample); private: float _cutoff_freq{0.0f}; float _a1{0.0f}; float _a2{0.0f}; float _b0{0.0f}; float _b1{0.0f}; float _b2{0.0f}; float _delay_element_1{0.0f}; // buffered sample -1 float _delay_element_2{0.0f}; // buffered sample -2 };
29.102941
81
0.748863
dakejahl
3338e39d62c0d3f9024b522efb11518c16cda176
2,573
cpp
C++
2015/14/main.cpp
adrian-stanciu/adventofcode
47b3d12226b0c71fff485ef140cd7731c9a5d72f
[ "MIT" ]
null
null
null
2015/14/main.cpp
adrian-stanciu/adventofcode
47b3d12226b0c71fff485ef140cd7731c9a5d72f
[ "MIT" ]
null
null
null
2015/14/main.cpp
adrian-stanciu/adventofcode
47b3d12226b0c71fff485ef140cd7731c9a5d72f
[ "MIT" ]
null
null
null
#include <algorithm> #include <iostream> #include <regex> #include <string> #include <vector> struct Reindeer { long speed; long flying_duration; long resting_duration; long cycle_duration; Reindeer(long speed, long flying_duration, long resting_duration) : speed(speed) , flying_duration(flying_duration) , resting_duration(resting_duration) , cycle_duration(flying_duration + resting_duration) {} auto distance_after(long t) const { auto num_completed_cycles = t / cycle_duration; auto remaining_duration = t % cycle_duration; auto total_flying_duration = num_completed_cycles * flying_duration; total_flying_duration += std::min(flying_duration, remaining_duration); return total_flying_duration * speed; } }; auto parse(const std::string& line) { static const std::regex re{"[a-zA-Z]+ can fly ([1-9][0-9]*) km/s for ([1-9][0-9]*) seconds, but then must rest for ([1-9][0-9]*) seconds."}; static const auto to_number = [] (const auto& s) { return strtol(s.data(), nullptr, 10); }; std::smatch matched; regex_match(line, matched, re); auto speed = to_number(matched[1].str()); auto flying_duration = to_number(matched[2].str()); auto resting_duration = to_number(matched[3].str()); return Reindeer{speed, flying_duration, resting_duration}; } auto max_distance_after(const std::vector<Reindeer>& reindeers, long t) { auto max_dist = 0L; for (const auto& r : reindeers) max_dist = std::max(max_dist, r.distance_after(t)); return max_dist; } auto max_points_after(const std::vector<Reindeer>& reindeers, long t) { std::vector<long> distances(reindeers.size(), 0); std::vector<long> points(reindeers.size(), 0); for (auto i = 1; i <= t; ++i) { transform(reindeers.begin(), reindeers.end(), distances.begin(), [&] (const auto& r) { return r.distance_after(i); }); auto max_dist = *max_element(distances.begin(), distances.end()); transform(distances.begin(), distances.end(), points.begin(), points.begin(), [&] (const auto& d, const auto& p) { return p + (d == max_dist ? 1 : 0); }); } return *max_element(points.begin(), points.end()); } int main() { std::vector<Reindeer> reindeers; std::string line; while (getline(std::cin, line)) reindeers.push_back(parse(line)); std::cout << max_distance_after(reindeers, 2503) << "\n"; std::cout << max_points_after(reindeers, 2503) << "\n"; return 0; }
27.967391
144
0.647882
adrian-stanciu
333942a730724d50cb03a147c0f0b02f250a3c1a
607
cpp
C++
src/util/MetricResetter.cpp
tangchain/tang-core
b112fc43f7df6153406810fc0ffb6676418d20c8
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSL-1.0", "BSD-3-Clause" ]
null
null
null
src/util/MetricResetter.cpp
tangchain/tang-core
b112fc43f7df6153406810fc0ffb6676418d20c8
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSL-1.0", "BSD-3-Clause" ]
null
null
null
src/util/MetricResetter.cpp
tangchain/tang-core
b112fc43f7df6153406810fc0ffb6676418d20c8
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSL-1.0", "BSD-3-Clause" ]
null
null
null
// Copyright 2018 Stellar Development Foundation and contributors. Licensed // under the Apache License, Version 2.0. See the COPYING file at the root // of this distribution or at http://www.apache.org/licenses/LICENSE-2.0 #include "MetricResetter.h" namespace tang { void MetricResetter::Process(medida::Counter& counter) { counter.clear(); } void MetricResetter::Process(medida::Meter& meter) { // Meter has no "clear" method } void MetricResetter::Process(medida::Histogram& histogram) { histogram.Clear(); } void MetricResetter::Process(medida::Timer& timer) { timer.Clear(); } }
17.852941
75
0.729819
tangchain
33406282fb9e979e26e578f4f54eac7a8a9508a9
12,055
cpp
C++
be/src/olap/column_vector.cpp
stgztsw/incubator-doris
f622ce0497bea35e05bc67708e15d7eb2f271f3a
[ "Apache-2.0" ]
1
2022-03-09T03:37:21.000Z
2022-03-09T03:37:21.000Z
be/src/olap/column_vector.cpp
stgztsw/incubator-doris
f622ce0497bea35e05bc67708e15d7eb2f271f3a
[ "Apache-2.0" ]
null
null
null
be/src/olap/column_vector.cpp
stgztsw/incubator-doris
f622ce0497bea35e05bc67708e15d7eb2f271f3a
[ "Apache-2.0" ]
null
null
null
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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 "column_vector.h" #include "olap/field.h" namespace doris { ColumnVectorBatch::~ColumnVectorBatch() = default; Status ColumnVectorBatch::resize(size_t new_cap) { if (_nullable) { _null_signs.resize(new_cap); } _capacity = new_cap; return Status::OK(); } Status ColumnVectorBatch::create(size_t init_capacity, bool is_nullable, std::shared_ptr<const TypeInfo> type_info, Field* field, std::unique_ptr<ColumnVectorBatch>* column_vector_batch) { if (is_scalar_type(type_info->type())) { std::unique_ptr<ColumnVectorBatch> local; switch (type_info->type()) { case OLAP_FIELD_TYPE_BOOL: local.reset(new ScalarColumnVectorBatch<CppTypeTraits<OLAP_FIELD_TYPE_BOOL>::CppType>( type_info, is_nullable)); break; case OLAP_FIELD_TYPE_TINYINT: local.reset( new ScalarColumnVectorBatch<CppTypeTraits<OLAP_FIELD_TYPE_TINYINT>::CppType>( type_info, is_nullable)); break; case OLAP_FIELD_TYPE_SMALLINT: local.reset( new ScalarColumnVectorBatch<CppTypeTraits<OLAP_FIELD_TYPE_SMALLINT>::CppType>( type_info, is_nullable)); break; case OLAP_FIELD_TYPE_INT: local.reset(new ScalarColumnVectorBatch<CppTypeTraits<OLAP_FIELD_TYPE_INT>::CppType>( type_info, is_nullable)); break; case OLAP_FIELD_TYPE_UNSIGNED_INT: local.reset(new ScalarColumnVectorBatch< CppTypeTraits<OLAP_FIELD_TYPE_UNSIGNED_INT>::CppType>(type_info, is_nullable)); break; case OLAP_FIELD_TYPE_BIGINT: local.reset(new ScalarColumnVectorBatch<CppTypeTraits<OLAP_FIELD_TYPE_BIGINT>::CppType>( type_info, is_nullable)); break; case OLAP_FIELD_TYPE_UNSIGNED_BIGINT: local.reset(new ScalarColumnVectorBatch< CppTypeTraits<OLAP_FIELD_TYPE_UNSIGNED_BIGINT>::CppType>(type_info, is_nullable)); break; case OLAP_FIELD_TYPE_LARGEINT: local.reset( new ScalarColumnVectorBatch<CppTypeTraits<OLAP_FIELD_TYPE_LARGEINT>::CppType>( type_info, is_nullable)); break; case OLAP_FIELD_TYPE_FLOAT: local.reset(new ScalarColumnVectorBatch<CppTypeTraits<OLAP_FIELD_TYPE_FLOAT>::CppType>( type_info, is_nullable)); break; case OLAP_FIELD_TYPE_DOUBLE: local.reset(new ScalarColumnVectorBatch<CppTypeTraits<OLAP_FIELD_TYPE_DOUBLE>::CppType>( type_info, is_nullable)); break; case OLAP_FIELD_TYPE_DECIMAL: local.reset( new ScalarColumnVectorBatch<CppTypeTraits<OLAP_FIELD_TYPE_DECIMAL>::CppType>( type_info, is_nullable)); break; case OLAP_FIELD_TYPE_DATE: local.reset(new ScalarColumnVectorBatch<CppTypeTraits<OLAP_FIELD_TYPE_DATE>::CppType>( type_info, is_nullable)); break; case OLAP_FIELD_TYPE_DATETIME: local.reset( new ScalarColumnVectorBatch<CppTypeTraits<OLAP_FIELD_TYPE_DATETIME>::CppType>( type_info, is_nullable)); break; case OLAP_FIELD_TYPE_CHAR: local.reset(new ScalarColumnVectorBatch<CppTypeTraits<OLAP_FIELD_TYPE_CHAR>::CppType>( type_info, is_nullable)); break; case OLAP_FIELD_TYPE_VARCHAR: local.reset( new ScalarColumnVectorBatch<CppTypeTraits<OLAP_FIELD_TYPE_VARCHAR>::CppType>( type_info, is_nullable)); break; case OLAP_FIELD_TYPE_STRING: local.reset(new ScalarColumnVectorBatch<CppTypeTraits<OLAP_FIELD_TYPE_STRING>::CppType>( type_info, is_nullable)); break; case OLAP_FIELD_TYPE_HLL: local.reset(new ScalarColumnVectorBatch<CppTypeTraits<OLAP_FIELD_TYPE_HLL>::CppType>( type_info, is_nullable)); break; case OLAP_FIELD_TYPE_OBJECT: local.reset(new ScalarColumnVectorBatch<CppTypeTraits<OLAP_FIELD_TYPE_OBJECT>::CppType>( type_info, is_nullable)); break; default: return Status::NotSupported("unsupported type for ColumnVectorBatch: " + std::to_string(type_info->type())); } RETURN_IF_ERROR(local->resize(init_capacity)); *column_vector_batch = std::move(local); return Status::OK(); } else { switch (type_info->type()) { case FieldType::OLAP_FIELD_TYPE_ARRAY: { if (field == nullptr) { return Status::NotSupported( "When create ArrayColumnVectorBatch, `Field` is indispensable"); } std::unique_ptr<ColumnVectorBatch> elements; auto array_type_info = dynamic_cast<const ArrayTypeInfo*>(type_info.get()); RETURN_IF_ERROR(ColumnVectorBatch::create( init_capacity * 2, field->get_sub_field(0)->is_nullable(), array_type_info->item_type_info(), field->get_sub_field(0), &elements)); std::unique_ptr<ColumnVectorBatch> offsets; auto offsets_type_info = get_scalar_type_info(FieldType::OLAP_FIELD_TYPE_UNSIGNED_INT); RETURN_IF_ERROR(ColumnVectorBatch::create(init_capacity + 1, false, offsets_type_info, nullptr, &offsets)); std::unique_ptr<ColumnVectorBatch> local(new ArrayColumnVectorBatch( type_info, is_nullable, reinterpret_cast<ScalarColumnVectorBatch<uint32_t>*>(offsets.release()), elements.release())); RETURN_IF_ERROR(local->resize(init_capacity)); *column_vector_batch = std::move(local); return Status::OK(); } default: return Status::NotSupported("unsupported type for ColumnVectorBatch: " + std::to_string(type_info->type())); } } } template <class ScalarType> ScalarColumnVectorBatch<ScalarType>::ScalarColumnVectorBatch(std::shared_ptr<const TypeInfo> type_info, bool is_nullable) : ColumnVectorBatch(type_info, is_nullable), _data(0) {} template <class ScalarType> ScalarColumnVectorBatch<ScalarType>::~ScalarColumnVectorBatch() = default; template <class ScalarType> Status ScalarColumnVectorBatch<ScalarType>::resize(size_t new_cap) { if (capacity() < new_cap) { // before first init, _capacity is 0. RETURN_IF_ERROR(ColumnVectorBatch::resize(new_cap)); _data.resize(new_cap); } return Status::OK(); } ArrayColumnVectorBatch::ArrayColumnVectorBatch(std::shared_ptr<const TypeInfo> type_info, bool is_nullable, ScalarColumnVectorBatch<uint32_t>* offsets, ColumnVectorBatch* elements) : ColumnVectorBatch(type_info, is_nullable), _data(0) { _offsets.reset(offsets); *(_offsets->scalar_cell_ptr(0)) = 0; _elements.reset(elements); } ArrayColumnVectorBatch::~ArrayColumnVectorBatch() = default; Status ArrayColumnVectorBatch::resize(size_t new_cap) { if (capacity() < new_cap) { RETURN_IF_ERROR(ColumnVectorBatch::resize(new_cap)); _data.resize(new_cap); _offsets->resize(new_cap + 1); } return Status::OK(); } void ArrayColumnVectorBatch::get_offset_by_length(size_t start_idx, size_t size) { DCHECK(start_idx >= 0); DCHECK(start_idx + size < _offsets->capacity()); for (size_t i = start_idx; i < start_idx + size; ++i) { *(_offsets->scalar_cell_ptr(i + 1)) = *(_offsets->scalar_cell_ptr(i)) + *(_offsets->scalar_cell_ptr(i + 1)); } } void ArrayColumnVectorBatch::prepare_for_read(size_t start_idx, size_t size, bool item_has_null) { DCHECK(start_idx + size <= capacity()); for (size_t i = 0; i < size; ++i) { if (!is_null_at(start_idx + i)) { _data[start_idx + i] = CollectionValue( _elements->mutable_cell_ptr(*(_offsets->scalar_cell_ptr(start_idx + i))), *(_offsets->scalar_cell_ptr(start_idx + i + 1)) - *(_offsets->scalar_cell_ptr(start_idx + i)), item_has_null, _elements->is_nullable() ? const_cast<bool*>(&_elements->null_signs()[*( _offsets->scalar_cell_ptr(start_idx + i))]) : nullptr); } } } template <class T> DataBuffer<T>::DataBuffer(size_t new_size) : buf(nullptr), current_size(0), current_capacity(0) { resize(new_size); } template <class T> DataBuffer<T>::~DataBuffer() { for (uint64_t i = current_size; i > 0; --i) { (buf + i - 1)->~T(); } if (buf) { std::free(buf); } } template <class T> void DataBuffer<T>::resize(size_t new_size) { if (new_size > current_capacity || !buf) { if (buf) { T* buf_old = buf; buf = reinterpret_cast<T*>(std::malloc(sizeof(T) * new_size)); memcpy(buf, buf_old, sizeof(T) * current_size); std::free(buf_old); } else { buf = reinterpret_cast<T*>(std::malloc(sizeof(T) * new_size)); } current_capacity = new_size; } current_size = new_size; } template class DataBuffer<bool>; template class DataBuffer<int8_t>; template class DataBuffer<int16_t>; template class DataBuffer<int32_t>; template class DataBuffer<uint32_t>; template class DataBuffer<int64_t>; template class DataBuffer<uint64_t>; template class DataBuffer<int128_t>; template class DataBuffer<float>; template class DataBuffer<double>; template class DataBuffer<decimal12_t>; template class DataBuffer<uint24_t>; template class DataBuffer<Slice>; template class DataBuffer<CollectionValue>; template class ScalarColumnVectorBatch<bool>; template class ScalarColumnVectorBatch<int8_t>; template class ScalarColumnVectorBatch<int16_t>; template class ScalarColumnVectorBatch<int32_t>; template class ScalarColumnVectorBatch<uint32_t>; template class ScalarColumnVectorBatch<int64_t>; template class ScalarColumnVectorBatch<uint64_t>; template class ScalarColumnVectorBatch<int128_t>; template class ScalarColumnVectorBatch<float>; template class ScalarColumnVectorBatch<double>; template class ScalarColumnVectorBatch<decimal12_t>; template class ScalarColumnVectorBatch<uint24_t>; template class ScalarColumnVectorBatch<Slice>; } // namespace doris
42.15035
115
0.624637
stgztsw
3340762e762e7f0220a3c5b2abeaccb21c930924
4,435
cpp
C++
src/luaruntime/LuaRuntime.cpp
Dreae/SourceLua
5737eaf3d77bbd715b258df78ab101265890662c
[ "Apache-2.0" ]
null
null
null
src/luaruntime/LuaRuntime.cpp
Dreae/SourceLua
5737eaf3d77bbd715b258df78ab101265890662c
[ "Apache-2.0" ]
null
null
null
src/luaruntime/LuaRuntime.cpp
Dreae/SourceLua
5737eaf3d77bbd715b258df78ab101265890662c
[ "Apache-2.0" ]
null
null
null
#include "luaruntime/LuaRuntime.hpp" #include "luaruntime/lualibs/Server.hpp" #include "luaruntime/lualibs/Curl.hpp" LuaRuntime g_LuaRuntime; LuaRuntime::LuaRuntime() { L = luaL_newstate(); this->basePath = new char[PATH_MAX]; } void LuaRuntime::OnPluginStart() { const char *gameDir = g_SMAPI->GetBaseDir(); g_SMAPI->PathFormat(this->basePath, PATH_MAX, "%s/addons/sourcelua/lua/?.lua", gameDir); lua_gc(L, LUA_GCSTOP, 0); luaL_openlibs(L); lua_gc(L, LUA_GCRESTART, 0); luaJIT_setmode(L, 0, LUAJIT_MODE_ENGINE | LUAJIT_MODE_ON); // Update lua require path lua_getglobal(L, "package"); lua_pushstring(L, this->basePath); lua_setfield(L, -2, "path"); lua_remove(L, -1); this->register_std_lib(); } int LuaPrint(lua_State *L) { if(lua_gettop(L)) { if(!lua_isstring(L, 1)) { lua_getglobal(L, "tostring"); lua_pushvalue(L, 1); lua_call(L, 1, 1); } g_SMAPI->ConPrintf("%s\n", lua_tostring(L, -1)); } return 0; } int lua_traceback (lua_State *L) { if (!lua_isstring(L, 1)) /* 'message' not a string? */ return 1; /* keep it intact */ lua_getfield(L, LUA_GLOBALSINDEX, "debug"); if (!lua_istable(L, -1)) { lua_pop(L, 1); return 1; } lua_getfield(L, -1, "traceback"); if (!lua_isfunction(L, -1)) { lua_pop(L, 2); return 1; } lua_pushvalue(L, 1); /* pass error message */ lua_pushinteger(L, 2); /* skip this function and traceback */ lua_call(L, 2, 1); /* call debug.traceback */ return 1; } inline int lua_docall(lua_State *L, int nargs, int ret) { int base = lua_gettop(L) - nargs; lua_pushcfunction(L, lua_traceback); lua_insert(L, base); int status = lua_pcall(L, nargs, ret, base); if(status) { META_LOG(g_PLAPI, "Error loading addon: %s", lua_tostring(L, -1)); } lua_remove(L, base); return status; } void LuaRuntime::register_std_lib() { lua_register(L, "print", LuaPrint); lua_getglobal(L, "require"); lua_pushstring(L, "sourcelua"); lua_call(L, 1, 1); lua_setglobal(L, "SourceLua"); //Save gameDir const char* gameDir = g_SMAPI->GetBaseDir(); lua_getglobal(L, "SourceLua"); lua_pushstring(L, gameDir); lua_setfield(L, -2, "BaseDir"); char slDir[PATH_MAX]; strcpy(slDir, g_plPath); slDir[strlen(slDir) - 4] = 0; // Chop of /bin #FIXME: Find better way? lua_pushstring(L, slDir); lua_setfield(L, -2, "SourceLuaDir"); lua_register_Server(L); lua_register_Curl(L); } void LuaRuntime::LoadAddons() { FileFindHandle_t findHandle; const char *filename = g_iFileSystem->FindFirstEx("addons/sourcelua/addons/*.*", "MOD", &findHandle); while(filename) { char addonDir[PATH_MAX]; char indexFile[PATH_MAX]; g_SMAPI->PathFormat(addonDir, PATH_MAX, "addons/sourcelua/addons/%s", filename); g_SMAPI->PathFormat(indexFile, PATH_MAX, "%s/index.lua", addonDir); if(g_iFileSystem->FileExists(indexFile)) { this->LoadAddon(addonDir); } filename = g_iFileSystem->FindNext(findHandle); } } void LuaRuntime::LoadAddon(const char *addonDir) { this->lua_chroot(addonDir, [this]() -> void { // #TODO: Create addon context for per-addon managers lua_getglobal(this->L, "require"); lua_pushstring(this->L, "index"); lua_docall(this->L, 1, 1); }); } void LuaRuntime::lua_chroot(const char *addonDir, std::function<void(void)> f) { char path[PATH_MAX * 2]; g_SMAPI->PathFormat(path, PATH_MAX * 2, "%s;%s/%s/?.lua", this->basePath, g_SMAPI->GetBaseDir(), addonDir); lua_getglobal(this->L, "package"); lua_pushstring(this->L, path); lua_setfield(this->L, -2, "path"); lua_remove(this->L, -1); f(); lua_getglobal(this->L, "package"); lua_pushstring(this->L, this->basePath); lua_setfield(this->L, -2, "path"); lua_remove(this->L, -1); } META_RES LuaRuntime::FireClientCommand(int client, const CCommand args) { lua_getglobal(this->L, "SourceLua"); lua_getfield(this->L, -1, "Events"); lua_remove(this->L, -2); lua_getfield(this->L, -1, "FireClientCommand"); lua_remove(this->L, -2); lua_pushinteger(this->L, client); lua_createtable(this->L, args.ArgC(), 0); for(int i = 1; i <= args.ArgC(); i++) { lua_pushstring(this->L, args.Arg(i - 1)); lua_rawseti(this->L, -2, i); } if(lua_pcall(this->L, 2, 1, 0)) { META_LOG(g_PLAPI, "Error firing client command: %s", lua_tostring(this->L, -1)); return MRES_IGNORED; } return (META_RES)lua_tointeger(this->L, -1); }
27.71875
109
0.660203
Dreae
33415069ea6176d20da69d149d1e6ae99054abc0
136
cpp
C++
src/examples/04_module/01_bank/checking_account.cpp
acc-cosc-1337-fall-2019/acc-cosc-1337-fall-2019-HienVuong-1337
d3ea38455829954cd558b8a1c1aa70416d50efd0
[ "MIT" ]
null
null
null
src/examples/04_module/01_bank/checking_account.cpp
acc-cosc-1337-fall-2019/acc-cosc-1337-fall-2019-HienVuong-1337
d3ea38455829954cd558b8a1c1aa70416d50efd0
[ "MIT" ]
null
null
null
src/examples/04_module/01_bank/checking_account.cpp
acc-cosc-1337-fall-2019/acc-cosc-1337-fall-2019-HienVuong-1337
d3ea38455829954cd558b8a1c1aa70416d50efd0
[ "MIT" ]
null
null
null
//checking_account.cpp #include "checking_account.h" int CheckingAccount::get_balance() const { return BankAccount::get_balance(); }
15.111111
40
0.772059
acc-cosc-1337-fall-2019